: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): implement invoiceninja import source (#67820)
Tom Owersc133a45a690b
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 15e6370692a3..710833b6a859 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -181,6 +181,7 @@ the row lists both.| incident_io | HTTP | requests | ✅ || insightly | HTTP | requests | ✅ || intercom | HTTP | requests + `rest_source.RESTClient` | ✅ |+| invoiceninja | HTTP | requests | ✅ || ip2whois | HTTP | requests | ✅ || iterable | HTTP | requests | ✅ || jira | HTTP | requests | ✅ |@@ -483,7 +484,6 @@ doesn't conflict with concurrent PRs.- interzoid- intruder- invoiced-- invoiceninja- jamf_pro- jobber- jobnimbusdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex a6f8f1f54a2e..7d19518ed1e1 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@@ -1663,7 +1663,8 @@ class InvoicedSourceConfig(config.Config):@config.configclass InvoiceninjaSourceConfig(config.Config):- pass+ api_token: str+ base_url: str | None = None@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/canonical_descriptions.pynew file mode 100644index 000000000000..e56fdb77ca8f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/canonical_descriptions.py@@ -0,0 +1,199 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++_DOCS_URL = "https://api-docs.invoicing.co"++# Curated, docs-sourced descriptions for Invoice Ninja's core tables. Columns not covered here fall+# back to LLM enrichment. Timestamps (`created_at`, `updated_at`, `archived_at`) are integer unix+# seconds across every resource.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "clients": {+ "description": "A customer you invoice. Contacts are nested under each client as a `contacts` array.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the client.",+ "name": "The client's business or display name.",+ "balance": "Outstanding amount the client currently owes across all invoices.",+ "paid_to_date": "Total amount the client has paid to date.",+ "credit_balance": "Unapplied credit currently available to the client.",+ "contacts": "Array of the client's contacts (name, email, phone).",+ "is_deleted": "Whether the client has been soft-deleted.",+ "created_at": "Unix timestamp (seconds) when the client was created.",+ "updated_at": "Unix timestamp (seconds) when the client was last updated.",+ },+ },+ "invoices": {+ "description": "A bill sent to a client, with line items, totals, and payment status.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the invoice.",+ "client_id": "Identifier of the client the invoice was issued to.",+ "number": "Human-readable invoice number.",+ "status_id": "Lifecycle status of the invoice (draft, sent, partial, paid, etc.).",+ "amount": "Total amount of the invoice.",+ "balance": "Amount still outstanding on the invoice.",+ "paid_to_date": "Amount paid against the invoice so far.",+ "date": "Invoice date (YYYY-MM-DD).",+ "due_date": "Date the invoice is due (YYYY-MM-DD).",+ "line_items": "Array of line items on the invoice.",+ "is_deleted": "Whether the invoice has been soft-deleted.",+ "created_at": "Unix timestamp (seconds) when the invoice was created.",+ "updated_at": "Unix timestamp (seconds) when the invoice was last updated.",+ },+ },+ "quotes": {+ "description": "A proposal sent to a client that can be converted into an invoice.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the quote.",+ "client_id": "Identifier of the client the quote was issued to.",+ "number": "Human-readable quote number.",+ "status_id": "Lifecycle status of the quote (draft, sent, approved, etc.).",+ "amount": "Total amount of the quote.",+ "date": "Quote date (YYYY-MM-DD).",+ "invoice_id": "Identifier of the invoice this quote was converted into, if any.",+ "created_at": "Unix timestamp (seconds) when the quote was created.",+ },+ },+ "credits": {+ "description": "A credit note reducing what a client owes.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the credit.",+ "client_id": "Identifier of the client the credit belongs to.",+ "number": "Human-readable credit number.",+ "amount": "Total amount of the credit.",+ "balance": "Remaining unapplied balance on the credit.",+ "created_at": "Unix timestamp (seconds) when the credit was created.",+ },+ },+ "payments": {+ "description": "A payment recorded against one or more invoices.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the payment.",+ "client_id": "Identifier of the client who made the payment.",+ "amount": "Amount of the payment.",+ "refunded": "Amount of the payment that has been refunded.",+ "applied": "Amount of the payment applied to invoices.",+ "date": "Date the payment was made (YYYY-MM-DD).",+ "type_id": "Payment method used (bank transfer, credit card, etc.).",+ "transaction_reference": "External reference for the payment transaction.",+ "created_at": "Unix timestamp (seconds) when the payment was recorded.",+ },+ },+ "recurring_invoices": {+ "description": "A template that automatically generates invoices on a schedule.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the recurring invoice.",+ "client_id": "Identifier of the client billed by the recurring invoice.",+ "frequency_id": "How often invoices are generated (weekly, monthly, etc.).",+ "amount": "Amount of each generated invoice.",+ "next_send_date": "Date the next invoice will be generated (YYYY-MM-DD).",+ "remaining_cycles": "Number of invoices left to generate (-1 for unlimited).",+ "created_at": "Unix timestamp (seconds) when the recurring invoice was created.",+ },+ },+ "products": {+ "description": "A reusable catalog item that can be added to invoices and quotes.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the product.",+ "product_key": "Short code / SKU for the product.",+ "notes": "Description of the product.",+ "price": "Default unit price of the product.",+ "cost": "Cost of the product.",+ "created_at": "Unix timestamp (seconds) when the product was created.",+ },+ },+ "expenses": {+ "description": "A business expense, optionally billable to a client.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the expense.",+ "client_id": "Identifier of the client the expense is billable to, if any.",+ "vendor_id": "Identifier of the vendor the expense was paid to.",+ "category_id": "Identifier of the expense category.",+ "amount": "Amount of the expense.",+ "date": "Date the expense was incurred (YYYY-MM-DD).",+ "created_at": "Unix timestamp (seconds) when the expense was created.",+ },+ },+ "expense_categories": {+ "description": "A category used to classify expenses.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the expense category.",+ "name": "Name of the category.",+ "created_at": "Unix timestamp (seconds) when the category was created.",+ },+ },+ "vendors": {+ "description": "A supplier you pay. Contacts are nested under each vendor as a `contacts` array.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the vendor.",+ "name": "The vendor's business or display name.",+ "contacts": "Array of the vendor's contacts (name, email, phone).",+ "created_at": "Unix timestamp (seconds) when the vendor was created.",+ },+ },+ "purchase_orders": {+ "description": "An order sent to a vendor to purchase goods or services.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the purchase order.",+ "vendor_id": "Identifier of the vendor the purchase order was sent to.",+ "number": "Human-readable purchase order number.",+ "amount": "Total amount of the purchase order.",+ "status_id": "Lifecycle status of the purchase order.",+ "created_at": "Unix timestamp (seconds) when the purchase order was created.",+ },+ },+ "projects": {+ "description": "A project used to group tasks and expenses for a client.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the project.",+ "client_id": "Identifier of the client the project belongs to.",+ "name": "Name of the project.",+ "budgeted_hours": "Budgeted hours for the project.",+ "task_rate": "Default hourly rate for tasks on the project.",+ "created_at": "Unix timestamp (seconds) when the project was created.",+ },+ },+ "tasks": {+ "description": "A unit of tracked work, often billed by time, belonging to a project or client.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the task.",+ "client_id": "Identifier of the client the task belongs to.",+ "project_id": "Identifier of the project the task belongs to.",+ "description": "Description of the work.",+ "time_log": "JSON-encoded array of start/stop time entries for the task.",+ "rate": "Hourly rate applied to the task.",+ "created_at": "Unix timestamp (seconds) when the task was created.",+ },+ },+ "tax_rates": {+ "description": "A named tax rate applied to invoice and quote line items.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the tax rate.",+ "name": "Name of the tax rate.",+ "rate": "Percentage rate applied.",+ "created_at": "Unix timestamp (seconds) when the tax rate was created.",+ },+ },+ "payment_terms": {+ "description": "A reusable net payment term (e.g. Net 30) offered to clients.",+ "docs_url": _DOCS_URL,+ "columns": {+ "id": "Unique identifier for the payment term.",+ "num_days": "Number of days until payment is due.",+ "created_at": "Unix timestamp (seconds) when the payment term was created.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/invoiceninja.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/invoiceninja.pynew file mode 100644index 000000000000..96ea249630f9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/invoiceninja.py@@ -0,0 +1,322 @@+"""Invoice Ninja transport layer.++Invoice Ninja is an open-source invoicing / billing platform offered both as the hosted SaaS+(``https://invoicing.co``) and self-hosted (a customer-supplied host), so the API base URL must be+configurable. Auth is a single ``X-API-TOKEN`` header; every request must also carry+``X-Requested-With: XMLHttpRequest`` (the API rejects requests without it) and be made over HTTPS.++List endpoints are page-number paginated (``page`` / ``per_page``) and wrap their records under a+top-level ``data`` key alongside a ``meta.pagination`` object that reports ``current_page`` and+``total_pages``.++Every stream is full-refresh. Invoice Ninja documents ``created_at`` / ``updated_at`` filters on its+index endpoints, but the timestamps are integer unix seconds and the ordering the API applies under+those filters could not be verified against the live API without a token — an unverified sort order+risks a corrupted incremental watermark on a mid-sync shutdown. Incremental sync can be layered on+per endpoint once its server-side filter and sort behaviour are verified with real credentials.+"""++import re+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import requests+from structlog.types import FilteringBoundLogger+from tenacity import RetryCallState, 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.common.mixins import _is_host_safe+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.settings import (+ INVOICENINJA_ENDPOINTS,+ InvoiceNinjaEndpointConfig,+)++DEFAULT_API_HOST = "https://invoicing.co"+API_VERSION_PATH = "/api/v1"++REQUEST_TIMEOUT_SECONDS = 60+MAX_RETRIES = 5+MAX_RETRY_AFTER_SECONDS = 60++HOST_NOT_ALLOWED_ERROR = "Invoice Ninja API URL is not allowed"+HTTP_NOT_ALLOWED_ERROR = "Invoice Ninja API URL must use HTTPS"+++class InvoiceNinjaRetryableError(Exception):+ def __init__(self, message: str, retry_after: float | None = None) -> None:+ super().__init__(message)+ self.retry_after = retry_after+++class InvoiceNinjaHostNotAllowedError(Exception):+ pass+++class InvoiceNinjaResumeConfig:+ # The next page to fetch on resume. Persisted after each page is yielded, so a crash before this+ # write leaves the previous value in place and the last page is re-yielded (merge dedupes on `id`).+ next_page: int+++def normalize_base_url(base_url: Optional[str]) -> str:+ """Turn whatever the user typed into a ``<scheme>://<host>/api/v1`` base URL.++ Blank → the hosted Invoice Ninja SaaS. Accepts bare hosts (``invoices.example.com``), full URLs+ with or without a scheme, and values that already include the ``/api/v1`` suffix.+ """+ raw = (base_url or "").strip()+ if not raw:+ raw = DEFAULT_API_HOST+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):+ raw = f"https://{raw}"+ raw = raw.rstrip("/")+ # Drop a trailing version segment the user may have pasted in, then re-add the version we target.+ raw = re.sub(r"/api/v\d+$", "", raw)+ return f"{raw}{API_VERSION_PATH}"+++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 token rides in the X-API-TOKEN header, so refuse plaintext HTTP to keep an on-path+ # attacker from capturing it. Invoice Ninja mandates HTTPS anyway (HTTP requests fail).+ return urlparse(base_url).scheme == "https"+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "X-API-TOKEN": api_token,+ # Invoice Ninja rejects API requests that omit this header.+ "X-Requested-With": "XMLHttpRequest",+ "Accept": "application/json",+ }+++def _is_invalid_token(response: requests.Response) -> bool:+ """A 403 from Invoice Ninja means a bad token — its body reads ``{"message": "Invalid token"}``.++ Enterprise plans can also restrict a token to a subset of entities, which surfaces as a 403 without+ that message; those are treated as a missing permission rather than a bad token.+ """+ try:+ message = (response.json() or {}).get("message", "")+ except Exception:+ message = response.text or ""+ return "invalid token" in message.lower()+++def validate_credentials(+ base_url: Optional[str], api_token: str, schema_name: Optional[str] = None, team_id: Optional[int] = None+) -> tuple[bool, str | None]:+ """Probe a cheap list endpoint to confirm the API token is genuine.++ A bad Invoice Ninja token returns 403 ``{"message": "Invalid token"}``, so — unlike sources whose+ 403 means "valid token, missing scope" — a 403 carrying that message is always a hard failure. A+ 403 *without* it (an entity-restricted enterprise token) is accepted at source-create and only+ rejected for a scoped probe.+ """+ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)++ if not host:+ return False, "Invalid Invoice Ninja API URL"++ # The host is fully customer-controlled for self-hosted deployments, 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++ # Refuse plaintext HTTP before the token-bearing request goes out, so a self-hosted URL can't+ # expose the API token on the network.+ if not _is_https(resolved_base_url):+ return False, HTTP_NOT_ALLOWED_ERROR++ url = f"{resolved_base_url}/clients?{urlencode({'per_page': 1, 'page': 1})}"+ try:+ # `redact_values` masks the token from captured HTTP samples: it rides in the `X-API-TOKEN`+ # header, which the transport's name-based denylist doesn't recognise. Don't follow redirects:+ # the validated host could 3xx to an internal address, defeating the host check above (SSRF).+ session = make_tracked_session(redact_values=(api_token,))+ response = session.get(url, headers=_get_headers(api_token), timeout=10, allow_redirects=False)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.is_redirect or response.is_permanent_redirect:+ return False, HOST_NOT_ALLOWED_ERROR++ if response.status_code == 200:+ return True, None++ if response.status_code == 401:+ return False, "Invalid Invoice Ninja API token"++ if response.status_code == 403:+ if _is_invalid_token(response):+ return False, "Invalid Invoice Ninja API token"+ if schema_name is None:+ # Valid token, restricted to a subset of entities — let source creation through.+ return True, None+ return False, "Your Invoice Ninja API token lacks permission for this endpoint"++ try:+ body = response.json()+ return False, body.get("message", response.text)+ except Exception:+ return False, response.text+++def _parse_retry_after(response: requests.Response) -> float | None:+ """Honor a whole-second ``Retry-After`` on 429. HTTP-date forms are ignored."""+ raw = response.headers.get("Retry-After")+ if raw and raw.strip().isdigit():+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)+ return None+++def _retry_wait(retry_state: RetryCallState) -> float:+ """Use a server-provided Retry-After when present, else exponential backoff."""+ exc = retry_state.outcome.exception() if retry_state.outcome else None+ if isinstance(exc, InvoiceNinjaRetryableError) and exc.retry_after is not None:+ return exc.retry_after+ return wait_exponential_jitter(initial=1, max=30)(retry_state)+++def get_rows(+ base_url: Optional[str],+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InvoiceNinjaResumeConfig],+ team_id: int,+) -> Iterator[list[dict[str, Any]]]:+ config: InvoiceNinjaEndpointConfig = INVOICENINJA_ENDPOINTS[endpoint]+ resolved_base_url = normalize_base_url(base_url)+ host = _host_of(resolved_base_url)++ # Re-check at run time (not just at source-create) in case the URL was edited or now resolves 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 InvoiceNinjaHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)++ # Refuse plaintext HTTP before the token is used, so the token is never sent in the clear.+ if not _is_https(resolved_base_url):+ raise InvoiceNinjaHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)++ headers = _get_headers(api_token)+ request_url = f"{resolved_base_url}{config.path}"++ # One session reused across every page (and retry) so urllib3 keeps the connection alive. It+ # redacts the token from captured HTTP samples — the token rides in the `X-API-TOKEN` header, which+ # the transport's name-based denylist doesn't recognise, so value-based masking is what covers it.+ session = make_tracked_session(redact_values=(api_token,))++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ page = resume_config.next_page if resume_config is not None else 1+ if resume_config is not None:+ logger.debug(f"Invoice Ninja: resuming {endpoint} from page {page}")++ @retry(+ retry=retry_if_exception_type((InvoiceNinjaRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(MAX_RETRIES),+ wait=_retry_wait,+ reraise=True,+ )+ def fetch_page(page_number: int) -> requests.Response:+ query = urlencode({"page": page_number, "per_page": config.page_size})+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address,+ # bypassing the host validation done before the request (SSRF).+ response = session.get(+ f"{request_url}?{query}", headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False+ )++ if response.status_code == 429 or response.status_code >= 500:+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None+ raise InvoiceNinjaRetryableError(+ f"Invoice Ninja API error (retryable): status={response.status_code}, url={request_url}",+ retry_after=retry_after,+ )++ # A 3xx isn't an error status (`response.ok` is True), so reject it explicitly rather than+ # silently parsing the redirect body as data.+ if response.is_redirect or response.is_permanent_redirect:+ raise InvoiceNinjaHostNotAllowedError(+ f"Invoice Ninja API returned an unexpected redirect (status={response.status_code}); "+ "refusing to follow it"+ )++ if not response.ok:+ logger.error(+ f"Invoice Ninja API error: status={response.status_code}, body={response.text}, url={request_url}"+ )+ response.raise_for_status()++ return response++ while True:+ response = fetch_page(page)+ body = response.json()+ rows = body.get("data") or []+ if not isinstance(rows, list) or not rows:+ break++ yield rows++ # Invoice Ninja wraps its Laravel/Fractal paginator under `meta.pagination`, reporting the+ # current/total page count and a `links.next` URL that is null on the last page. Treat either+ # signal as "more pages remain". If the pagination block is missing entirely (never the case+ # for a healthy index endpoint), stop rather than risk an unbounded loop.+ pagination = (body.get("meta") or {}).get("pagination") or {}+ current_page = pagination.get("current_page")+ total_pages = pagination.get("total_pages")+ has_next_link = bool((pagination.get("links") or {}).get("next"))+ more_by_count = bool(current_page and total_pages and int(current_page) < int(total_pages))+ if not (more_by_count or has_next_link):+ break+ page = (int(current_page) + 1) if current_page else page + 1++ # Checkpoint AFTER yielding the page: a crash before this write re-yields the page on resume+ # (dedupes on the primary key), while a crash after it resumes at the next page.+ resumable_source_manager.save_state(InvoiceNinjaResumeConfig(next_page=page))+++def invoiceninja_source(+ base_url: Optional[str],+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[InvoiceNinjaResumeConfig],+ team_id: int,+) -> SourceResponse:+ config = INVOICENINJA_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ base_url=base_url,+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ team_id=team_id,+ ),+ primary_keys=[config.primary_key],+ # Full-refresh replace: no incremental cursor is enabled, so there is no watermark to+ # checkpoint. Invoice Ninja returns `created_at` / `updated_at` as integer unix seconds rather+ # than datetimes, so datetime partitioning isn't applied — see the module docstring.+ sort_mode="asc",+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/settings.pynew file mode 100644index 000000000000..58797ef51223--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/settings.py@@ -0,0 +1,54 @@+from dataclasses import dataclass, field++from products.warehouse_sources.backend.types import IncrementalField++# Invoice Ninja defaults `per_page` to 20 and accepts larger values; 100 keeps request counts low+# without risking the larger-payload timeouts seen on very high page sizes.+DEFAULT_PAGE_SIZE = 100+++@dataclass+class InvoiceNinjaEndpointConfig:+ name: str+ # Path appended to the API base (which already ends in `/api/v1`).+ path: str+ # Invoice Ninja index endpoints wrap their records under a top-level `data` key alongside a+ # `meta.pagination` object. The key is uniform across every list endpoint.+ primary_key: str = "id"+ page_size: int = DEFAULT_PAGE_SIZE+ should_sync_default: bool = True+ # Invoice Ninja documents server-side `created_at` / `updated_at` filters on its index endpoints,+ # but the timestamps it returns are integer unix seconds (not datetimes), and the ordering the API+ # applies when those filters are set could not be verified against the live API without a token.+ # An incremental cursor whose sort order we can't confirm risks a corrupted watermark on a mid-sync+ # shutdown, so every stream ships full-refresh only for now. Left empty deliberately — incremental+ # can be layered on per endpoint once the filter + sort behaviour is verified with real credentials.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++# Top-level index endpoints that return a full collection without requiring a parent resource id as a+# filter. Client and vendor contacts arrive embedded in their parent objects (Invoice Ninja nests a+# `contacts` array on each client/vendor), so they are captured without a dedicated fan-out endpoint.+INVOICENINJA_ENDPOINTS: dict[str, InvoiceNinjaEndpointConfig] = {+ "clients": InvoiceNinjaEndpointConfig(name="clients", path="/clients"),+ "credits": InvoiceNinjaEndpointConfig(name="credits", path="/credits"),+ "expense_categories": InvoiceNinjaEndpointConfig(name="expense_categories", path="/expense_categories"),+ "expenses": InvoiceNinjaEndpointConfig(name="expenses", path="/expenses"),+ "invoices": InvoiceNinjaEndpointConfig(name="invoices", path="/invoices"),+ "payments": InvoiceNinjaEndpointConfig(name="payments", path="/payments"),+ "payment_terms": InvoiceNinjaEndpointConfig(name="payment_terms", path="/payment_terms"),+ "products": InvoiceNinjaEndpointConfig(name="products", path="/products"),+ "projects": InvoiceNinjaEndpointConfig(name="projects", path="/projects"),+ "purchase_orders": InvoiceNinjaEndpointConfig(name="purchase_orders", path="/purchase_orders"),+ "quotes": InvoiceNinjaEndpointConfig(name="quotes", path="/quotes"),+ "recurring_invoices": InvoiceNinjaEndpointConfig(name="recurring_invoices", path="/recurring_invoices"),+ "tasks": InvoiceNinjaEndpointConfig(name="tasks", path="/tasks"),+ "tax_rates": InvoiceNinjaEndpointConfig(name="tax_rates", path="/tax_rates"),+ "vendors": InvoiceNinjaEndpointConfig(name="vendors", path="/vendors"),+}++ENDPOINTS = tuple(INVOICENINJA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in INVOICENINJA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/source.pyindex 6276d49f0db4..6cfe3b9b8724 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/source.py@@ -1,30 +1,150 @@-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.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+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.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InvoiceninjaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.invoiceninja import (+ HOST_NOT_ALLOWED_ERROR,+ HTTP_NOT_ALLOWED_ERROR,+ InvoiceNinjaResumeConfig,+ invoiceninja_source,+ validate_credentials as validate_invoiceninja_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ INVOICENINJA_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class InvoiceninjaSource(SimpleSource[InvoiceninjaSourceConfig]):+class InvoiceninjaSource(ResumableSource[InvoiceninjaSourceConfig, InvoiceNinjaResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.INVOICENINJA+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` is where the stored API token is sent; retargeting it must re-require the token.+ return ["base_url"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Invalid Invoice Ninja API token. Generate a new token in Settings > Account Management > Integrations > API tokens and reconnect.",+ "403 Client Error": "Your Invoice Ninja API token is invalid or lacks permission for this data. Check the token and try again.",+ HOST_NOT_ALLOWED_ERROR: "The Invoice Ninja API URL is not allowed. Please use a publicly reachable host.",+ HTTP_NOT_ALLOWED_ERROR: "The Invoice Ninja API URL must use HTTPS. Please update the API URL to use https://.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: InvoiceninjaSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=INVOICENINJA_ENDPOINTS[endpoint].should_sync_default,+ )+ 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: InvoiceninjaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_invoiceninja_credentials(config.base_url, config.api_token, schema_name, team_id)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[InvoiceNinjaResumeConfig]:+ return ResumableSourceManager[InvoiceNinjaResumeConfig](inputs, InvoiceNinjaResumeConfig)++ def source_for_pipeline(+ self,+ config: InvoiceninjaSourceConfig,+ resumable_source_manager: ResumableSourceManager[InvoiceNinjaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return invoiceninja_source(+ base_url=config.base_url,+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ team_id=inputs.team_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.INVOICENINJA,category=DataWarehouseSourceCategory.FINANCE___ACCOUNTING,- label="Invoiceninja",- iconPath="/static/services/invoiceninja.png",- fields=cast(list[FieldType], []),+ label="Invoice Ninja",+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ keywords=["invoice ninja", "invoicing", "billing"],+ caption="""Enter your Invoice Ninja API token to pull your invoicing data into the PostHog Data warehouse.++You can create an API token in Invoice Ninja under **Settings > Account Management > Integrations > API tokens**.++Self-hosted users should set the API URL to their own Invoice Ninja host (for example `https://invoices.example.com`). Leave it blank to use the hosted Invoice Ninja (`https://invoicing.co`).""",+ iconPath="/static/services/invoiceninja.png",+ docsUrl="https://posthog.com/docs/cdp/sources/invoiceninja",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="base_url",+ label="API URL (self-hosted only)",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="https://invoicing.co",+ secret=False,+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja.pynew file mode 100644index 000000000000..1c7806f9efad--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja.py@@ -0,0 +1,367 @@+from typing import Any+from urllib.parse import parse_qs, urlparse++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja import (+ invoiceninja as invoiceninja_module,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.invoiceninja import (+ InvoiceNinjaHostNotAllowedError,+ InvoiceNinjaResumeConfig,+ get_rows,+ invoiceninja_source,+ normalize_base_url,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.settings import (+ INVOICENINJA_ENDPOINTS,+)+++def _response(*, status_code: int = 200, json_data: Any = None, text: str = "") -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 400+ response.is_redirect = status_code in (301, 302, 303, 307, 308)+ response.is_permanent_redirect = status_code in (301, 308)+ response.text = text+ response.json.return_value = json_data+ response.headers = {}+ return response+++def _page(rows: list[dict[str, Any]], *, current_page: int, total_pages: int) -> mock.MagicMock:+ return _response(+ json_data={"data": rows, "meta": {"pagination": {"current_page": current_page, "total_pages": total_pages}}}+ )+++class TestNormalizeBaseUrl:+ @pytest.mark.parametrize(+ "raw, expected",+ [+ (None, "https://invoicing.co/api/v1"),+ ("", "https://invoicing.co/api/v1"),+ (" ", "https://invoicing.co/api/v1"),+ ("https://invoicing.co", "https://invoicing.co/api/v1"),+ ("https://invoicing.co/", "https://invoicing.co/api/v1"),+ ("https://invoicing.co/api/v1", "https://invoicing.co/api/v1"),+ ("invoices.example.com", "https://invoices.example.com/api/v1"),+ ("http://invoices.example.com/", "http://invoices.example.com/api/v1"),+ ("https://invoices.example.com/api/v5", "https://invoices.example.com/api/v1"),+ ],+ )+ def test_normalize(self, raw, expected):+ assert normalize_base_url(raw) == expected+++class TestHostOf:+ @pytest.mark.parametrize(+ "url, expected_host",+ [+ ("https://invoices.example.com/api/v1", "invoices.example.com"),+ # Backslash (and its %5c encoding) is userinfo to urlparse but a path separator to+ # requests/urllib3 — the host must reflect the address the request actually reaches, or+ # the SSRF check validates a decoy host while the token goes elsewhere.+ ("https://127.0.0.1\\@example.com/api/v1", "127.0.0.1"),+ ("https://127.0.0.1%[email protected]/api/v1", "127.0.0.1"),+ ("https://127.0.0.1%[email protected]/api/v1", "127.0.0.1"),+ ],+ )+ def test_host_reflects_real_connect_target(self, url, expected_host):+ assert invoiceninja_module._host_of(url) == expected_host+++class TestValidateCredentials:+ def _patch_session(self, response=None, raises=None):+ session = mock.MagicMock()+ if raises is not None:+ session.get.side_effect = raises+ else:+ session.get.return_value = response+ return mock.patch.object(invoiceninja_module, "make_tracked_session", return_value=session)++ def test_success(self):+ with self._patch_session(_response(status_code=200)):+ assert validate_credentials(None, "tok") == (True, None)++ def test_invalid_token_401(self):+ with self._patch_session(_response(status_code=401)):+ valid, msg = validate_credentials(None, "tok")+ assert valid is False+ assert msg == "Invalid Invoice Ninja API token"++ def test_invalid_token_403_message_always_fails(self):+ # A bad Invoice Ninja token returns 403 {"message": "Invalid token"} — reject it even at create.+ response = _response(status_code=403, json_data={"message": "Invalid token"})+ with self._patch_session(response):+ valid, msg = validate_credentials(None, "tok", schema_name=None)+ assert valid is False+ assert msg == "Invalid Invoice Ninja API token"++ def test_permission_403_at_source_create_is_accepted(self):+ # A 403 without the "Invalid token" message is a restricted (enterprise) token, not a bad one.+ response = _response(status_code=403, json_data={"message": "This action is unauthorized."})+ with self._patch_session(response):+ assert validate_credentials(None, "tok", schema_name=None) == (True, None)++ def test_permission_403_for_scoped_probe_fails(self):+ response = _response(status_code=403, json_data={"message": "This action is unauthorized."})+ with self._patch_session(response):+ valid, msg = validate_credentials(None, "tok", schema_name="invoices")+ assert valid is False+ assert msg is not None++ def test_request_exception_returns_failure(self):+ import requests++ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):+ valid, msg = validate_credentials(None, "tok")+ assert valid is False+ assert "boom" in (msg or "")++ def test_rejects_redirect_response(self):+ with self._patch_session(_response(status_code=302)) as patched:+ valid, msg = validate_credentials(None, "tok")+ assert valid is False+ assert msg == invoiceninja_module.HOST_NOT_ALLOWED_ERROR+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False++ def test_blocks_unsafe_host(self):+ with (+ mock.patch.object(invoiceninja_module, "_is_host_safe", return_value=(False, "internal address")),+ self._patch_session(_response(status_code=200)) as patched,+ ):+ valid, msg = validate_credentials("http://10.0.0.1", "tok", team_id=99)+ assert valid is False+ assert msg == "internal address"+ patched.return_value.get.assert_not_called()++ def test_probe_hits_configured_host_with_required_headers(self):+ with self._patch_session(_response(status_code=200)) as patched:+ validate_credentials("https://invoices.example.com", "tok")+ call = patched.return_value.get.call_args+ assert call.args[0].startswith("https://invoices.example.com/api/v1/clients")+ headers = call.kwargs["headers"]+ assert headers["X-API-TOKEN"] == "tok"+ assert headers["X-Requested-With"] == "XMLHttpRequest"++ def test_redacts_token_in_telemetry(self):+ # The token rides in X-API-TOKEN, which the transport's name-based scrubber doesn't cover, so+ # it must be passed as a redact value to keep it out of captured HTTP samples.+ with self._patch_session(_response(status_code=200)) as patched:+ validate_credentials(None, "tok")+ assert patched.call_args.kwargs["redact_values"] == ("tok",)++ def test_rejects_plaintext_http_before_sending_token(self):+ # A plaintext http:// URL would expose the X-API-TOKEN on the wire, so reject it without+ # ever issuing the token-bearing request.+ with self._patch_session(_response(status_code=200)) as patched:+ valid, msg = validate_credentials("http://invoices.example.com", "tok")+ assert valid is False+ assert msg == invoiceninja_module.HTTP_NOT_ALLOWED_ERROR+ patched.return_value.get.assert_not_called()+++class TestInvoiceNinjaSourceResponse:+ @pytest.mark.parametrize("endpoint", list(INVOICENINJA_ENDPOINTS.keys()))+ def test_response_shape(self, endpoint):+ response = invoiceninja_source(+ base_url=None,+ api_token="tok",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(),+ team_id=1,+ )+ assert response.name == endpoint+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"+ # Integer unix timestamps aren't datetime-partitionable, so no partitioning is applied.+ assert response.partition_keys is None+ assert response.partition_mode is None+++class TestGetRows:+ def _run(self, manager, responses, team_id=1, base_url=None):+ session = mock.MagicMock()+ session.get.side_effect = responses+ with mock.patch.object(invoiceninja_module, "make_tracked_session", return_value=session):+ rows: list[dict[str, Any]] = []+ for batch in get_rows(+ base_url=base_url,+ api_token="tok",+ endpoint="clients",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=team_id,+ ):+ rows.extend(batch)+ return rows, session++ def test_paginates_via_meta_pagination(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _page([{"id": "1"}, {"id": "2"}], current_page=1, total_pages=2)+ page2 = _page([{"id": "3"}], current_page=2, total_pages=2)+ rows, session = self._run(manager, [page1, page2])++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ first_qs = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)+ second_qs = parse_qs(urlparse(session.get.call_args_list[1].args[0]).query)+ assert first_qs["page"] == ["1"]+ assert second_qs["page"] == ["2"]++ def test_saves_next_page_after_yielding(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _page([{"id": "1"}], current_page=1, total_pages=2)+ page2 = _page([{"id": "2"}], current_page=2, total_pages=2)+ self._run(manager, [page1, page2])++ # State is saved once (after page 1, pointing at page 2); the last page is terminal.+ assert manager.save_state.call_count == 1+ saved = manager.save_state.call_args.args[0]+ assert isinstance(saved, InvoiceNinjaResumeConfig)+ assert saved.next_page == 2++ def test_resumes_from_saved_state(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = True+ manager.load_state.return_value = InvoiceNinjaResumeConfig(next_page=3)+ rows, session = self._run(manager, [_page([{"id": "9"}], current_page=3, total_pages=3)])++ first_qs = parse_qs(urlparse(session.get.call_args_list[0].args[0]).query)+ assert first_qs["page"] == ["3"]+ assert [r["id"] for r in rows] == ["9"]++ def test_paginates_via_links_next_when_page_counts_absent(self):+ # Some deployments only expose `links.next` without current/total page counts.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ page1 = _response(+ json_data={"data": [{"id": "1"}], "meta": {"pagination": {"links": {"next": "https://next"}}}}+ )+ page2 = _response(json_data={"data": [{"id": "2"}], "meta": {"pagination": {"links": {"next": None}}}})+ rows, session = self._run(manager, [page1, page2])+ assert [r["id"] for r in rows] == ["1", "2"]+ assert session.get.call_count == 2+ second_qs = parse_qs(urlparse(session.get.call_args_list[1].args[0]).query)+ assert second_qs["page"] == ["2"]++ def test_empty_page_terminates(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ rows, session = self._run(manager, [_page([], current_page=1, total_pages=5)])+ assert rows == []+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_missing_pagination_terminates_after_first_page(self):+ # A response with no pagination block must not loop forever.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ rows, session = self._run(manager, [_response(json_data={"data": [{"id": "1"}]})])+ assert [r["id"] for r in rows] == ["1"]+ assert session.get.call_count == 1+ manager.save_state.assert_not_called()++ def test_does_not_follow_redirects(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with pytest.raises(InvoiceNinjaHostNotAllowedError):+ self._run(manager, [_response(status_code=302)])++ def test_passes_allow_redirects_false(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ _rows, session = self._run(manager, [_page([{"id": "1"}], current_page=1, total_pages=1)])+ assert session.get.call_args.kwargs["allow_redirects"] is False++ def test_sends_required_headers(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ _rows, session = self._run(manager, [_page([{"id": "1"}], current_page=1, total_pages=1)])+ headers = session.get.call_args.kwargs["headers"]+ assert headers["X-API-TOKEN"] == "tok"+ assert headers["X-Requested-With"] == "XMLHttpRequest"++ def test_redacts_token_in_telemetry(self):+ # The token rides in X-API-TOKEN, which the transport's name-based scrubber doesn't cover, so+ # it must be passed as a redact value to keep it out of captured HTTP samples.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ session = mock.MagicMock()+ session.get.side_effect = [_page([{"id": "1"}], current_page=1, total_pages=1)]+ with mock.patch.object(invoiceninja_module, "make_tracked_session", return_value=session) as mts:+ list(+ get_rows(+ base_url=None,+ api_token="tok",+ endpoint="clients",+ logger=mock.MagicMock(),+ resumable_source_manager=manager,+ team_id=1,+ )+ )+ assert mts.call_args.kwargs["redact_values"] == ("tok",)++ def test_raises_when_host_not_allowed(self):+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with mock.patch.object(invoiceninja_module, "_is_host_safe", return_value=(False, "internal address")):+ with pytest.raises(InvoiceNinjaHostNotAllowedError):+ self._run(manager, [_page([{"id": "1"}], current_page=1, total_pages=1)])++ def test_raises_on_plaintext_http(self):+ # A plaintext http:// URL must fail before the token-bearing request goes out.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ with pytest.raises(InvoiceNinjaHostNotAllowedError):+ self._run(+ manager, [_page([{"id": "1"}], current_page=1, total_pages=1)], base_url="http://invoices.example.com"+ )++ @pytest.mark.parametrize("status_code", [429, 503])+ def test_retries_retryable_status_then_succeeds(self, status_code):+ # End-to-end: a retryable status raises, tenacity retries, and the subsequent 200 yields rows.+ manager = mock.MagicMock()+ manager.can_resume.return_value = False+ responses = [_response(status_code=status_code), _page([{"id": "r1"}], current_page=1, total_pages=1)]+ with mock.patch.object(invoiceninja_module, "_retry_wait", return_value=0):+ rows, session = self._run(manager, responses)+ assert [r["id"] for r in rows] == ["r1"]+ assert session.get.call_count == 2+++class TestRetryAfter:+ @pytest.mark.parametrize(+ "header, expected",+ [+ ({"Retry-After": "5"}, 5.0),+ ({"Retry-After": " 9 "}, 9.0),+ ({"Retry-After": "100000"}, 60.0),+ ({"Retry-After": "Wed, 21 Oct 2025 07:28:00 GMT"}, None),+ ({}, None),+ ],+ )+ def test_parse_retry_after(self, header, expected):+ from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.invoiceninja import (+ _parse_retry_after,+ )++ response = mock.MagicMock()+ response.headers = header+ assert _parse_retry_after(response) == expected++ def test_retry_wait_prefers_retry_after(self):+ from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.invoiceninja import (+ InvoiceNinjaRetryableError,+ _retry_wait,+ )++ state = mock.MagicMock()+ state.outcome.exception.return_value = InvoiceNinjaRetryableError("rate limited", retry_after=7.0)+ assert _retry_wait(state) == 7.0diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja_source.pynew file mode 100644index 000000000000..2bb94d1f496a--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/invoiceninja/tests/test_invoiceninja_source.py@@ -0,0 +1,132 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import InvoiceninjaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.invoiceninja import (+ InvoiceNinjaResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.source import InvoiceninjaSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestInvoiceninjaSource:+ def setup_method(self):+ self.source = InvoiceninjaSource()+ self.team_id = 123+ self.config = InvoiceninjaSourceConfig(api_token="tok", base_url=None)++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.INVOICENINJA++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Invoiceninja"+ assert config.label == "Invoice Ninja"+ assert config.unreleasedSource is True+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/invoiceninja.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/invoiceninja"++ field_names = [f.name for f in config.fields]+ assert field_names == ["api_token", "base_url"]++ api_token_field, base_url_field = config.fields+ assert isinstance(api_token_field, SourceFieldInputConfig)+ assert api_token_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_token_field.secret is True+ assert api_token_field.required is True++ assert isinstance(base_url_field, SourceFieldInputConfig)+ assert base_url_field.type == SourceFieldInputConfigType.TEXT+ assert base_url_field.secret is False+ assert base_url_field.required is False++ def test_connection_host_fields_force_secret_reentry(self):+ # The API token is sent to base_url, so retargeting it must re-require the token.+ assert self.source.connection_host_fields == ["base_url"]++ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])+ def test_non_retryable_errors(self, expected_key):+ assert expected_key in self.source.get_non_retryable_errors()++ def test_get_schemas_returns_all_endpoints(self):+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_schemas_are_full_refresh(self):+ # Incremental is deferred until the server-side filter + sort order are verified against the+ # live API, so every stream ships full-refresh only.+ schemas = self.source.get_schemas(self.config, self.team_id)+ 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):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["invoices"])+ assert len(schemas) == 1+ assert schemas[0].name == "invoices"++ def test_get_schemas_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials(self):+ # Static endpoint catalog with no I/O, so the public docs can render the table list.+ assert self.source.lists_tables_without_credentials is True+ tables = self.source.get_documented_tables()+ assert {t["name"] for t in tables} == set(ENDPOINTS)++ @pytest.mark.parametrize(+ "mock_return, expected",+ [+ ((True, None), (True, None)),+ ((False, "Invalid Invoice Ninja API token"), (False, "Invalid Invoice Ninja API token")),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.source.validate_invoiceninja_credentials"+ )+ def test_validate_credentials(self, mock_validate, mock_return, expected):+ mock_validate.return_value = mock_return++ result = self.source.validate_credentials(self.config, self.team_id, schema_name="invoices")++ assert result == expected+ mock_validate.assert_called_once_with(self.config.base_url, self.config.api_token, "invoices", self.team_id)++ def test_get_resumable_source_manager(self):+ inputs = mock.MagicMock()+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is InvoiceNinjaResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.invoiceninja.source.invoiceninja_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_invoiceninja_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "invoices"+ inputs.team_id = 42+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_invoiceninja_source.assert_called_once()+ kwargs = mock_invoiceninja_source.call_args.kwargs+ assert kwargs["base_url"] == self.config.base_url+ assert kwargs["api_token"] == "tok"+ assert kwargs["endpoint"] == "invoices"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["team_id"] == 42++ def test_canonical_descriptions_cover_core_tables(self):+ descriptions = self.source.get_canonical_descriptions()+ # Curated docs only describe endpoints we actually expose.+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "clients" in descriptions+ assert "invoices" in descriptions+ assert "payments" in descriptions