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 coolify import source (#107243)

Tom Owers8b421195770a
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 e64eb2850d29..643b1305db05 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -186,6 +186,7 @@ the row lists both.
| commercetools | HTTP | requests | ✅ |
| companycam | HTTP | requests + `rest_source.RESTClient` | ✅ |
| concord | HTTP | requests | ✅ |
+| coolify | HTTP | requests + `rest_source.RESTClient` | ✅ |
| conekta | HTTP | requests + `rest_source.RESTClient` | ✅ |
| configcat | HTTP | requests | ✅ |
| confluence | HTTP | requests | ✅ |
@@ -977,7 +978,6 @@ doesn't conflict with concurrent PRs.
- conta_azul
- contentsquare
- convonite
-- coolify
- copper
- cosmosdb
- couchbase
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/canonical_descriptions.py
new file mode 100644
index 000000000000..c2ce5bbd0752
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/canonical_descriptions.py
@@ -0,0 +1,126 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Descriptions sourced from the Coolify API reference (https://coolify.io/docs/api-reference)
+# and the OpenAPI spec shipped in the Coolify repository.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "applications": {
+ "description": "An application deployed on a Coolify server: its git source, build configuration, domains, and health checks.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-applications",
+ "columns": {
+ "id": "The application identifier in the database.",
+ "uuid": "The application UUID, unique across the instance.",
+ "name": "The application name.",
+ "description": "The application description.",
+ "fqdn": "The application domains.",
+ "git_repository": "Git repository URL.",
+ "git_branch": "Git branch the application deploys from.",
+ "git_commit_sha": "Git commit SHA the application is pinned to.",
+ "build_pack": "Build pack used to build the application (nixpacks, static, dockerfile, dockercompose).",
+ "status": "Current runtime status of the application.",
+ "environment_id": "Identifier of the environment the application belongs to.",
+ "destination_id": "Identifier of the destination (Docker network) the application deploys to.",
+ "created_at": "The date and time the application was created.",
+ "updated_at": "The date and time the application was last updated.",
+ },
+ },
+ "databases": {
+ "description": "A standalone database managed by Coolify (PostgreSQL, MySQL, MariaDB, MongoDB, Redis, KeyDB, Dragonfly, or ClickHouse). Credential columns are removed before storage.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-databases",
+ "columns": {
+ "id": "The database identifier in the database.",
+ "uuid": "The database UUID, unique across the instance.",
+ "name": "The database name.",
+ "description": "The database description.",
+ "status": "Current runtime status of the database.",
+ "image": "Docker image the database runs.",
+ "is_public": "Whether the database is exposed on a public port.",
+ "public_port": "Public port the database is exposed on, when public.",
+ "environment_id": "Identifier of the environment the database belongs to.",
+ "created_at": "The date and time the database was created.",
+ "updated_at": "The date and time the database was last updated.",
+ },
+ },
+ "deployments": {
+ "description": "One row per application deployment, fetched per application. Deploy logs and configuration snapshots are removed before storage.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-deployments-by-app-uuid",
+ "columns": {
+ "id": "The deployment identifier in the database.",
+ "deployment_uuid": "The deployment UUID, unique across the instance.",
+ "application_id": "Identifier of the application that was deployed.",
+ "application_uuid": "UUID of the application that was deployed, projected from the parent applications table.",
+ "application_name": "Name of the application that was deployed.",
+ "status": "Deployment status (queued, in_progress, finished, failed, cancelled-by-user).",
+ "commit": "Git commit SHA that was deployed.",
+ "commit_message": "Git commit message of the deployed commit.",
+ "pull_request_id": "Pull request number for preview deployments, 0 otherwise.",
+ "is_webhook": "Whether the deployment was triggered by a git webhook.",
+ "is_api": "Whether the deployment was triggered through the API.",
+ "rollback": "Whether the deployment was a rollback.",
+ "force_rebuild": "Whether the deployment skipped the build cache.",
+ "server_id": "Identifier of the server the deployment ran on.",
+ "server_name": "Name of the server the deployment ran on.",
+ "deployment_url": "URL of the deployment view in the Coolify dashboard.",
+ "created_at": "The date and time the deployment was queued.",
+ "updated_at": "The date and time the deployment was last updated.",
+ },
+ },
+ "projects": {
+ "description": "A Coolify project: the top-level grouping that holds environments and their resources.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-projects",
+ "columns": {
+ "id": "The project identifier in the database.",
+ "uuid": "The project UUID, unique across the instance.",
+ "name": "The project name.",
+ "description": "The project description.",
+ },
+ },
+ "servers": {
+ "description": "A server connected to Coolify that resources deploy onto.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-servers",
+ "columns": {
+ "id": "The server ID.",
+ "uuid": "The server UUID.",
+ "name": "The server name.",
+ "description": "The server description.",
+ "ip": "The IP address Coolify connects to.",
+ "user": "The SSH user Coolify connects as.",
+ "port": "The SSH port number.",
+ "proxy": "The proxy configuration.",
+ "proxy_type": "The proxy type (traefik, caddy, or none).",
+ "unreachable_count": "How many consecutive reachability checks have failed.",
+ "high_disk_usage_notification_sent": "Whether the high disk usage notification has been sent.",
+ "unreachable_notification_sent": "Whether the unreachable notification has been sent.",
+ },
+ },
+ "services": {
+ "description": "A one-click or compose-based service running on a Coolify server. Compose file contents are removed before storage.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-services",
+ "columns": {
+ "id": "The service identifier in the database.",
+ "uuid": "The service UUID, unique across the instance.",
+ "name": "The service name.",
+ "description": "The service description.",
+ "service_type": "The one-click service type the service was created from.",
+ "server_id": "Identifier of the server the service runs on.",
+ "environment_id": "Identifier of the environment the service belongs to.",
+ "created_at": "The date and time the service was created.",
+ "updated_at": "The date and time the service was last updated.",
+ },
+ },
+ "teams": {
+ "description": "A Coolify team, with its members embedded. API tokens are scoped to one team, so this lists the teams that token can see.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-teams",
+ "columns": {
+ "id": "The unique identifier of the team.",
+ "name": "The name of the team.",
+ "description": "The description of the team.",
+ "personal_team": "Whether the team is personal or not.",
+ "custom_server_limit": "The custom server limit.",
+ "members": "The members of the team.",
+ "created_at": "The date and time the team was created.",
+ "updated_at": "The date and time the team was last updated.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/coolify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/coolify.py
new file mode 100644
index 000000000000..5a766e825b33
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/coolify.py
@@ -0,0 +1,334 @@
+import re
+from collections.abc import Callable
+from typing import Any, Optional, cast
+from urllib.parse import urlparse
+
+import requests
+from requests import Response
+
+from posthog.cloud_utils import is_cloud
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source import (
+ RESTAPIConfig,
+ rest_api_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_dependent_resource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import (
+ find_values,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
+ OffsetPaginator,
+ SinglePagePaginator,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
+ ClientConfig,
+ EndpointResource,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.settings import (
+ COOLIFY_ENDPOINTS,
+ DEPLOYMENTS_PAGE_SIZE,
+ MAX_DEPLOYMENTS_OFFSET,
+ CoolifyEndpointConfig,
+)
+
+# Every Coolify endpoint lives under this prefix, on the customer's own instance
+# (or https://app.coolify.io for Coolify Cloud).
+API_PATH = "/api/v1"
+
+REQUEST_TIMEOUT_SECONDS = 30
+
+HOST_NOT_ALLOWED_ERROR = "This Coolify instance URL is not allowed"
+
+
+class CoolifyHostNotAllowedError(Exception):
+ pass
+
+
+def normalize_base_url(base_url: str) -> str:
+ """Instance root with no trailing slash and no `/api/v1` suffix.
+
+ Users paste the URL from their browser or from the API docs, so both
+ `https://coolify.example.com/` and `https://coolify.example.com/api/v1` must resolve to the
+ same instance root; the API path is appended once in `api_base_url`.
+ """
+ url = base_url.strip()
+ if url and "://" not in url:
+ url = f"https://{url}"
+ url = url.rstrip("/")
+ if url.endswith(API_PATH):
+ url = url.removesuffix(API_PATH)
+ return url.rstrip("/")
+
+
+def api_base_url(base_url: str) -> str:
+ return f"{normalize_base_url(base_url)}{API_PATH}"
+
+
+def _validated_hostname(base_url: str) -> Optional[str]:
+ """Hostname of the normalized instance URL, or None when the URL is malformed or ambiguous.
+
+ SSRF guard: urlparse treats a backslash as ordinary userinfo and an "@" as a userinfo
+ separator, but urllib3/requests treat the backslash as an authority separator, so
+ `https://127.0.0.1\\@example.com` validates as example.com yet connects to 127.0.0.1. A
+ legitimate instance URL has no userinfo, so reject either construct outright.
+ """
+ if "\\" in base_url or "%5c" in base_url.lower():
+ return None
+ parsed = urlparse(base_url)
+ if parsed.scheme not in ("http", "https") or "@" in parsed.netloc:
+ return None
+ # The API token rides in a header on every request, so plaintext http would leak it to any
+ # network observer once it egresses over the public internet. Self-hosted PostHog operators
+ # control their own network path, so http stays allowed there (mirrors Discourse/Flagsmith).
+ if parsed.scheme == "http" and is_cloud():
+ return None
+ hostname = parsed.hostname
+ if not hostname or not re.match(r"^[A-Za-z0-9.\-]+$", hostname):
+ return None
+ return hostname
+
+
+def hostname_of(base_url: str) -> Optional[str]:
+ return _validated_hostname(normalize_base_url(base_url))
+
+
+def _check_host(base_url: str, team_id: int) -> None:
+ hostname = hostname_of(base_url)
+ if not hostname:
+ raise CoolifyHostNotAllowedError("Invalid Coolify instance URL")
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ raise CoolifyHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+
+class DeploymentsPaginationTruncatedError(Exception):
+ """Raised when Coolify reports more deployments than MAX_DEPLOYMENTS_OFFSET permits walking.
+
+ The safety cap exists to bound a host that misreports `count` or ignores `skip`, not to
+ silently truncate a real, very long deploy history. The deployments table syncs with
+ `write_disposition: "replace"`, so stopping at the cap without raising would replace a
+ complete table with an incomplete one and report success. Fail the sync instead.
+ """
+
+
+class _DeploymentsPaginator(OffsetPaginator):
+ """`OffsetPaginator` that fails the sync when `count` exceeds the safety cap.
+
+ The base implementation stops silently once `offset` reaches `maximum_offset`, regardless of
+ whether the response's `count` says there is more to walk. That is fine for a cap that only
+ ever guards against a misbehaving host, but wrong for one meant to protect a real, bounded
+ walk: reaching it while `count` still exceeds the offset means rows were left unfetched.
+ """
+
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ super().update_state(response, data)
+ if self._has_next_page or self.maximum_offset is None or self.offset < self.maximum_offset:
+ return
+ try:
+ values = find_values("count", response.json())
+ except Exception:
+ values = []
+ total = values[0] if values else None
+ if isinstance(total, int) and total > self.offset:
+ raise DeploymentsPaginationTruncatedError(
+ f"Coolify reports {total} deployments for this application, past the "
+ f"{self.maximum_offset}-row safety cap ({self.offset} fetched). Refusing to "
+ "replace the table with a truncated sync."
+ )
+
+
+def _deployments_paginator() -> BasePaginator:
+ # `/deployments/applications/{uuid}` pages with `skip`/`take` and reports the grand total
+ # under `count` (verified against the controller: rows come newest-first, `take` defaults
+ # to 10 server-side). `maximum_offset` bounds the walk against a host that misreports
+ # `count` or ignores `skip` (see MAX_DEPLOYMENTS_OFFSET); `_DeploymentsPaginator` turns a
+ # genuine breach of that cap into a hard failure instead of a silent truncation.
+ return _DeploymentsPaginator(
+ limit=DEPLOYMENTS_PAGE_SIZE,
+ offset_param="skip",
+ limit_param="take",
+ total_path="count",
+ maximum_offset=MAX_DEPLOYMENTS_OFFSET,
+ )
+
+
+def _client_config(base_url: str, api_token: str, endpoint_config: CoolifyEndpointConfig) -> ClientConfig:
+ client_config: ClientConfig = {
+ "base_url": api_base_url(base_url),
+ "auth": {
+ "type": "bearer",
+ "token": api_token,
+ },
+ # The instance URL is customer-supplied: pin every request (including pagination) to the
+ # base host and refuse redirects so the credentialed request can't be bounced off-host.
+ "allowed_hosts": [],
+ "allow_redirects": False,
+ # Bound every sync request so a host that accepts the connection then stalls can't hold
+ # an import worker indefinitely.
+ "request_timeout": REQUEST_TIMEOUT_SECONDS,
+ }
+ # Sample capture records the raw response before resource maps run, so stripping a field
+ # from storage does not keep it out of a sample. The request stays metered, logged, and
+ # token-redacted.
+ if endpoint_config.sensitive_fields or not endpoint_config.captures_http_samples:
+ client_config["capture"] = False
+ return client_config
+
+
+def _get_resource(endpoint_config: CoolifyEndpointConfig) -> EndpointResource:
+ return {
+ "name": endpoint_config.name,
+ "table_name": endpoint_config.name,
+ # No server-side timestamp filter exists on any Coolify list endpoint, so we always
+ # replace the whole table rather than merge on an incremental cursor.
+ "write_disposition": "replace",
+ "endpoint": {
+ "data_selector": endpoint_config.data_selector,
+ "path": endpoint_config.path,
+ "paginator": SinglePagePaginator(),
+ },
+ "table_format": "delta",
+ }
+
+
+def _strip_sensitive_fields(sensitive_fields: frozenset[str]) -> Callable[[dict[str, Any]], dict[str, Any]]:
+ # Drop credential-bearing keys from each record before it's stored. Recurses through nested
+ # dicts and lists because e.g. database rows nest their type-specific fields. Runs as a
+ # resource map, so it's the last thing to touch a record before persistence.
+ def _scrub(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {key: _scrub(item) for key, item in value.items() if key not in sensitive_fields}
+ if isinstance(value, list):
+ return [_scrub(item) for item in value]
+ return value
+
+ def _strip(record: dict[str, Any]) -> dict[str, Any]:
+ return _scrub(record)
+
+ return _strip
+
+
+def _fanout_resource(
+ endpoint_config: CoolifyEndpointConfig, client_config: ClientConfig, endpoint: str, team_id: int, job_id: str
+) -> Resource:
+ fanout = endpoint_config.fanout
+ assert fanout is not None
+
+ return cast(
+ Resource,
+ build_dependent_resource(
+ endpoint_configs=COOLIFY_ENDPOINTS,
+ child_endpoint=endpoint,
+ fanout=fanout,
+ client_config=client_config,
+ path_format_values={},
+ team_id=team_id,
+ job_id=job_id,
+ db_incremental_field_last_value=None,
+ parent_endpoint_extra={
+ "data_selector": COOLIFY_ENDPOINTS[fanout.parent_name].data_selector,
+ "paginator": SinglePagePaginator(),
+ },
+ # The child paginator is always explicit: the REST framework defaults a path that
+ # ends in its resolved id to a single unpaginated entity, which would sync only the
+ # newest page of an application's deployments.
+ child_endpoint_extra={
+ "data_selector": endpoint_config.data_selector,
+ "paginator": _deployments_paginator(),
+ },
+ # Both paginators own their page params (the parent listing takes none at all), so
+ # the builder must not add a `limit` of its own.
+ page_size_param=None,
+ ),
+ )
+
+
+def coolify_source(base_url: str, api_token: str, endpoint: str, team_id: int, job_id: str) -> Resource:
+ # Re-checked at sync time (not just at source-create) in case the instance URL was edited
+ # or now resolves to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ _check_host(base_url, team_id)
+
+ endpoint_config = COOLIFY_ENDPOINTS[endpoint]
+ client_config = _client_config(base_url, api_token, endpoint_config)
+
+ if endpoint_config.fanout is not None:
+ resource = _fanout_resource(endpoint_config, client_config, endpoint, team_id, job_id)
+ else:
+ config: RESTAPIConfig = {
+ "client": client_config,
+ "resource_defaults": {
+ "write_disposition": "replace",
+ },
+ "resources": [_get_resource(endpoint_config)],
+ }
+ # No incremental support, so `db_incremental_field_last_value` is always None.
+ resource = rest_api_resource(config, team_id, job_id, None)
+
+ if endpoint_config.sensitive_fields:
+ resource.add_map(_strip_sensitive_fields(endpoint_config.sensitive_fields))
+ return resource
+
+
+def validate_credentials(
+ base_url: str,
+ api_token: str,
+ team_id: Optional[int] = None,
+ schema_name: Optional[str] = None,
+) -> tuple[bool, Optional[str]]:
+ """Probe `/teams` to confirm the token is genuine and carries the `read` ability.
+
+ Coolify tokens carry global abilities (`read`, `write`, `deploy`, `read:sensitive`, `root`)
+ rather than per-resource scopes, so one probe covers every table: a token that can read
+ `/teams` can read everything this source syncs. `schema_name` therefore changes nothing.
+ Coolify answers 400 with "Invalid token." for an unrecognized token and 403 when the token
+ lacks the `read` ability.
+ """
+ normalized_base_url = normalize_base_url(base_url)
+ hostname = _validated_hostname(normalized_base_url)
+ if not hostname:
+ return False, "Enter your Coolify instance URL, like https://coolify.example.com"
+
+ # The instance URL is fully customer-controlled, so block hosts that resolve to private/
+ # internal addresses (SSRF). Only enforced on cloud.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(hostname, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ # The session never follows redirects: the validated host could 3xx to an internal address,
+ # defeating the host check above (SSRF).
+ session = make_tracked_session(
+ headers={"Authorization": f"Bearer {api_token}", "Accept": "application/json"},
+ redact_values=(api_token,),
+ allow_redirects=False,
+ )
+ try:
+ response = session.get(f"{normalized_base_url}{API_PATH}/teams", timeout=REQUEST_TIMEOUT_SECONDS)
+ except requests.exceptions.RequestException:
+ return False, "Couldn't reach your Coolify instance. Check the URL and try again."
+
+ 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 in (400, 401):
+ return False, (
+ "Coolify rejected the API token. Check the token, or create a new one under "
+ "Keys & Tokens > API tokens on your Coolify instance."
+ )
+
+ if response.status_code == 403:
+ return False, (
+ "Your API token doesn't have read permission. Create a token with read permission "
+ "under Keys & Tokens > API tokens on your Coolify instance."
+ )
+
+ return False, f"Coolify returned HTTP {response.status_code}. Wait a moment and try again."
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/settings.py
new file mode 100644
index 000000000000..88486f866cc5
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/settings.py
@@ -0,0 +1,171 @@
+from dataclasses import field
+from typing import Optional
+
+from posthog.dataclasses import frozen
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ DependentEndpointConfig,
+)
+from products.warehouse_sources.backend.types import IncrementalField
+
+# Page size for the deployments fan-out (`take` param). Coolify's other list endpoints take no
+# pagination params at all and return the full collection in one response.
+DEPLOYMENTS_PAGE_SIZE = 100
+
+# Hard ceiling on the `skip` offset walked per application. The instance is customer-controlled,
+# so a hostile or broken server could report an ever-growing `count` with non-empty pages forever;
+# this cap makes the walk self-terminate. Generous enough not to truncate a real deploy history.
+MAX_DEPLOYMENTS_OFFSET = 100_000
+
+
+@frozen
+class CoolifyEndpointConfig:
+ name: str
+ # Path relative to the API base ({instance}/api/v1). A fan-out child's path carries the
+ # `{...}` placeholder its `fanout.resolve_param` binds.
+ path: str
+ # jsonpath into the response body where the list of records lives. "$" for the endpoints
+ # that answer with a bare array.
+ data_selector: str = "$"
+ primary_keys: list[str] = field(default_factory=lambda: ["uuid"])
+ # A stable creation timestamp to partition by. None for resources the API doesn't stamp
+ # with one. Never a mutable field like `updated_at`.
+ partition_key: Optional[str] = None
+ # Response keys Coolify itself hides from tokens without the `read:sensitive`/`root` ability
+ # (each model's `$hidden` list): credentials, connection URLs, compose/dockerfile contents,
+ # and deploy logs. A privileged token returns them, so they're dropped from every record
+ # (recursively) before storage, and their presence also disables HTTP sample capture for the
+ # endpoint. Stripping them for every token also keeps the table shape independent of the
+ # token's abilities.
+ sensitive_fields: frozenset[str] = frozenset()
+ # False keeps the endpoint's raw response out of HTTP sample capture even when nothing is
+ # stripped from storage, e.g. team member emails. Implied by `sensitive_fields`.
+ captures_http_samples: bool = True
+ # Set on endpoints that are fetched once per row of a parent endpoint.
+ fanout: Optional[DependentEndpointConfig] = None
+ # Read by the fan-out helper's `FanoutEndpointLike` protocol. No Coolify endpoint takes a
+ # server-side time filter, so the incremental members stay empty for every endpoint.
+ page_size: int = DEPLOYMENTS_PAGE_SIZE
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+
+
+# Server settings a `read:sensitive`/`root` token can see but a read-only token cannot (Coolify's
+# own model `$hidden` list, plus the log-drain destinations): the Sentinel APM token and its
+# custom collector URL, the raw log-drain forwarder config (which can embed its own credentials
+# for Axiom/New Relic/a custom endpoint), and the log-drain parser script. `servers` returns
+# these directly; `applications` embeds the same server settings object under its destination, so
+# both endpoints strip this set.
+SERVER_SENSITIVE_FIELDS: frozenset[str] = frozenset(
+ {
+ "logdrain_axiom_api_key",
+ "logdrain_newrelic_license_key",
+ "sentinel_token",
+ "sentinel_custom_url",
+ "logdrain_custom_config",
+ "logdrain_custom_config_parser",
+ }
+)
+
+COOLIFY_ENDPOINTS: dict[str, CoolifyEndpointConfig] = {
+ "applications": CoolifyEndpointConfig(
+ name="applications",
+ path="/applications",
+ partition_key="created_at",
+ # Applications embed their destination server's settings object, so this set also carries
+ # every key in SERVER_SENSITIVE_FIELDS (see `servers` below).
+ sensitive_fields=frozenset(
+ {
+ "http_basic_auth_password",
+ "manual_webhook_secret_github",
+ "manual_webhook_secret_gitlab",
+ "manual_webhook_secret_bitbucket",
+ "manual_webhook_secret_gitea",
+ "dockerfile",
+ "docker_compose",
+ "docker_compose_raw",
+ "custom_labels",
+ "domain_dns_statuses",
+ "domain_port_overrides",
+ }
+ | SERVER_SENSITIVE_FIELDS
+ ),
+ ),
+ # One listing across every standalone database type (PostgreSQL, MySQL, MariaDB, MongoDB,
+ # Redis, KeyDB, Dragonfly, ClickHouse), so the sensitive set is the union of every type's
+ # credential fields.
+ "databases": CoolifyEndpointConfig(
+ name="databases",
+ path="/databases",
+ partition_key="created_at",
+ sensitive_fields=frozenset(
+ {
+ "postgres_password",
+ "mysql_password",
+ "mysql_root_password",
+ "mariadb_password",
+ "mariadb_root_password",
+ "mongo_initdb_root_password",
+ "redis_password",
+ "keydb_password",
+ "dragonfly_password",
+ "clickhouse_admin_password",
+ "internal_db_url",
+ "external_db_url",
+ "init_scripts",
+ }
+ ),
+ ),
+ # Full deploy history per application. The account-wide `/deployments` endpoint only lists
+ # deployments that are currently running, so the history has to be fanned out per app uuid.
+ # Rows already carry `application_id` (the numeric id); the parent's `uuid` is projected on
+ # as `application_uuid` so deployments join directly to the applications table's key.
+ "deployments": CoolifyEndpointConfig(
+ name="deployments",
+ path="/deployments/applications/{application_uuid}",
+ data_selector="deployments",
+ primary_keys=["deployment_uuid"],
+ partition_key="created_at",
+ sensitive_fields=frozenset({"logs", "configuration_snapshot", "configuration_diff"}),
+ fanout=DependentEndpointConfig(
+ parent_name="applications",
+ resolve_param="application_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid"],
+ parent_field_renames={"uuid": "application_uuid"},
+ # An application deleted between the parent listing and this fetch answers 404;
+ # treat it as an empty page rather than failing the whole table.
+ child_response_actions=[{"status_code": 404, "action": "ignore"}],
+ ),
+ ),
+ "projects": CoolifyEndpointConfig(
+ name="projects",
+ path="/projects",
+ ),
+ "servers": CoolifyEndpointConfig(
+ name="servers",
+ path="/servers",
+ sensitive_fields=SERVER_SENSITIVE_FIELDS,
+ ),
+ "services": CoolifyEndpointConfig(
+ name="services",
+ path="/services",
+ partition_key="created_at",
+ sensitive_fields=frozenset({"docker_compose", "docker_compose_raw"}),
+ ),
+ "teams": CoolifyEndpointConfig(
+ name="teams",
+ path="/teams",
+ primary_keys=["id"],
+ partition_key="created_at",
+ # Rows embed the member list with each member's email address; keep that out of
+ # diagnostic samples even though it belongs in the table.
+ captures_http_samples=False,
+ ),
+}
+
+ENDPOINTS = tuple(COOLIFY_ENDPOINTS.keys())
+
+# Coolify exposes no server-side timestamp filter on any list endpoint, so no endpoint supports
+# genuine incremental sync. Kept for parity with the schema-building convention.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/source.py
index 75678e50d18a..4762bb1ec4a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/source.py
@@ -1,8 +1,31 @@
-from typing import cast
+from typing import Optional, cast
-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig
+from products.warehouse_sources.backend.facade.source_config import (
+ DataWarehouseSourceCategory,
+ ReleaseStatus,
+ SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify import (
+ coolify_source,
+ validate_credentials as validate_coolify_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.settings import (
+ COOLIFY_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.coolify import (
CoolifySourceConfig,
)
@@ -11,18 +34,116 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class CoolifySource(SimpleSource[CoolifySourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ # Coolify's API has a single, never-versioned base (`/api/v1` on every instance) and no
+ # version header or changelog of version tokens, so it stays on the unversioned default.
+ api_docs_url = "https://coolify.io/docs/api-reference/authorization"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.COOLIFY
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `base_url` is where the stored API token is sent, so retargeting it must re-require the token.
+ return ["base_url"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # The base host is customer-specific (self-hosted instances), so the keys match the
+ # stable status text rather than a fixed host. Coolify answers an unrecognized token
+ # with 400 "Invalid token." rather than 401, so both map to the credential message.
+ "400 Client Error: Bad Request for url": "Coolify rejected the API token. Check the token, or create a new one under Keys & Tokens > API tokens on your Coolify instance, then reconnect.",
+ "401 Client Error: Unauthorized for url": "Coolify rejected the API token. Check the token, or create a new one under Keys & Tokens > API tokens on your Coolify instance, then reconnect.",
+ "403 Client Error: Forbidden for url": "Your API token doesn't have read permission. Create a token with read permission under Keys & Tokens > API tokens on your Coolify instance, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: CoolifySourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: CoolifySourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_coolify_credentials(config.base_url, config.api_token, team_id=team_id, schema_name=schema_name)
+
+ def source_for_pipeline(self, config: CoolifySourceConfig, inputs: SourceInputs) -> SourceResponse:
+ endpoint_config = COOLIFY_ENDPOINTS[inputs.schema_name]
+ resource = coolify_source(
+ base_url=config.base_url,
+ api_token=config.api_token,
+ endpoint=inputs.schema_name,
+ team_id=inputs.team_id,
+ job_id=inputs.job_id,
+ )
+ response = SourceResponse(
+ name=resource.name,
+ items=lambda: resource,
+ primary_keys=endpoint_config.primary_keys,
+ column_hints=resource.column_hints,
+ )
+
+ if endpoint_config.partition_key:
+ response.partition_count = 1
+ response.partition_size = 1
+ response.partition_mode = "datetime"
+ response.partition_format = "month"
+ response.partition_keys = [endpoint_config.partition_key]
+
+ return response
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=ExternalDataSourceType.COOLIFY,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Coolify",
- keywords=["coolify.io"],
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Coolify instance URL and an API token to pull your servers, projects, applications, databases, services, deployments, and teams into the PostHog Data warehouse.
+
+Create a token under **Keys & Tokens > API tokens** in your Coolify dashboard. A read-only token is enough, because this source never writes or deploys.
+
+The instance URL is where your Coolify dashboard runs, for example `https://coolify.example.com` (use `https://app.coolify.io` for Coolify Cloud).""",
iconPath="/static/services/coolify.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/coolify",
+ keywords=["paas", "self-hosted", "coollabs", "deployments"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="base_url",
+ label="Instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://coolify.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify.py
new file mode 100644
index 000000000000..d4eb6faf6dd0
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify.py
@@ -0,0 +1,356 @@
+import json
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests import Response
+from requests.exceptions import ConnectionError
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify import (
+ CoolifyHostNotAllowedError,
+ DeploymentsPaginationTruncatedError,
+ _client_config,
+ _DeploymentsPaginator,
+ api_base_url,
+ coolify_source,
+ hostname_of,
+ normalize_base_url,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.settings import (
+ COOLIFY_ENDPOINTS,
+ DEPLOYMENTS_PAGE_SIZE,
+)
+
+BASE_URL = "https://coolify.example.com"
+API_BASE = f"{BASE_URL}/api/v1"
+APP_UUID = "o8g80wkc4s0gks0k0ok8cog4"
+
+
+def _make_response(json_body: Any = None, status_code: int = 200) -> Response:
+ resp = Response()
+ resp.status_code = status_code
+ resp.headers["Content-Type"] = "application/json"
+ resp._content = json.dumps(json_body if json_body is not None else {}).encode()
+ return resp
+
+
+def _rows(endpoint: str, base_url: str = BASE_URL) -> list[dict[str, Any]]:
+ resource = coolify_source(base_url, "coolify-token", endpoint, team_id=1, job_id="job-1")
+ return [row for page in resource for row in page]
+
+
+class TestCoolifyNormalizeBaseUrl:
+ @pytest.mark.parametrize(
+ "raw,expected",
+ [
+ pytest.param("https://coolify.example.com", BASE_URL, id="already_normalized"),
+ pytest.param("https://coolify.example.com/", BASE_URL, id="trailing_slash"),
+ pytest.param("https://coolify.example.com/api/v1", BASE_URL, id="pasted_api_base"),
+ pytest.param("https://coolify.example.com/api/v1/", BASE_URL, id="pasted_api_base_with_slash"),
+ pytest.param("coolify.example.com", BASE_URL, id="bare_host_gets_https"),
+ pytest.param(" https://coolify.example.com ", BASE_URL, id="surrounding_whitespace"),
+ ],
+ )
+ def test_resolves_pasted_variants_to_one_instance_root(self, raw: str, expected: str) -> None:
+ # Users paste the URL from a browser bar or the API docs; every variant must produce the
+ # same request URLs or a pasted `/api/v1` suffix silently doubles into `/api/v1/api/v1`.
+ assert normalize_base_url(raw) == expected
+ assert api_base_url(raw) == f"{expected}/api/v1"
+
+
+class TestCoolifyHostnameValidation:
+ @pytest.mark.parametrize(
+ "url",
+ [
+ pytest.param("https://127.0.0.1\\@coolify.example.com", id="backslash_authority_smuggling"),
+ pytest.param("https://127.0.0.1%[email protected]", id="encoded_backslash"),
+ pytest.param("https://[email protected]", id="userinfo"),
+ pytest.param("ftp://coolify.example.com", id="non_http_scheme"),
+ pytest.param("https://", id="no_host"),
+ pytest.param("", id="empty"),
+ ],
+ )
+ def test_rejects_ambiguous_or_malformed_urls(self, url: str) -> None:
+ # urlparse and requests disagree on where the authority ends for these shapes, so a URL
+ # that validates as one host but connects to another must be rejected outright (SSRF).
+ assert hostname_of(url) is None
+
+ def test_accepts_a_plain_instance_url(self) -> None:
+ assert hostname_of(BASE_URL) == "coolify.example.com"
+
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.is_cloud",
+ return_value=True,
+ )
+ def test_rejects_plain_http_on_cloud(self, _mock: MagicMock) -> None:
+ # On cloud the bearer token would ride in cleartext to a customer-supplied http host.
+ assert hostname_of("http://coolify.example.com") is None
+
+ def test_source_refuses_a_rejected_host(self) -> None:
+ with pytest.raises(CoolifyHostNotAllowedError):
+ coolify_source("https://[email protected]", "coolify-token", "servers", team_id=1, job_id="job-1")
+
+
+class TestCoolifyClientConfig:
+ @pytest.mark.parametrize(
+ "endpoint,capture_disabled",
+ [
+ pytest.param("applications", True, id="webhook_secrets_in_the_response"),
+ pytest.param("databases", True, id="database_credentials_in_the_response"),
+ pytest.param("deployments", True, id="deploy_logs_in_the_response"),
+ pytest.param("servers", True, id="log_drain_keys_in_the_response"),
+ pytest.param("services", True, id="compose_contents_in_the_response"),
+ pytest.param("teams", True, id="member_emails_in_the_response"),
+ pytest.param("projects", False, id="nothing_to_withhold"),
+ ],
+ )
+ def test_capture_is_disabled_only_where_the_response_must_not_be_sampled(
+ self, endpoint: str, capture_disabled: bool
+ ) -> None:
+ # Sample capture records the raw response before resource maps run, so stripping a field
+ # from storage does not keep it out of a sample; those endpoints must turn capture off,
+ # and every other endpoint must leave the operator-configured default in place.
+ client_config = _client_config(BASE_URL, "coolify-token", COOLIFY_ENDPOINTS[endpoint])
+ if capture_disabled:
+ assert client_config["capture"] is False
+ else:
+ assert "capture" not in client_config
+
+
+class TestCoolifySensitiveFields:
+ def test_databases_strip_credentials_of_every_database_type(self) -> None:
+ # /databases mixes every standalone database type in one listing, and a token with the
+ # `read:sensitive` or `root` ability gets the credential fields back; each type's
+ # password and connection URLs must be gone before the record is stored.
+ record = {
+ "uuid": "db-1",
+ "name": "prod-pg",
+ "postgres_password": "leak-me",
+ "internal_db_url": "postgres://coolify:leak-me@db:5432/prod",
+ "external_db_url": "postgres://coolify:[email protected]:5432/prod",
+ "init_scripts": [{"filename": "init.sql", "content": "leak-me"}],
+ }
+ resource = coolify_source(BASE_URL, "coolify-token", "databases", team_id=1, job_id="job-1")
+
+ assert resource._apply_transforms([record]) == [{"uuid": "db-1", "name": "prod-pg"}]
+
+ def test_deployments_strip_logs_and_configuration_snapshots(self) -> None:
+ # Deploy logs echo build output (which can print env values) and the configuration
+ # snapshot holds the full application config; both are hidden by Coolify for plain read
+ # tokens and must not land in the warehouse for privileged ones either.
+ record = {
+ "deployment_uuid": "dep-1",
+ "status": "finished",
+ "logs": '[{"output": "leak-me"}]',
+ "configuration_snapshot": {"env": "leak-me"},
+ "configuration_diff": {"env": "leak-me"},
+ }
+ resource = coolify_source(BASE_URL, "coolify-token", "deployments", team_id=1, job_id="job-1")
+
+ assert resource._apply_transforms([record]) == [{"deployment_uuid": "dep-1", "status": "finished"}]
+
+ def test_projects_round_trip_untouched(self) -> None:
+ # Only endpoints that declare sensitive_fields get filtered; everything else must
+ # round-trip untouched or the strip would silently drop real data.
+ record = {"uuid": "proj-1", "name": "web", "description": None}
+ resource = coolify_source(BASE_URL, "coolify-token", "projects", team_id=1, job_id="job-1")
+
+ assert resource._apply_transforms([dict(record)]) == [record]
+
+ def test_servers_strip_sentinel_and_logdrain_credentials(self) -> None:
+ # A `read:sensitive`/`root` token also gets back the Sentinel APM token, its custom
+ # collector URL, and the raw log-drain forwarder config/parser (which can itself embed
+ # Axiom/New Relic/a custom endpoint's credentials); none of that may reach storage.
+ record = {
+ "uuid": "srv-1",
+ "name": "hetzner-1",
+ "logdrain_axiom_api_key": "leak-me",
+ "logdrain_newrelic_license_key": "leak-me",
+ "sentinel_token": "leak-me",
+ "sentinel_custom_url": "https://sentinel.internal/leak-me",
+ "logdrain_custom_config": "leak-me",
+ "logdrain_custom_config_parser": "leak-me",
+ }
+ resource = coolify_source(BASE_URL, "coolify-token", "servers", team_id=1, job_id="job-1")
+
+ assert resource._apply_transforms([record]) == [{"uuid": "srv-1", "name": "hetzner-1"}]
+
+ def test_applications_strip_the_embedded_destination_servers_credentials(self) -> None:
+ # Applications nest their destination server's settings object; the recursive strip must
+ # reach it too, or a privileged token's Sentinel token/log-drain config leaks through the
+ # applications table even though the servers table strips it.
+ record = {
+ "uuid": "app-1",
+ "name": "web",
+ "destination": {
+ "server": {
+ "uuid": "srv-1",
+ "sentinel_token": "leak-me",
+ "logdrain_custom_config": "leak-me",
+ }
+ },
+ }
+ resource = coolify_source(BASE_URL, "coolify-token", "applications", team_id=1, job_id="job-1")
+
+ assert resource._apply_transforms([record]) == [
+ {"uuid": "app-1", "name": "web", "destination": {"server": {"uuid": "srv-1"}}}
+ ]
+
+
+class TestCoolifyFlatEndpoints:
+ def test_reads_the_bare_array_from_the_versioned_path(self, requests_mock: Any) -> None:
+ # Coolify list endpoints answer a bare JSON array under /api/v1; a wrong data_selector or
+ # a doubled/missing API prefix would sync zero rows without erroring.
+ servers = requests_mock.get(f"{API_BASE}/servers", json=[{"uuid": "srv-1", "name": "hetzner-1"}])
+
+ assert _rows("servers", base_url=f"{BASE_URL}/api/v1") == [{"uuid": "srv-1", "name": "hetzner-1"}]
+ assert servers.call_count == 1
+
+
+class TestCoolifyDeploymentsFanout:
+ def _mock_applications(self, requests_mock: Any, uuids: list[str]) -> None:
+ requests_mock.get(f"{API_BASE}/applications", json=[{"uuid": uuid, "name": f"app-{uuid}"} for uuid in uuids])
+
+ def test_deployments_carry_their_parent_application_uuid(self, requests_mock: Any) -> None:
+ # Deployment rows only carry the numeric application_id; the parent's uuid projection
+ # (renamed off the `_applications_` prefix) is what joins them to the applications
+ # table's primary key.
+ self._mock_applications(requests_mock, [APP_UUID])
+ requests_mock.get(
+ f"{API_BASE}/deployments/applications/{APP_UUID}",
+ json={"count": 1, "deployments": [{"deployment_uuid": "dep-1", "status": "finished"}]},
+ )
+
+ assert _rows("deployments") == [
+ {"deployment_uuid": "dep-1", "status": "finished", "application_uuid": APP_UUID}
+ ]
+
+ def test_pages_with_skip_and_take_until_the_reported_count(self, requests_mock: Any) -> None:
+ # The endpoint pages with skip/take and reports the grand total under `count`; wrong
+ # param names or a wrong total path would either sync only the newest page or loop.
+ self._mock_applications(requests_mock, [APP_UUID])
+ page_one = [{"deployment_uuid": f"dep-{i}"} for i in range(DEPLOYMENTS_PAGE_SIZE)]
+ page_two = [{"deployment_uuid": "dep-last"}]
+ deployments = requests_mock.get(
+ f"{API_BASE}/deployments/applications/{APP_UUID}",
+ [
+ {"json": {"count": DEPLOYMENTS_PAGE_SIZE + 1, "deployments": page_one}},
+ {"json": {"count": DEPLOYMENTS_PAGE_SIZE + 1, "deployments": page_two}},
+ ],
+ )
+
+ rows = _rows("deployments")
+
+ assert len(rows) == DEPLOYMENTS_PAGE_SIZE + 1
+ assert deployments.call_count == 2
+ first_request, second_request = deployments.request_history
+ assert first_request.qs["take"] == [str(DEPLOYMENTS_PAGE_SIZE)]
+ assert second_request.qs["skip"] == [str(DEPLOYMENTS_PAGE_SIZE)]
+
+ def test_an_application_deleted_mid_sync_does_not_fail_the_table(self, requests_mock: Any) -> None:
+ # An app removed between the parent listing and its child fetch answers 404; one such app
+ # must cost only its own rows, not the whole deployments table.
+ gone_uuid = "gone0000000000000000000000"
+ self._mock_applications(requests_mock, [gone_uuid, APP_UUID])
+ requests_mock.get(f"{API_BASE}/deployments/applications/{gone_uuid}", status_code=404, json={})
+ requests_mock.get(
+ f"{API_BASE}/deployments/applications/{APP_UUID}",
+ json={"count": 1, "deployments": [{"deployment_uuid": "dep-1"}]},
+ )
+
+ assert [row["deployment_uuid"] for row in _rows("deployments")] == ["dep-1"]
+
+ def test_a_count_past_the_safety_cap_fails_the_table_instead_of_truncating_it(self, requests_mock: Any) -> None:
+ # The deployments table replaces on every sync (`write_disposition: "replace"`). Stopping
+ # at the safety cap while `count` still claims more rows exist would silently swap a
+ # complete table for an incomplete one; it must raise instead.
+ self._mock_applications(requests_mock, [APP_UUID])
+ page = [{"deployment_uuid": f"dep-{i}"} for i in range(DEPLOYMENTS_PAGE_SIZE)]
+ requests_mock.get(
+ f"{API_BASE}/deployments/applications/{APP_UUID}",
+ json={"count": DEPLOYMENTS_PAGE_SIZE + 1, "deployments": page},
+ )
+
+ with (
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.MAX_DEPLOYMENTS_OFFSET",
+ DEPLOYMENTS_PAGE_SIZE,
+ ),
+ pytest.raises(DeploymentsPaginationTruncatedError),
+ ):
+ _rows("deployments")
+
+ def test_an_unparseable_body_at_the_cap_stops_without_crashing(self) -> None:
+ # If the response at the cap boundary isn't valid JSON, `_DeploymentsPaginator` can't read
+ # `count` to tell whether rows were left unfetched; it must fall back to stopping quietly
+ # rather than raising on a body it can't interpret.
+ paginator = _DeploymentsPaginator(
+ limit=DEPLOYMENTS_PAGE_SIZE,
+ offset_param="skip",
+ limit_param="take",
+ total_path="count",
+ maximum_offset=DEPLOYMENTS_PAGE_SIZE,
+ )
+ paginator.offset = DEPLOYMENTS_PAGE_SIZE
+ response = Response()
+ response.status_code = 200
+ response._content = b"not json"
+ page = [{"deployment_uuid": f"dep-{i}"} for i in range(DEPLOYMENTS_PAGE_SIZE)]
+
+ paginator.update_state(response, page)
+
+ assert paginator.has_next_page is False
+
+
+class TestCoolifyValidateCredentials:
+ def test_rejects_an_invalid_url_without_a_network_call(self) -> None:
+ valid, error = validate_credentials("https://[email protected]", "coolify-token")
+ assert not valid
+ assert error is not None
+ assert "instance URL" in error
+
+ @pytest.mark.parametrize(
+ "status_code,expected_valid,expected_fragment",
+ [
+ pytest.param(200, True, None, id="ok"),
+ # Coolify answers an unrecognized token with 400 "Invalid token." rather than 401.
+ pytest.param(400, False, "rejected the API token", id="invalid_token_400"),
+ pytest.param(401, False, "rejected the API token", id="unauthenticated"),
+ pytest.param(403, False, "read permission", id="missing_read_ability"),
+ pytest.param(500, False, "try again", id="transient_server_error"),
+ ],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.make_tracked_session")
+ def test_maps_status_to_a_message(
+ self, mock_session: MagicMock, status_code: int, expected_valid: bool, expected_fragment: str | None
+ ) -> None:
+ mock_session.return_value.get.return_value = _make_response(status_code=status_code)
+
+ valid, error = validate_credentials(BASE_URL, "coolify-token", team_id=1)
+
+ assert valid is expected_valid
+ if expected_fragment is not None:
+ assert error is not None and expected_fragment in error
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.make_tracked_session")
+ def test_transport_error_does_not_blame_the_token(self, mock_session: MagicMock) -> None:
+ # An unreachable instance is not proof the token is bad; the message must point at the
+ # URL, not tell the user to regenerate a good token.
+ mock_session.return_value.get.side_effect = ConnectionError("boom")
+
+ valid, error = validate_credentials(BASE_URL, "coolify-token", team_id=1)
+
+ assert not valid
+ assert error is not None and "reach" in error
+
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.make_tracked_session")
+ def test_probes_the_normalized_teams_endpoint(self, mock_session: MagicMock) -> None:
+ # A pasted `/api/v1` suffix must not double into `/api/v1/api/v1/teams`.
+ mock_session.return_value.get.return_value = _make_response(json_body=[], status_code=200)
+
+ validate_credentials(f"{BASE_URL}/api/v1/", "coolify-token", team_id=1)
+
+ args, _ = mock_session.return_value.get.call_args
+ assert args[0] == f"{API_BASE}/teams"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify_source.py
new file mode 100644
index 000000000000..99f3f40ef565
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/tests/test_coolify_source.py
@@ -0,0 +1,80 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.source import CoolifySource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.coolify import (
+ CoolifySourceConfig,
+)
+
+
+def _config() -> CoolifySourceConfig:
+ return CoolifySourceConfig(base_url="https://coolify.example.com", api_token="coolify-token")
+
+
+class TestCoolifyGetSchemas:
+ def test_lists_every_endpoint_as_full_refresh(self) -> None:
+ schemas = CoolifySource().get_schemas(_config(), team_id=1)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+ # Coolify has no server-side timestamp filter, so nothing may advertise incremental
+ # sync; an "incremental" run would re-fetch every endpoint at full API cost anyway.
+ assert all(not s.supports_incremental for s in schemas)
+ assert all(not s.supports_append for s in schemas)
+
+ def test_filters_by_names(self) -> None:
+ schemas = CoolifySource().get_schemas(_config(), team_id=1, names=["applications"])
+ assert [s.name for s in schemas] == ["applications"]
+
+ def test_documented_tables_render_without_credentials(self) -> None:
+ # lists_tables_without_credentials=True powers the public docs Supported tables section;
+ # it must produce an entry per endpoint from the static catalog with no network call.
+ tables = CoolifySource().get_documented_tables()
+ assert {t["name"] for t in tables} == set(ENDPOINTS)
+
+
+class TestCoolifySourceForPipeline:
+ @pytest.mark.parametrize(
+ "endpoint,expected_pk,expected_partition_key",
+ [
+ pytest.param("applications", ["uuid"], "created_at", id="applications_uuid_pk_partitioned"),
+ # The deployment queue row's uuid, unique across the instance, so no parent
+ # component is needed in the key.
+ pytest.param("deployments", ["deployment_uuid"], "created_at", id="deployments_own_uuid_pk"),
+ # Teams have no uuid, and projects/servers return no creation timestamp to
+ # partition on.
+ pytest.param("teams", ["id"], "created_at", id="teams_id_pk"),
+ pytest.param("projects", ["uuid"], None, id="projects_no_partition"),
+ pytest.param("servers", ["uuid"], None, id="servers_no_partition"),
+ ],
+ )
+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.coolify.source.coolify_source")
+ def test_plumbs_primary_keys_and_partitioning(
+ self, mock_source: MagicMock, endpoint: str, expected_pk: list[str], expected_partition_key: str | None
+ ) -> None:
+ resource = MagicMock()
+ resource.name = endpoint
+ resource.column_hints = None
+ mock_source.return_value = resource
+
+ inputs = MagicMock()
+ inputs.schema_name = endpoint
+ inputs.team_id = 1
+ inputs.job_id = "job-1"
+
+ response = CoolifySource().source_for_pipeline(_config(), inputs)
+
+ assert response.name == endpoint
+ assert response.primary_keys == expected_pk
+ if expected_partition_key:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [expected_partition_key]
+ else:
+ assert response.partition_mode is None
+
+
+class TestCoolifyCanonicalDescriptions:
+ def test_descriptions_key_on_real_endpoints(self) -> None:
+ # Canonical descriptions are keyed by schema name; a typo'd key silently falls back to
+ # LLM enrichment instead of the curated text, so keep the keys inside the endpoint set.
+ descriptions = CoolifySource().get_canonical_descriptions()
+ assert set(descriptions.keys()) <= set(ENDPOINTS)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coolify.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coolify.py
index f617c81392f1..3a6564cf63c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coolify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/coolify.py
@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class CoolifySourceConfig(config.Config):
- pass
+ base_url: str
+ api_token: str