Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement the fintoc import source (#108633)

Tom Owers5d15fe283cfc
diff --git a/frontend/public/services/fintoc.png b/frontend/public/services/fintoc.png
new file mode 100644
index 000000000000..53bb05e2f9d1
Binary files /dev/null and b/frontend/public/services/fintoc.png differ
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 99c18ab81c87..322d5410b6ca 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5427,7 +5427,7 @@ snapshots:
lemon-ui-object-tags--editable-tags-in-narrow-container--dark:
hash: v1.k794b7964.6538590671c5bcd8feb77e0400c8532705932f4f55856dd6a99a6abcdc00b6e3.ca3qOKbmxmRDrNfdNRCEg9I9Wvnkrs7PHzA0tvpXTIM
lemon-ui-object-tags--editable-tags-in-narrow-container--light:
- hash: v1.k794b7964.8b8f244a4387d0d1165067851b5758f5ad5429fae2b4a4e87eb7c53cdfdd4e18.MekQJYDe11n-5XnhJV5phxqMh5OqTw36CTFCk_BZNnw
+ hash: v1.k794b7964.330caf8c02373e4eb6a97b073a8170893c946ad83305df0421765c7e099b23da.5pN6LxPRYe8fKoDKZCP2DmT-NdHSF2YZB7T_c9VXerI
lemon-ui-object-tags--static-only--dark:
hash: v1.k794b7964.62481a20890d8d9702570d58b69f47580c91399daa635cab23d9e8da75d2636f.oAaWHdceTRTQOchqDXvZ7-ym0DB_CpRpPyXnqlKugwo
lemon-ui-object-tags--static-only--light:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 0046089c03c9..19e71b98febb 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -301,6 +301,7 @@ the row lists both.
| financial_modelling | HTTP | requests | ✅ |
| finnhub | HTTP | requests | ✅ |
| finnworlds | HTTP | requests | ✅ |
+| fintoc | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |
| firebase | HTTP | requests + `pyjwt` | ✅ |
| firecrawl | HTTP | requests | ✅ |
| fireworks_ai | HTTP | requests | ✅ |
@@ -1055,7 +1056,6 @@ doesn't conflict with concurrent PRs.
- fieldwire
- filevine
- finout
-- fintoc
- firebolt
- five9
- flagsmith
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/canonical_descriptions.py
new file mode 100644
index 000000000000..6b2cdf1d2d25
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/canonical_descriptions.py
@@ -0,0 +1,61 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "payment_intents": {
+ "description": "Payment attempts and their current status.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/payment-intents/payment-intents-list",
+ "columns": {"id": "Payment intent identifier.", "created_at": "Time the payment intent was created."},
+ },
+ "transfers": {
+ "description": "Inbound and outbound transfers for the organization.",
+ "docs_url": "https://docs.fintoc.com/api/business-accounts-api/transfers/transfers-list",
+ "columns": {"id": "Transfer identifier.", "direction": "Whether the transfer is inbound or outbound."},
+ },
+ "refunds": {
+ "description": "Refunds of payments, including their disbursement status.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/refunds/refunds-list",
+ "columns": {"id": "Refund identifier.", "resource_id": "Identifier of the refunded payment."},
+ },
+ "charges": {
+ "description": "Legacy direct debit collections against subscriptions.",
+ "docs_url": "https://docs.fintoc.com/api/direct-debit-legacy/charges/charges-list",
+ "columns": {"id": "Charge identifier.", "created_at": "Time the charge was created."},
+ },
+ "checkout_sessions": {
+ "description": "Checkout sessions for payments, subscriptions, or payment method setup.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/checkout-sessions/checkout-sessions-list",
+ "columns": {"id": "Checkout session identifier.", "created_at": "Time the session was created."},
+ },
+ "subscriptions": {
+ "description": "Recurring payment subscriptions with their subscription items.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/subscriptions/subscriptions-list",
+ "columns": {"id": "Subscription identifier."},
+ },
+ "invoices": {
+ "description": "Customer invoices, including invoices generated by subscriptions.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/invoices/invoices-list",
+ "columns": {"id": "Invoice identifier.", "created_at": "Time the invoice was created."},
+ },
+ "customers": {
+ "description": "Customers registered with the organization for payments and billing.",
+ "docs_url": "https://docs.fintoc.com/api/payments-api/customers/customers-list",
+ "columns": {"id": "Customer identifier.", "created_at": "Time the customer was created."},
+ },
+ "links": {
+ "description": "Bank connections and their refresh status. Listing links does not expose their access tokens or accounts.",
+ "docs_url": "https://docs.fintoc.com/api/movements-api/links/links-list",
+ "columns": {"id": "Link identifier.", "last_time_refreshed": "Time the link was last refreshed."},
+ },
+ "accounts": {
+ "description": "Open-banking accounts accessible through the configured link tokens.",
+ "docs_url": "https://docs.fintoc.com/api/movements-api/accounts/accounts-list",
+ "columns": {"id": "Bank account identifier."},
+ },
+ "movements": {
+ "description": "Bank account transactions, including unconfirmed movements, from the configured links.",
+ "docs_url": "https://docs.fintoc.com/api/movements-api/movements/movements-list",
+ "columns": {"id": "Movement identifier.", "post_date": "Date the bank posts the movement."},
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/fintoc.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/fintoc.py
new file mode 100644
index 000000000000..4f50a30d7426
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/fintoc.py
@@ -0,0 +1,343 @@
+import hashlib
+from collections.abc import Iterator
+from typing import TYPE_CHECKING, Any
+from urllib.parse import parse_qsl, quote, urlencode, urlsplit, urlunsplit
+
+from requests import HTTPError
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+)
+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.rest_source import (
+ rest_api_resource,
+ rest_api_resources,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+ RESTAPIConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.settings import (
+ AUTH_ERROR,
+ BASE_URL,
+ ENDPOINTS,
+ LINK_TOKEN_ERROR,
+ PERMISSION_ERROR,
+)
+
+if TYPE_CHECKING:
+ import pyarrow as pa
+
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
+
+@frozen
+class FintocResumeState:
+ paginator: dict[str, Any] | None = None
+ complete: bool = False
+
+
+def parse_link_tokens(value: str | None) -> list[str]:
+ return list(dict.fromkeys((value or "").replace(",", " ").split()))
+
+
+def _without_link_token(state: dict[str, Any]) -> dict[str, Any]:
+ result = dict(state)
+ if result.get("next_url"):
+ parts = urlsplit(result["next_url"])
+ query = urlencode([(key, value) for key, value in parse_qsl(parts.query) if key != "link_token"])
+ result["next_url"] = urlunsplit(parts._replace(query=query))
+ if result.get("child_state"):
+ result["child_state"] = _without_link_token(result["child_state"])
+ return result
+
+
+class FintocAPI:
+ def __init__(self, api_key: str, api_version: str) -> None:
+ self.api_key = api_key
+ self.api_version = api_version
+
+ def client_config(self, link_token: str | None = None) -> ClientConfig:
+ headers = {"Fintoc-Version": self.api_version, "Accept": "application/json"}
+ if link_token:
+ # Query auth reapplies the token on every page, including sanitized resume URLs.
+ headers["Authorization"] = self.api_key
+ return {
+ "base_url": BASE_URL,
+ "headers": headers,
+ "auth": {
+ "type": "api_key",
+ "name": "link_token" if link_token else "Authorization",
+ "location": "query" if link_token else "header",
+ "api_key": link_token or self.api_key,
+ },
+ "session": make_tracked_session(redact_values=(self.api_key, link_token or ""), capture=False),
+ "paginator": "header_link",
+ "allowed_hosts": ["api.fintoc.com"],
+ "allow_redirects": False,
+ "request_timeout": (10, 60),
+ }
+
+ def validate_credentials(self, schema_name: str | None, link_tokens: list[str]) -> tuple[bool, str | None]:
+ name = schema_name or "links"
+ if name not in ENDPOINTS:
+ return False, "Unknown Fintoc table. Select a supported table."
+ if ENDPOINTS[name].requires_link_token and not link_tokens:
+ return False, LINK_TOKEN_ERROR
+ tokens: list[str | None] = list(link_tokens) if ENDPOINTS[name].requires_link_token else [None]
+ try:
+ for token in tokens:
+ # Movements need an account ID, so probe the account before probing its child scope.
+ probe_name = "accounts" if name == "movements" else name
+ resource = self.resource(probe_name, page_size=1)
+ config: RESTAPIConfig = {"client": self.client_config(token), "resources": [resource]}
+ page = next(iter(rest_api_resource(config, 0, "fintoc-validation", None)), [])
+ if name == "movements" and page:
+ config["resources"] = [self.resource(name, page_size=1, account_id=page[0]["id"])]
+ next(iter(rest_api_resource(config, 0, "fintoc-validation", None)), None)
+ except HTTPError as error:
+ status = error.response.status_code if error.response is not None else None
+ if status == 401:
+ return False, AUTH_ERROR
+ if status == 403:
+ return (True, None) if schema_name is None else (False, PERMISSION_ERROR)
+ raise
+ return True, None
+
+ @staticmethod
+ def resource(name: str, page_size: int = 300, account_id: str | None = None) -> EndpointResource:
+ endpoint = ENDPOINTS[name]
+ params: dict[str, Any] = {endpoint.page_size_param: page_size}
+ path = endpoint.path
+ if name == "movements":
+ params["confirmed_only"] = "false"
+ if account_id is not None:
+ path = path.format(account_id=quote(account_id, safe=""))
+ else:
+ params["account_id"] = {"type": "resolve", "resource": "accounts", "field": "id"}
+ resource: EndpointResource = {
+ "name": name,
+ "endpoint": {"path": path, "params": params, "data_selector": "$"},
+ }
+ if name == "movements" and account_id is None:
+ resource["include_from_parent"] = ["id"]
+ return resource
+
+ def rows(
+ self,
+ name: str,
+ link_tokens: list[str],
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[FintocResumeState],
+ ) -> Iterator[list[dict[str, Any]]]:
+ endpoint = ENDPOINTS[name]
+ if endpoint.requires_link_token and not link_tokens:
+ raise ValueError(LINK_TOKEN_ERROR)
+ tokens: list[str | None] = list(link_tokens) if endpoint.requires_link_token else [None]
+ for token in tokens:
+ token_manager = manager.with_namespace(hashlib.sha256(token.encode()).hexdigest()) if token else manager
+ resume = token_manager.load_state() if token_manager.can_resume() else None
+ if resume and resume.complete:
+ continue
+
+ def save_state(
+ state: dict[str, Any] | None,
+ current_manager: ResumableSourceManager[FintocResumeState] = token_manager,
+ ) -> None:
+ # Resume state is logged by the manager, so never persist token-bearing next links.
+ current_manager.save_state(
+ FintocResumeState(
+ paginator=_without_link_token(state) if state is not None else None,
+ complete=state is None,
+ )
+ )
+
+ resource = self.resource(name)
+ resources: list[str | EndpointResource] = [resource]
+ if name == "movements":
+ resources = [self.resource("accounts"), resource]
+ config: RESTAPIConfig = {"client": self.client_config(token), "resources": resources}
+ result = rest_api_resources(
+ config,
+ inputs.team_id,
+ inputs.job_id,
+ None,
+ resume_hook=save_state,
+ initial_paginator_state=resume.paginator if resume else None,
+ )[-1]
+ for page in result:
+ if name == "movements":
+ for row in page:
+ row["account_id"] = row.pop("_accounts_id")
+ yield page
+ token_manager.save_state(FintocResumeState(complete=True))
+
+ def source(
+ self,
+ name: str,
+ link_tokens: list[str],
+ inputs: SourceInputs,
+ manager: ResumableSourceManager[FintocResumeState],
+ ) -> SourceResponse:
+ if name not in ENDPOINTS:
+ raise ValueError("Unknown Fintoc table. Select a supported table.")
+ endpoint = ENDPOINTS[name]
+ return SourceResponse(
+ name=name,
+ items=lambda: self.rows(name, link_tokens, inputs, manager),
+ primary_keys=list(endpoint.primary_keys),
+ partition_keys=[endpoint.partition_key] if endpoint.partition_key else None,
+ partition_mode="datetime" if endpoint.partition_key else None,
+ partition_format="month" if endpoint.partition_key else None,
+ sort_mode="desc",
+ )
+
+ def _webhook_request(self, method: str, path: str, body: dict[str, Any] | None = None) -> Any:
+ with make_tracked_session(
+ headers={"Authorization": self.api_key, "Fintoc-Version": self.api_version},
+ redact_values=(self.api_key,),
+ capture=False,
+ ) as session:
+ response = session.request(method, f"{BASE_URL}{path}", json=body, timeout=(10, 60), allow_redirects=False)
+ response.raise_for_status()
+ if response.is_redirect:
+ raise ValueError("Fintoc returned an unexpected redirect.")
+ return response.json() if response.content else None
+
+ def _find_webhook(self, url: str) -> dict[str, Any] | None:
+ config: RESTAPIConfig = {
+ "client": self.client_config(),
+ "resources": [{"name": "webhooks", "endpoint": {"path": "/v1/webhook_endpoints", "data_selector": "$"}}],
+ }
+ for page in rest_api_resource(config, 0, "fintoc-webhooks", None):
+ for webhook in page:
+ if webhook["url"] == url:
+ return webhook
+ return None
+
+ def create_webhook(self, url: str) -> WebhookCreationResult:
+ if self._find_webhook(url):
+ return WebhookCreationResult(
+ success=False,
+ error="This webhook already exists. Enter its signing secret or delete it before creating another.",
+ )
+ result = self._webhook_request(
+ "POST",
+ "/v1/webhook_endpoints",
+ {
+ "url": url,
+ "description": "PostHog data warehouse",
+ "enabled_events": [event for endpoint in ENDPOINTS.values() for event in endpoint.webhook_events],
+ },
+ )
+ if not result.get("secret"):
+ return WebhookCreationResult(
+ success=False,
+ error="Fintoc did not return a signing secret. Check the webhook in Fintoc before trying again.",
+ )
+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": result["secret"]})
+
+ def delete_webhook(self, url: str) -> WebhookDeletionResult:
+ webhook = self._find_webhook(url)
+ if webhook:
+ try:
+ self._webhook_request("DELETE", f"/v1/webhook_endpoints/{quote(webhook['id'], safe='')}")
+ except HTTPError as error:
+ if error.response is None or error.response.status_code != 404:
+ raise
+ return WebhookDeletionResult(success=True)
+
+ def webhook_info(self, url: str) -> ExternalWebhookInfo:
+ webhook = self._find_webhook(url)
+ if webhook is None:
+ return ExternalWebhookInfo(exists=False)
+ return ExternalWebhookInfo(
+ exists=True,
+ url=webhook["url"],
+ enabled_events=webhook["enabled_events"],
+ description=webhook.get("description"),
+ created_at=webhook.get("created_at"),
+ status=webhook.get("status"),
+ )
+
+
+def webhook_table(table: "pa.Table") -> "pa.Table":
+ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import ( # noqa: PLC0415 - keeps Arrow off the source registry import path
+ table_from_py_list,
+ )
+
+ latest: dict[str, dict[str, Any]] = {}
+ for event in table.to_pylist():
+ row = event.get("data")
+ if not isinstance(row, dict) or not row.get("id"):
+ continue
+ previous = latest.get(row["id"])
+ if previous is None or (event.get("created_at") or "") >= (previous.get("created_at") or ""):
+ latest[row["id"]] = event
+ return table_from_py_list([event["data"] for event in latest.values()])
+
+
+def webhook_template() -> "HogFunctionTemplateDC":
+ from posthog.cdp.templates.hog_function_template import ( # noqa: PLC0415 - keeps template dependencies off the source registry import path
+ HogFunctionTemplateDC,
+ )
+
+ return HogFunctionTemplateDC(
+ status="alpha",
+ free=False,
+ type="warehouse_source_webhook",
+ id="template-warehouse-source-fintoc",
+ name="Fintoc warehouse source webhook",
+ description="Receive Fintoc events for data warehouse ingestion",
+ icon_url="/static/services/fintoc.png",
+ category=["Data warehouse"],
+ code_language="hog",
+ code="""
+if (request.method != 'POST') {
+ return {'httpResponse': {'status': 405, 'body': 'Method not allowed'}}
+}
+if (empty(inputs.signing_secret)) {
+ return {'httpResponse': {'status': 503, 'body': 'Signing secret not configured'}}
+}
+let timestamp := null
+let signatures := []
+for (let _, part in splitByString(',', request.headers['fintoc-signature'] ?? '')) {
+ let pair := splitByString('=', trim(part), 2)
+ if (length(pair) = 2) {
+ if (pair[1] = 't') { timestamp := pair[2] }
+ if (pair[1] = 'v1') { signatures := arrayPushBack(signatures, pair[2]) }
+ }
+}
+if (empty(timestamp) or empty(signatures)) {
+ return {'httpResponse': {'status': 400, 'body': 'Invalid signature timestamp'}}
+}
+if (not match(timestamp, '^[0-9]{1,12}$')) {
+ return {'httpResponse': {'status': 400, 'body': 'Invalid signature timestamp'}}
+}
+let age := toUnixTimestamp(now()) - toInt(timestamp)
+if (age > 300 or age < -300) {
+ return {'httpResponse': {'status': 400, 'body': 'Invalid signature timestamp'}}
+}
+let expected := sha256HmacChainHex([inputs.signing_secret, concat(timestamp, '.', request.stringBody)])
+if (not has(signatures, expected)) {
+ return {'httpResponse': {'status': 400, 'body': 'Invalid signature'}}
+}
+let schemaId := inputs.schema_mapping?.[request.body.data?.object]
+if (not empty(schemaId) and not empty(request.body.data?.id)) {
+ produceToWarehouseWebhooks(request.body, schemaId)
+}
+return {'httpResponse': {'status': 200, 'body': 'OK'}}
+""",
+ inputs_schema=[
+ {"type": "string", "key": "signing_secret", "label": "Signing secret", "required": True, "secret": True},
+ {"type": "json", "key": "schema_mapping", "label": "Schema mapping", "required": True, "hidden": True},
+ {"type": "string", "key": "source_id", "label": "Source ID", "required": True, "hidden": True},
+ ],
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/settings.py
new file mode 100644
index 000000000000..b3b9341fd181
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/settings.py
@@ -0,0 +1,98 @@
+from posthog.dataclasses import frozen
+
+BASE_URL = "https://api.fintoc.com"
+API_VERSION = "2026-02-01"
+
+
+@frozen
+class FintocEndpoint:
+ path: str
+ page_size_param: str = "limit"
+ primary_keys: tuple[str, ...] = ("id",)
+ partition_key: str | None = "created_at"
+ requires_link_token: bool = False
+ webhook_object: str | None = None
+ webhook_events: tuple[str, ...] = ()
+
+
+# Creation-date filters miss later status changes; timestamp filtering also needs live verification.
+ENDPOINTS: dict[str, FintocEndpoint] = {
+ "payment_intents": FintocEndpoint(
+ path="/v2/payment_intents",
+ webhook_object="payment_intent",
+ webhook_events=tuple(
+ f"payment_intent.{status}" for status in ("succeeded", "rejected", "failed", "pending", "expired")
+ ),
+ ),
+ "transfers": FintocEndpoint(
+ path="/v2/transfers",
+ webhook_object="transfer",
+ webhook_events=(
+ "transfer.inbound.succeeded",
+ "transfer.inbound.returned",
+ "transfer.inbound.return_failed",
+ "transfer.inbound.rejected",
+ "transfer.inbound.reversed",
+ "transfer.outbound.succeeded",
+ "transfer.outbound.partially_succeeded",
+ "transfer.outbound.failed",
+ "transfer.outbound.returned",
+ "transfer.outbound.reversed",
+ ),
+ ),
+ "refunds": FintocEndpoint(
+ path="/v1/refunds",
+ page_size_param="per_page",
+ webhook_object="refund",
+ webhook_events=("refund.succeeded", "refund.failed", "refund.in_progress"),
+ ),
+ "charges": FintocEndpoint(
+ path="/v1/charges",
+ page_size_param="per_page",
+ webhook_object="charge",
+ webhook_events=("charge.succeeded", "charge.failed"),
+ ),
+ "checkout_sessions": FintocEndpoint(
+ path="/v2/checkout_sessions",
+ webhook_object="checkout_session",
+ webhook_events=("checkout_session.finished", "checkout_session.expired"),
+ ),
+ "subscriptions": FintocEndpoint(path="/v2/subscriptions"),
+ "invoices": FintocEndpoint(
+ path="/v2/invoices",
+ webhook_object="invoice",
+ webhook_events=tuple(
+ f"invoice.{status}"
+ for status in (
+ "created",
+ "finalized",
+ "paid",
+ "payment_created",
+ "payment_failed",
+ "payment_succeeded",
+ "voided",
+ )
+ ),
+ ),
+ "customers": FintocEndpoint(path="/v2/customers"),
+ "links": FintocEndpoint(path="/v1/links", page_size_param="per_page"),
+ "accounts": FintocEndpoint(
+ path="/v1/accounts",
+ page_size_param="per_page",
+ partition_key=None,
+ requires_link_token=True,
+ ),
+ "movements": FintocEndpoint(
+ path="/v1/accounts/{account_id}/movements",
+ page_size_param="per_page",
+ primary_keys=("account_id", "id"),
+ partition_key=None,
+ requires_link_token=True,
+ ),
+}
+
+AUTH_ERROR = "Your Fintoc API key or link token is invalid or expired. Check your credentials and reconnect."
+PERMISSION_ERROR = "Your Fintoc API key cannot access this resource. Check your Fintoc product permissions."
+LINK_TOKEN_ERROR = (
+ "Add link tokens to import open-banking accounts and movements. Fintoc does not return tokens when listing links."
+)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/source.py
index e982e11f9f04..2ec27c0776ba 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/source.py
@@ -1,14 +1,58 @@
-from typing import cast
+from typing import TYPE_CHECKING, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from asgiref.sync import async_to_sync
+
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ ExternalWebhookInfo,
+ FieldType,
+ ResumableSource,
+ WebhookCreationResult,
+ WebhookDeletionResult,
+ WebhookSource,
+)
+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 SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.fintoc import (
+ FintocAPI,
+ FintocResumeState,
+ parse_link_tokens,
+ webhook_table,
+ webhook_template,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.settings import (
+ API_VERSION,
+ AUTH_ERROR,
+ ENDPOINTS,
+ LINK_TOKEN_ERROR,
+ PERMISSION_ERROR,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fintoc import FintocSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
+if TYPE_CHECKING:
+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC
+
@SourceRegistry.register
-class FintocSource(SimpleSource[FintocSourceConfig]):
+class FintocSource(ResumableSource[FintocSourceConfig, FintocResumeState], WebhookSource[FintocSourceConfig]):
+ lists_tables_without_credentials = True
+ supported_versions = (API_VERSION,)
+ default_version = API_VERSION
+ api_docs_url = "https://docs.fintoc.com/changelog"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.FINTOC
@@ -16,11 +60,158 @@ class FintocSource(SimpleSource[FintocSourceConfig]):
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
- name=ExternalDataSourceType.FINTOC,
+ name=self.source_type,
category=DataWarehouseSourceCategory.PAYMENTS___BILLING,
label="Fintoc",
iconPath="/static/services/fintoc.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/fintoc",
keywords=["payments", "open banking", "fintech", "latam"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ caption="Enter your Fintoc secret API key. Test keys import test data; live keys import live data. "
+ "Accounts and movements need link tokens saved when exchanging links. "
+ "Full refresh includes all available records. Optional webhook sync imports only event-delivered changes after the initial backfill.",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ placeholder="sk_live_...",
+ label="Secret API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="link_tokens",
+ placeholder="",
+ label="Link tokens (comma-separated)",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=False,
+ secret=True,
+ ),
+ ],
+ ),
+ webhookFields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="signing_secret",
+ placeholder="",
+ label="Signing secret",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ secret=True,
+ )
+ ],
+ ),
+ releaseStatus=ReleaseStatus.ALPHA,
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": AUTH_ERROR,
+ "403 Client Error": PERMISSION_ERROR,
+ "invalid_api_key": AUTH_ERROR,
+ "invalid_link_token": AUTH_ERROR,
+ LINK_TOKEN_ERROR: LINK_TOKEN_ERROR,
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.canonical_descriptions import ( # noqa: PLC0415 - loads documentation only when requested
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def validate_credentials(
+ self,
+ config: FintocSourceConfig,
+ team_id: int,
+ schema_name: str | None = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ if not config.api_key or not config.api_key.isascii() or any(char.isspace() for char in config.api_key):
+ return False, "Enter a Fintoc secret API key without spaces or unsupported characters."
+ return FintocAPI(config.api_key, self.resolve_api_version(api_version)).validate_credentials(
+ schema_name, parse_link_tokens(config.link_tokens)
+ )
+
+ def get_schemas(
+ self,
+ config: FintocSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return [
+ SourceSchema(
+ name=name,
+ supports_incremental=False,
+ supports_append=False,
+ supports_webhooks=bool(endpoint.webhook_events),
+ should_sync_default=not endpoint.requires_link_token or bool(parse_link_tokens(config.link_tokens)),
+ )
+ for name, endpoint in ENDPOINTS.items()
+ if names is None or name in names
+ ]
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[FintocResumeState]:
+ return ResumableSourceManager(inputs, FintocResumeState)
+
+ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:
+ return WebhookSourceManager(inputs, inputs.logger)
+
+ @property
+ def webhook_template(self) -> "HogFunctionTemplateDC":
+ return webhook_template()
+
+ @property
+ def webhook_resource_map(self) -> dict[str, str]:
+ return {name: endpoint.webhook_object for name, endpoint in ENDPOINTS.items() if endpoint.webhook_object}
+
+ def create_webhook(
+ self,
+ config: FintocSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> WebhookCreationResult:
+ return FintocAPI(config.api_key, self.resolve_api_version(api_version)).create_webhook(webhook_url)
+
+ def delete_webhook(
+ self,
+ config: FintocSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> WebhookDeletionResult:
+ return FintocAPI(config.api_key, self.resolve_api_version(api_version)).delete_webhook(webhook_url)
+
+ def get_external_webhook_info(
+ self,
+ config: FintocSourceConfig,
+ webhook_url: str,
+ team_id: int,
+ api_version: str | None = None,
+ ) -> ExternalWebhookInfo:
+ return FintocAPI(config.api_key, self.resolve_api_version(api_version)).webhook_info(webhook_url)
+
+ def source_for_pipeline(
+ self,
+ config: FintocSourceConfig,
+ resumable_source_manager: ResumableSourceManager[FintocResumeState],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ response = FintocAPI(config.api_key, self.resolve_api_version(inputs.api_version)).source(
+ inputs.schema_name,
+ parse_link_tokens(config.link_tokens),
+ inputs,
+ resumable_source_manager,
)
+ if ENDPOINTS[inputs.schema_name].webhook_events:
+ manager = self.get_webhook_source_manager(inputs)
+ if async_to_sync(manager.webhook_enabled)():
+ response.items = lambda: manager.get_items(table_transformer=webhook_table)
+ response.supports_resume = False
+ return response
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/conftest.py
new file mode 100644
index 000000000000..92146715c9d4
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/conftest.py
@@ -0,0 +1,50 @@
+import json
+from http.client import responses
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from requests import PreparedRequest, Response, Session
+
+
+def http_mock(monkeypatch: pytest.MonkeyPatch) -> MagicMock:
+ handler = MagicMock()
+
+ def send(session: Session, request: PreparedRequest, **kwargs: Any) -> Response:
+ status, body, headers = handler(request)
+ response = Response()
+ response.status_code = status
+ response.reason = responses[status]
+ response.url = request.url or ""
+ response.request = request
+ response._content = json.dumps(body).encode() if body is not None else b""
+ response.headers.update({"Content-Type": "application/json", **headers})
+ return response
+
+ monkeypatch.setattr(Session, "send", send)
+ monkeypatch.setattr("time.sleep", lambda _: None)
+ return handler
+
+
+def manager() -> MagicMock:
+ result = MagicMock()
+ result.can_resume.return_value = False
+ namespaces: dict[str, MagicMock] = {}
+
+ def namespace(key: str) -> MagicMock:
+ if key not in namespaces:
+ child = MagicMock()
+ child.can_resume.return_value = False
+ namespaces[key] = child
+ return namespaces[key]
+
+ result.with_namespace.side_effect = namespace
+ return result
+
+
+def inputs() -> MagicMock:
+ return MagicMock(team_id=1, job_id="fintoc-test-job", schema_name="links", api_version=None)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc.py
new file mode 100644
index 000000000000..5db02e6af4b8
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc.py
@@ -0,0 +1,257 @@
+import hmac
+import json
+import time
+import hashlib
+from collections.abc import Iterable
+from typing import Any, cast
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from unittest.mock import MagicMock
+
+import pyarrow as pa
+from requests import HTTPError, PreparedRequest
+
+from posthog.cdp.validation import compile_hog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (
+ RESTClientRetryableError,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.fintoc import (
+ FintocAPI,
+ FintocResumeState,
+ webhook_table,
+ webhook_template,
+)
+
+from common.hogvm.python.execute import execute_bytecode
+
+
+ "name,path,param,next_query",
+ [
+ ("links", "/v1/links", "per_page", "page=2"),
+ ("payment_intents", "/v2/payment_intents", "limit", "starting_after=pi_first"),
+ ("refunds", "/v1/refunds", "per_page", "page=2"),
+ ("charges", "/v1/charges", "per_page", "page=2"),
+ ("transfers", "/v2/transfers", "limit", "starting_after=tr_first"),
+ ("checkout_sessions", "/v2/checkout_sessions", "limit", "starting_after=cs_first"),
+ ("subscriptions", "/v2/subscriptions", "limit", "starting_after=sub_first"),
+ ("invoices", "/v2/invoices", "limit", "starting_after=inv_first"),
+ ("customers", "/v2/customers", "limit", "starting_after=cus_first"),
+ ],
+)
+def test_pages_and_resume_after_yield(
+ http_mock: MagicMock,
+ manager: MagicMock,
+ inputs: MagicMock,
+ name: str,
+ path: str,
+ param: str,
+ next_query: str,
+) -> None:
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ next_url = f"https://api.fintoc.com{path}?{next_query}"
+ http_mock.side_effect = [
+ (200, [{"id": "first"}], {"Link": f'<{next_url}>; rel="next"'}),
+ (200, [{"id": "last"}], {"Link": f'<https://api.fintoc.com{path}?page=1>; rel="prev"'}),
+ ]
+ source = FintocAPI("sk_test_example", "2026-02-01").source(name, [], inputs, manager)
+ rows = iter(cast(Iterable[Any], source.items()))
+ assert next(rows) == [{"id": "first"}]
+ manager.save_state.assert_not_called()
+ assert next(rows) == [{"id": "last"}]
+ manager.save_state.assert_called_with(FintocResumeState(paginator={"next_url": next_url}))
+ assert list(rows) == []
+ assert manager.save_state.call_args.args[0].complete
+ first, second = [call.args[0] for call in http_mock.call_args_list]
+ assert urlsplit(first.url).path == path
+ assert parse_qs(urlsplit(first.url).query) == {param: ["300"]}
+ assert first.headers["Authorization"] == "sk_test_example"
+ assert first.headers["Fintoc-Version"] == "2026-02-01"
+ assert second.url == next_url
+
+
[email protected]("complete", [False, True])
+def test_resume_does_not_restart_completed_pages(
+ http_mock: MagicMock,
+ manager: MagicMock,
+ inputs: MagicMock,
+ complete: bool,
+) -> None:
+ url = "https://api.fintoc.com/v2/customers?starting_after=cus_saved"
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = FintocResumeState(paginator={"next_url": url}, complete=complete)
+ http_mock.return_value = (200, [], {})
+ items = FintocAPI("sk_test_example", "2026-02-01").source("customers", [], inputs, manager).items()
+ assert list(cast(Iterable[Any], items)) == []
+ if complete:
+ http_mock.assert_not_called()
+ else:
+ assert http_mock.call_args.args[0].url == url
+
+
[email protected]("status,retryable", [(401, False), (403, False), (429, True), (500, True)])
+def test_http_retry_classification(
+ http_mock: MagicMock,
+ manager: MagicMock,
+ inputs: MagicMock,
+ status: int,
+ retryable: bool,
+) -> None:
+ http_mock.return_value = (status, {"error": {"code": "invalid_api_key"}}, {})
+ with pytest.raises(RESTClientRetryableError if retryable else HTTPError):
+ items = FintocAPI("sk_test_example", "2026-02-01").source("links", [], inputs, manager).items()
+ list(cast(Iterable[Any], items))
+ assert http_mock.call_count == (5 if retryable else 1)
+ manager.save_state.assert_not_called()
+
+
+def test_movements_fanout_keeps_account_keys_and_tokens_private(
+ http_mock: MagicMock,
+ manager: MagicMock,
+ inputs: MagicMock,
+) -> None:
+ tokens = ["link_example_token_one", "link_example_token_two"]
+ calls: list[tuple[str, dict[str, list[str]]]] = []
+
+ def respond(request: PreparedRequest) -> tuple[int, object, dict[str, str]]:
+ parts = urlsplit(request.url or "")
+ query = parse_qs(parts.query)
+ calls.append((parts.path, query))
+ token = query["link_token"][0]
+ assert request.headers["Authorization"] == "sk_test_example"
+ if parts.path == "/v1/accounts":
+ return 200, [{"id": "account_one"}, {"id": "account_two"}], {}
+ account = parts.path.split("/")[3]
+ if "page" not in query:
+ return (
+ 200,
+ [{"id": f"{token[-3:]}_{account}_first"}],
+ {"Link": f'<https://api.fintoc.com{parts.path}?page=2&link_token={token}>; rel="next"'},
+ )
+ return 200, [{"id": f"{token[-3:]}_{account}_last"}], {}
+
+ http_mock.side_effect = respond
+ result = FintocAPI("sk_test_example", "2026-02-01").source("movements", tokens, inputs, manager)
+ pages = list(cast(Iterable[Any], result.items()))
+ assert len(pages) == 8
+ assert {row["account_id"] for page in pages for row in page} == {"account_one", "account_two"}
+ assert result.primary_keys == ["account_id", "id"]
+ assert all("_accounts_id" not in row and "link_token" not in row for page in pages for row in page)
+ assert {query["link_token"][0] for _, query in calls} == set(tokens)
+ for token in tokens:
+ state_calls = manager.with_namespace(hashlib.sha256(token.encode()).hexdigest()).save_state.call_args_list
+ assert state_calls
+ assert token not in repr(state_calls)
+ assert all(
+ query["confirmed_only"] == ["false"] for path, query in calls if "movements" in path and "page" not in query
+ )
+
+
+def test_movements_resume_restores_token_and_skips_finished_accounts(
+ http_mock: MagicMock,
+ manager: MagicMock,
+ inputs: MagicMock,
+) -> None:
+ token = "link_example_token_one"
+ child = manager.with_namespace(hashlib.sha256(token.encode()).hexdigest())
+ child.can_resume.return_value = True
+ child.load_state.return_value = FintocResumeState(
+ paginator={
+ "completed": ["/v1/accounts/account_one/movements"],
+ "current": "/v1/accounts/account_two/movements",
+ "child_state": {"next_url": "https://api.fintoc.com/v1/accounts/account_two/movements?page=2"},
+ }
+ )
+ http_mock.side_effect = [
+ (200, [{"id": "account_one"}, {"id": "account_two"}], {}),
+ (200, [{"id": "movement_last"}], {}),
+ ]
+ items = FintocAPI("sk_test_example", "2026-02-01").source("movements", [token], inputs, manager).items()
+ pages = list(cast(Iterable[Any], items))
+ assert pages == [[{"id": "movement_last", "account_id": "account_two"}]]
+ request = http_mock.call_args.args[0]
+ assert urlsplit(request.url).path == "/v1/accounts/account_two/movements"
+ assert parse_qs(urlsplit(request.url).query) == {"page": ["2"], "link_token": [token]}
+
+
+def test_pagination_cannot_send_credentials_off_origin(
+ http_mock: MagicMock, manager: MagicMock, inputs: MagicMock
+) -> None:
+ http_mock.return_value = (200, [{"id": "first"}], {"Link": '<https://example.com/steal>; rel="next"'})
+ with pytest.raises(ValueError, match="disallowed host"):
+ items = FintocAPI("sk_test_example", "2026-02-01").source("links", [], inputs, manager).items()
+ list(cast(Iterable[Any], items))
+ assert http_mock.call_count == 1
+
+
+def test_webhook_batch_keeps_latest_object_and_ignores_invoice_preview() -> None:
+ events: list[dict[str, Any]] = [
+ {"created_at": "2026-01-02T00:00:00Z", "data": {"id": "invoice_one", "status": "paid"}},
+ {"created_at": "2026-01-01T00:00:00Z", "data": {"id": "invoice_one", "status": "draft"}},
+ {"created_at": "2026-01-03T00:00:00Z", "data": {"id": None, "status": "draft"}},
+ {"created_at": None, "data": {"id": "invoice_two", "status": "draft"}},
+ ]
+ assert webhook_table(pa.Table.from_pylist(events)).to_pylist() == [
+ {"id": "invoice_one", "status": "paid"},
+ {"id": "invoice_two", "status": "draft"},
+ ]
+
+
+ "kind,status,delivered",
+ [
+ ("valid", 200, True),
+ ("bad", 400, False),
+ ("missing", 400, False),
+ ("expired", 400, False),
+ ("malformed_timestamp", 400, False),
+ ("future", 400, False),
+ ("multiple_signatures", 200, True),
+ ("unconfigured", 503, False),
+ ("unmapped", 200, False),
+ ("preview", 200, False),
+ ("get", 405, False),
+ ],
+)
+def test_signed_webhook_routing(kind: str, status: int, delivered: bool) -> None:
+ data: dict[str, Any] = {"id": "invoice_one", "object": "invoice"}
+ body: dict[str, Any] = {
+ "created_at": "2026-01-01T00:00:00Z",
+ "data": data,
+ }
+ if kind == "preview":
+ data["id"] = None
+ payload = json.dumps(body)
+ timestamp = str(int(time.time()) + {"expired": -1000, "future": 1000}.get(kind, 0))
+ if kind == "malformed_timestamp":
+ timestamp = "not-a-number"
+ signature = hmac.new(b"test_signing_secret", f"{timestamp}.{payload}".encode(), hashlib.sha256).hexdigest()
+ header = f"t={timestamp},v1={signature if kind != 'bad' else 'bad'}"
+ if kind == "multiple_signatures":
+ header += ",v1=another_signature"
+ produce = MagicMock()
+ template = webhook_template()
+ result = execute_bytecode(
+ compile_hog(template.code, template.type),
+ {
+ "request": {
+ "method": "GET" if kind == "get" else "POST",
+ "body": body,
+ "stringBody": payload,
+ "headers": {"fintoc-signature": "" if kind == "missing" else header},
+ },
+ "inputs": {
+ "signing_secret": "" if kind == "unconfigured" else "test_signing_secret",
+ "schema_mapping": {} if kind == "unmapped" else {"invoice": "schema_example"},
+ },
+ },
+ functions={"produceToWarehouseWebhooks": produce},
+ )
+ assert result.result["httpResponse"]["status"] == status
+ if delivered:
+ produce.assert_called_once_with(body, "schema_example")
+ else:
+ produce.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc_source.py
new file mode 100644
index 000000000000..861e7f49a11e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/fintoc/tests/test_fintoc_source.py
@@ -0,0 +1,187 @@
+import json
+from collections.abc import Iterable
+from typing import Any, cast
+
+import pytest
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.fintoc.source import FintocSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.fintoc import FintocSourceConfig
+
+
+ "status,schema,valid,message",
+ [
+ (200, None, True, None),
+ (401, None, False, "invalid or expired"),
+ (403, None, True, None),
+ (403, "customers", False, "permissions"),
+ (401, "accounts", False, "invalid or expired"),
+ ],
+)
+def test_credential_probe_distinguishes_scope_from_invalid_key(
+ http_mock: MagicMock,
+ status: int,
+ schema: str | None,
+ valid: bool,
+ message: str | None,
+) -> None:
+ http_mock.return_value = (status, [] if status == 200 else {"error": {"code": "invalid_api_key"}}, {})
+ result, error = FintocSource().validate_credentials(
+ FintocSourceConfig(api_key="sk_test_example", link_tokens="link_example_token"),
+ 1,
+ schema,
+ )
+ assert result is valid
+ if message:
+ assert error and message in error
+ else:
+ assert error is None
+ assert http_mock.call_count == 1
+
+
+ "api_key,schema,tokens,message",
+ [
+ ("bad key", None, None, "without spaces"),
+ ("secret\u200b", None, None, "unsupported characters"),
+ ("sk_test_example", "missing", None, "Unknown Fintoc table"),
+ ("sk_test_example", "accounts", None, "Add link tokens"),
+ ("sk_test_example", "movements", None, "Add link tokens"),
+ ],
+)
+def test_bad_configuration_fails_before_http(
+ http_mock: MagicMock,
+ api_key: str,
+ schema: str | None,
+ tokens: str | None,
+ message: str,
+) -> None:
+ valid, error = FintocSource().validate_credentials(
+ FintocSourceConfig(api_key=api_key, link_tokens=tokens), 1, schema
+ )
+ assert not valid and error and message in error
+ http_mock.assert_not_called()
+
+
+def test_movements_scope_probe_checks_child_access(http_mock: MagicMock) -> None:
+ http_mock.side_effect = [(200, [{"id": "account_example"}], {}), (403, {}, {})]
+ valid, message = FintocSource().validate_credentials(
+ FintocSourceConfig(api_key="sk_test_example", link_tokens="token_example"),
+ 1,
+ "movements",
+ )
+ assert not valid and message and "permissions" in message
+ assert "/v1/accounts/account_example/movements?" in http_mock.call_args.args[0].url
+
+
[email protected]("tokens,enabled", [(None, False), ("token_one, token_two", True)])
+def test_open_banking_default_selection_requires_tokens(tokens: str | None, enabled: bool) -> None:
+ schemas = FintocSource().get_schemas(
+ FintocSourceConfig(api_key="sk_test_example", link_tokens=tokens), 1, names=["accounts", "links"]
+ )
+ assert {schema.name: schema.should_sync_default for schema in schemas} == {"accounts": enabled, "links": True}
+
+
+def test_unknown_pipeline_table_fails_clearly(inputs: MagicMock, manager: MagicMock) -> None:
+ inputs.schema_name = "unknown"
+ with pytest.raises(ValueError, match="Unknown Fintoc table"):
+ FintocSource().source_for_pipeline(FintocSourceConfig(api_key="sk_test_example"), manager, inputs)
+
+
[email protected]("webhook_enabled", [False, True])
+def test_pipeline_selects_backfill_or_webhook_rows(
+ http_mock: MagicMock,
+ inputs: MagicMock,
+ manager: MagicMock,
+ webhook_enabled: bool,
+) -> None:
+ inputs.schema_name = "invoices"
+ http_mock.return_value = (200, [{"id": "invoice_example"}], {})
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.WebhookSourceManager.webhook_enabled",
+ new=AsyncMock(return_value=webhook_enabled),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3.WebhookSourceManager.get_items",
+ return_value=iter([[{"id": "webhook_invoice"}]]),
+ ),
+ ):
+ result = FintocSource().source_for_pipeline(FintocSourceConfig(api_key="sk_test_example"), manager, inputs)
+ assert list(cast(Iterable[Any], result.items())) == [
+ [{"id": "webhook_invoice" if webhook_enabled else "invoice_example"}]
+ ]
+ assert http_mock.call_count == (0 if webhook_enabled else 1)
+ assert result.supports_resume is not webhook_enabled
+
+
+def test_webhook_creation_persists_secret_and_subscribes_only_routable_events(http_mock: MagicMock) -> None:
+ http_mock.side_effect = [(200, [], {}), (201, {"id": "webhook_example", "secret": "whsec_example"}, {})]
+ source = FintocSource()
+ result = source.create_webhook(FintocSourceConfig(api_key="sk_test_example"), "https://example.com/hook", 1)
+ assert result.success and result.extra_inputs == {"signing_secret": "whsec_example"}
+ request = http_mock.call_args.args[0]
+ payload = json.loads(request.body)
+ assert payload["url"] == "https://example.com/hook"
+ assert "invoice.upcoming" not in payload["enabled_events"]
+ assert all(event.split(".")[0] in source.webhook_resource_map.values() for event in payload["enabled_events"])
+ assert request.headers["Fintoc-Version"] == "2026-02-01"
+ assert request.headers["Authorization"] == "sk_test_example"
+
+
+ "existing,secret,message",
+ [
+ (True, "whsec_example", "already exists"),
+ (False, None, "did not return a signing secret"),
+ ],
+)
+def test_webhook_creation_does_not_claim_unverifiable_setup(
+ http_mock: MagicMock,
+ existing: bool,
+ secret: str | None,
+ message: str,
+) -> None:
+ url = "https://example.com/hook"
+ http_mock.side_effect = [
+ (200, [{"id": "webhook_example", "url": url}] if existing else [], {}),
+ (201, {"id": "webhook_example", "secret": secret}, {}),
+ ]
+ result = FintocSource().create_webhook(FintocSourceConfig(api_key="sk_test_example"), url, 1)
+ assert not result.success and result.error and message in result.error
+ assert http_mock.call_count == (1 if existing else 2)
+
+
[email protected]("exists,delete_status", [(False, 204), (True, 204), (True, 404)])
+def test_webhook_delete_matches_url_and_is_idempotent(http_mock: MagicMock, exists: bool, delete_status: int) -> None:
+ url = "https://example.com/hook"
+ http_mock.side_effect = [
+ (
+ 200,
+ [{"id": "unrelated", "url": "https://example.com/other"}],
+ {"Link": '<https://api.fintoc.com/v1/webhook_endpoints?page=2>; rel="next"'},
+ ),
+ (200, [{"id": "matching", "url": url}] if exists else [], {}),
+ (delete_status, None, {}),
+ ]
+ assert FintocSource().delete_webhook(FintocSourceConfig(api_key="sk_test_example"), url, 1).success
+ if exists:
+ request = http_mock.call_args.args[0]
+ assert request.method == "DELETE" and request.url.endswith("/webhook_endpoints/matching")
+ else:
+ assert http_mock.call_count == 2
+
+
[email protected]("exists", [False, True])
+def test_webhook_info_matches_destination(http_mock: MagicMock, exists: bool) -> None:
+ url = "https://example.com/hook"
+ http_mock.return_value = (
+ 200,
+ [{"url": url, "enabled_events": ["invoice.paid"], "status": "enabled"}] if exists else [],
+ {},
+ )
+ info = FintocSource().get_external_webhook_info(FintocSourceConfig(api_key="sk_test_example"), url, 1)
+ assert info.exists is exists
+ if exists:
+ assert info.url == url and info.enabled_events == ["invoice.paid"] and info.status == "enabled"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fintoc.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fintoc.py
index ff6a9ea1b50e..50cb6618699c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fintoc.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/fintoc.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class FintocSourceConfig(config.Config):
- pass
+ api_key: str
+ link_tokens: str | None = None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
index f2f00e9f3e64..ac1788142119 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/tests/test_source_catalog_invariants.py
@@ -57,7 +57,6 @@ SOURCES_WITHOUT_AN_ICON_FILE = {
"BrowserUse",
"Cohere",
"DenoDeploy",
- "Fintoc",
"FlyIo",
"Groq",
"Gumloop",