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(warehouse-sources): add coolify environments, audit log, and run tables (#119251)

Tom Owers621042f88519
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index e2d8fe0bc606..20ecafa05327 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -3229,10 +3229,10 @@ Today (7): `applications`, `databases`, `deployments`, `projects`, `servers`, `s
Diffed against: <https://raw.githubusercontent.com/coollabsio/coolify/main/openapi.json>
-- [ ] `Project environments (GET /projects/{uuid}/environments)` — resolve environment IDs on applications and services to named project environments (high)
-- [ ] `Audit events (GET /audit-events)` — analyze changes to deployed resources and identify the actors responsible (high)
-- [ ] `Backup executions (GET /databases/{uuid}/backups/{scheduled_backup_uuid}/executions)` — measure backup reliability, failure rates, and recovery readiness (medium)
-- [ ] `Application task executions (GET /applications/{uuid}/scheduled-tasks/{task_uuid}/executions)` — measure scheduled application job failures, duration, and execution volume (medium)
+- [x] `Project environments (GET /projects/{uuid}/environments)` — resolve environment IDs on applications and services to named project environments (high)
+- [x] `Audit events (GET /audit-events)` — analyze changes to deployed resources and identify the actors responsible (high)
+- [x] `Backup executions (GET /databases/{uuid}/backups/{scheduled_backup_uuid}/executions)` — measure backup reliability, failure rates, and recovery readiness (medium)
+- [x] `Application task executions (GET /applications/{uuid}/scheduled-tasks/{task_uuid}/executions)` — measure scheduled application job failures, duration, and execution volume (medium)
- [ ] `Service task executions (GET /services/{uuid}/scheduled-tasks/{task_uuid}/executions)` — measure scheduled service job failures, duration, and execution volume (medium)
- [ ] `Preview deployments (GET /applications/{uuid}/previews)` — analyze pull request preview environments and their current status (medium)
- [ ] `Service applications and databases (GET /services/{uuid}/applications; GET /services/{uuid}/databases)` — include individual workloads within service deployments in the deployment inventory (medium)
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
index c2ce5bbd0752..b660b7c1a236 100644
--- 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
@@ -66,6 +66,57 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"updated_at": "The date and time the deployment was last updated.",
},
},
+ "audit_events": {
+ "description": "One row per change recorded in the Coolify team audit log: who did what to which resource. Actor emails, tokens, IP addresses, user agents, metadata, and change diffs are removed before storage.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-audit-events",
+ "columns": {
+ "id": "The audit event identifier.",
+ "team_id": "Identifier of the team the event belongs to.",
+ "event": "The event name.",
+ "source": "Where the change came from (ui, api, mcp, webhook, system, scheduler).",
+ "action": "The action that was performed.",
+ "level": "Severity level of the event.",
+ "actor_type": "Type of the actor that performed the action.",
+ "actor_id": "Identifier of the actor that performed the action.",
+ "actor_name": "Name of the actor that performed the action.",
+ "resource_type": "Type of the resource the action applied to.",
+ "resource_uuid": "UUID of the resource the action applied to.",
+ "resource_name": "Name of the resource the action applied to.",
+ "description": "Human-readable description of the event.",
+ "created_at": "The date and time the event was recorded.",
+ },
+ },
+ "application_task_executions": {
+ "description": "One row per run of a scheduled task on an application, fetched per application and task. Command output is removed before storage.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-scheduled-task-executions-by-application-uuid",
+ "columns": {
+ "uuid": "The execution UUID, unique across the instance.",
+ "status": "Execution status (success, failed, running).",
+ "retry_count": "The number of retries.",
+ "duration": "Duration of the execution in seconds.",
+ "started_at": "The date and time the execution started.",
+ "finished_at": "The date and time the execution finished.",
+ "task_uuid": "UUID of the scheduled task, projected from the task listing.",
+ "task_name": "Name of the scheduled task, projected from the task listing.",
+ "application_uuid": "UUID of the application the task runs on, projected from the parent applications table.",
+ "created_at": "The date and time the execution record was created.",
+ "updated_at": "The date and time the execution record was last updated.",
+ },
+ },
+ "backup_executions": {
+ "description": "One row per run of a scheduled backup on a standalone database, fetched per database and backup configuration.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/list-backup-executions",
+ "columns": {
+ "uuid": "The backup execution UUID, unique across the instance.",
+ "filename": "Path of the backup file the execution wrote.",
+ "size": "Size of the backup file in bytes.",
+ "message": "Output or error message of the backup run.",
+ "status": "Status of the backup run.",
+ "scheduled_backup_uuid": "UUID of the backup configuration that ran, projected from the backup listing.",
+ "database_uuid": "UUID of the database that was backed up, projected from the parent databases table.",
+ "created_at": "The date and time the backup run was recorded.",
+ },
+ },
"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",
@@ -76,6 +127,16 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "The project description.",
},
},
+ "project_environments": {
+ "description": "An environment inside a Coolify project (for example production or staging), fetched per project. Join `id` to `environment_id` on applications, databases, and services.",
+ "docs_url": "https://coolify.io/docs/api-reference/api/operations/get-environments",
+ "columns": {
+ "id": "The environment identifier in the database.",
+ "uuid": "The environment UUID, unique across the instance.",
+ "name": "The environment name.",
+ "project_uuid": "UUID of the project the environment belongs to, projected from the parent projects table.",
+ },
+ },
"servers": {
"description": "A server connected to Coolify that resources deploy onto.",
"docs_url": "https://coolify.io/docs/api-reference/api/operations/list-servers",
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
index 5a766e825b33..f23597f766c8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/coolify.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/coolify.py
@@ -14,7 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
RESTAPIConfig,
rest_api_resource,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.config_setup import (
+ make_parent_key_name,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
+ build_chained_resource,
build_dependent_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.jsonpath_utils import (
@@ -23,16 +27,20 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
BasePaginator,
OffsetPaginator,
+ PageNumberPaginator,
SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.resource import Resource
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
+ Endpoint,
EndpointResource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.settings import (
COOLIFY_ENDPOINTS,
+ COOLIFY_FANOUT_PARENTS,
DEPLOYMENTS_PAGE_SIZE,
+ MAX_AUDIT_EVENTS_PAGES,
MAX_DEPLOYMENTS_OFFSET,
CoolifyEndpointConfig,
)
@@ -45,6 +53,10 @@ REQUEST_TIMEOUT_SECONDS = 30
HOST_NOT_ALLOWED_ERROR = "This Coolify instance URL is not allowed"
+AUDIT_EVENTS_FORBIDDEN_ERROR = (
+ "Only team admins and owners can read audit events. Use an API token created by a team admin or owner."
+)
+
class CoolifyHostNotAllowedError(Exception):
pass
@@ -158,6 +170,55 @@ def _deployments_paginator() -> BasePaginator:
)
+class AuditEventsPaginationTruncatedError(Exception):
+ """Raised when Coolify reports more audit event pages than MAX_AUDIT_EVENTS_PAGES permits walking.
+
+ Same reasoning as DeploymentsPaginationTruncatedError: the table replaces on every sync, so a
+ silent stop at the cap would swap a complete table for an incomplete one.
+ """
+
+
+class _AuditEventsPaginator(PageNumberPaginator):
+ def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
+ # Every page reports the total, so fail on the first one rather than walk to the cap.
+ try:
+ values = find_values("last_page", response.json())
+ except Exception:
+ values = []
+ last_page = values[0] if values else None
+ if self.maximum_page is not None and isinstance(last_page, int) and last_page > self.maximum_page:
+ raise AuditEventsPaginationTruncatedError(
+ f"Coolify reports {last_page} pages of audit events, past the {self.maximum_page}-page "
+ "safety cap. Refusing to replace the table with a truncated sync."
+ )
+ super().update_state(response, data)
+
+
+def _paginator(endpoint_config: CoolifyEndpointConfig) -> BasePaginator:
+ if endpoint_config.pagination == "skip_take":
+ return _deployments_paginator()
+ if endpoint_config.pagination == "page":
+ # A Laravel length-aware paginator: 1-based `page`, total page count under `last_page`.
+ return _AuditEventsPaginator(
+ base_page=1, page_param="page", total_path="last_page", maximum_page=MAX_AUDIT_EVENTS_PAGES
+ )
+ return SinglePagePaginator()
+
+
+def _endpoint(endpoint_config: CoolifyEndpointConfig, params: Optional[dict[str, Any]] = None) -> Endpoint:
+ endpoint: Endpoint = {
+ "path": endpoint_config.path,
+ "data_selector": endpoint_config.data_selector,
+ "paginator": _paginator(endpoint_config),
+ }
+ page_params = {"per_page": endpoint_config.page_size} if endpoint_config.pagination == "page" else {}
+ if params or page_params:
+ endpoint["params"] = {**page_params, **(params or {})}
+ if endpoint_config.fanout is not None:
+ endpoint["response_actions"] = endpoint_config.fanout.child_response_actions
+ return endpoint
+
+
def _client_config(base_url: str, api_token: str, endpoint_config: CoolifyEndpointConfig) -> ClientConfig:
client_config: ClientConfig = {
"base_url": api_base_url(base_url),
@@ -188,15 +249,27 @@ def _get_resource(endpoint_config: CoolifyEndpointConfig) -> EndpointResource:
# 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(),
- },
+ "endpoint": _endpoint(endpoint_config),
"table_format": "delta",
}
+def _skip_rows_shifted_across_pages() -> Callable[[dict[str, Any]], bool]:
+ # Audit events page newest first by (created_at, id), so an event recorded mid-sync pushes
+ # every row down one slot and the last row of a page comes back at the top of the next one.
+ # The table replaces on every sync, so keep only rows strictly older than the last kept row.
+ last_kept: list[tuple[str, int]] = []
+
+ def _keep(record: dict[str, Any]) -> bool:
+ key = (str(record.get("created_at") or ""), int(record.get("id") or 0))
+ if last_kept and key >= last_kept[0]:
+ return False
+ last_kept[:] = [key]
+ return True
+
+ return _keep
+
+
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
@@ -240,7 +313,7 @@ def _fanout_resource(
# newest page of an application's deployments.
child_endpoint_extra={
"data_selector": endpoint_config.data_selector,
- "paginator": _deployments_paginator(),
+ "paginator": _paginator(endpoint_config),
},
# Both paginators own their page params (the parent listing takes none at all), so
# the builder must not add a `limit` of its own.
@@ -249,6 +322,79 @@ def _fanout_resource(
)
+def _chained_resource(
+ endpoint_config: CoolifyEndpointConfig, client_config: ClientConfig, team_id: int, job_id: str
+) -> Resource:
+ """Build a root -> middle -> child chain, e.g. applications -> scheduled tasks -> executions."""
+ fanout = endpoint_config.fanout
+ assert fanout is not None
+ middle_config = COOLIFY_FANOUT_PARENTS[fanout.parent_name]
+ root_fanout = middle_config.fanout
+ assert root_fanout is not None
+ root_config = COOLIFY_ENDPOINTS[root_fanout.parent_name]
+
+ root_resource: EndpointResource = {
+ "name": root_config.name,
+ "table_name": root_config.name,
+ "write_disposition": "replace",
+ "endpoint": _endpoint(root_config),
+ "table_format": "delta",
+ }
+ middle_resource: EndpointResource = {
+ "name": middle_config.name,
+ "table_name": middle_config.name,
+ "write_disposition": "replace",
+ # Carries the root id onto each middle row so the child path can bind it.
+ "include_from_parent": root_fanout.include_from_parent,
+ "endpoint": _endpoint(
+ middle_config,
+ {
+ root_fanout.resolve_param: {
+ "type": "resolve",
+ "resource": root_config.name,
+ "field": root_fanout.resolve_field,
+ }
+ },
+ ),
+ "table_format": "delta",
+ }
+ child_resource: EndpointResource = {
+ "name": endpoint_config.name,
+ "table_name": endpoint_config.name,
+ "write_disposition": "replace",
+ "include_from_parent": fanout.include_from_parent,
+ "endpoint": _endpoint(
+ endpoint_config,
+ {
+ root_fanout.resolve_param: {
+ "type": "resolve",
+ "resource": middle_config.name,
+ "field": make_parent_key_name(root_config.name, root_fanout.resolve_field),
+ },
+ fanout.resolve_param: {
+ "type": "resolve",
+ "resource": middle_config.name,
+ "field": fanout.resolve_field,
+ },
+ },
+ ),
+ "table_format": "delta",
+ }
+
+ return cast(
+ Resource,
+ build_chained_resource(
+ resources=[root_resource, middle_resource, child_resource],
+ child_name=endpoint_config.name,
+ parent_name=middle_config.name,
+ parent_field_renames=fanout.parent_field_renames,
+ client_config=client_config,
+ team_id=team_id,
+ job_id=job_id,
+ ),
+ )
+
+
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.
@@ -257,7 +403,9 @@ def coolify_source(base_url: str, api_token: str, endpoint: str, team_id: int, j
endpoint_config = COOLIFY_ENDPOINTS[endpoint]
client_config = _client_config(base_url, api_token, endpoint_config)
- if endpoint_config.fanout is not None:
+ if endpoint_config.fanout is not None and endpoint_config.fanout.parent_name in COOLIFY_FANOUT_PARENTS:
+ resource = _chained_resource(endpoint_config, client_config, team_id, job_id)
+ elif endpoint_config.fanout is not None:
resource = _fanout_resource(endpoint_config, client_config, endpoint, team_id, job_id)
else:
config: RESTAPIConfig = {
@@ -270,6 +418,8 @@ def coolify_source(base_url: str, api_token: str, endpoint: str, team_id: int, j
# 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.pagination == "page":
+ resource.add_filter(_skip_rows_shifted_across_pages())
if endpoint_config.sensitive_fields:
resource.add_map(_strip_sensitive_fields(endpoint_config.sensitive_fields))
return resource
@@ -332,3 +482,32 @@ def validate_credentials(
)
return False, f"Coolify returned HTTP {response.status_code}. Wait a moment and try again."
+
+
+def audit_events_permission(base_url: str, api_token: str, team_id: int) -> Optional[str]:
+ """Why the token can't read `/audit-events`, or None when it can (or the probe can't tell).
+
+ Coolify lets only team admins and owners read audit events, so a token that passes
+ `validate_credentials` can still get 403 here. Only that answer is a denial; a bad host or a
+ failed probe is left to `validate_credentials` and the sync's own error handling.
+ """
+ normalized_base_url = normalize_base_url(base_url)
+ hostname = _validated_hostname(normalized_base_url)
+ if not hostname or not _is_host_safe(hostname, team_id)[0]:
+ return None
+
+ 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}/audit-events",
+ params={"per_page": 1},
+ timeout=REQUEST_TIMEOUT_SECONDS,
+ )
+ except requests.exceptions.RequestException:
+ return None
+
+ return AUDIT_EVENTS_FORBIDDEN_ERROR if response.status_code == 403 else None
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
index 88486f866cc5..1314c7cc9fad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/coolify/settings.py
@@ -1,11 +1,12 @@
from dataclasses import field
-from typing import Optional
+from typing import Literal, 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.temporal.data_imports.sources.common.rest_source.typing import ResponseAction
from products.warehouse_sources.backend.types import IncrementalField
# Page size for the deployments fan-out (`take` param). Coolify's other list endpoints take no
@@ -17,6 +18,16 @@ DEPLOYMENTS_PAGE_SIZE = 100
# this cap makes the walk self-terminate. Generous enough not to truncate a real deploy history.
MAX_DEPLOYMENTS_OFFSET = 100_000
+# `/audit-events` pages with `page`/`per_page` (100 is the server maximum).
+AUDIT_EVENTS_PAGE_SIZE = 100
+
+# Same safety ceiling as MAX_DEPLOYMENTS_OFFSET, in pages of AUDIT_EVENTS_PAGE_SIZE rows.
+MAX_AUDIT_EVENTS_PAGES = 10_000
+
+# A parent row deleted between its listing and the child fetch answers 404; skip it instead of
+# failing the whole table.
+_IGNORE_404: list[ResponseAction] = [{"status_code": 404, "action": "ignore"}]
+
@frozen
class CoolifyEndpointConfig:
@@ -41,7 +52,12 @@ class CoolifyEndpointConfig:
# 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.
+ # "skip_take" pages with `skip`/`take` and a `count` total (deployments), "page" with
+ # `page`/`per_page` and a `last_page` total (audit events). Every other endpoint answers with
+ # the full collection in one response.
+ pagination: Literal["none", "skip_take", "page"] = "none"
+ # Set on endpoints that are fetched once per row of a parent endpoint. A parent that itself
+ # fans out makes a two-level chain.
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.
@@ -127,21 +143,98 @@ COOLIFY_ENDPOINTS: dict[str, CoolifyEndpointConfig] = {
primary_keys=["deployment_uuid"],
partition_key="created_at",
sensitive_fields=frozenset({"logs", "configuration_snapshot", "configuration_diff"}),
+ pagination="skip_take",
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"}],
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ # Newest first by (created_at, id). Only team admins and owners can read the log, so a
+ # token created by any other member gets 403 on this endpoint alone.
+ "audit_events": CoolifyEndpointConfig(
+ name="audit_events",
+ path="/audit-events",
+ data_selector="data",
+ primary_keys=["id"],
+ partition_key="created_at",
+ # Only a `read:sensitive`/`root` token gets these. `metadata` and `changes` carry the
+ # before/after values of the edited resource, which can include its secrets.
+ sensitive_fields=frozenset(
+ {
+ "actor_email",
+ "actor_token_id",
+ "actor_token_name",
+ "metadata",
+ "changes",
+ "ip_address",
+ "user_agent",
+ }
+ ),
+ pagination="page",
+ page_size=AUDIT_EVENTS_PAGE_SIZE,
+ ),
+ # Every execution of every scheduled task on every application:
+ # applications -> scheduled tasks -> executions. `message` is the command output, which
+ # Coolify hides from tokens without `read:sensitive`.
+ "application_task_executions": CoolifyEndpointConfig(
+ name="application_task_executions",
+ path="/applications/{application_uuid}/scheduled-tasks/{task_uuid}/executions",
+ partition_key="created_at",
+ sensitive_fields=frozenset({"message"}),
+ fanout=DependentEndpointConfig(
+ parent_name="application_scheduled_tasks",
+ resolve_param="task_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid", "name", "_applications_uuid"],
+ parent_field_renames={
+ "uuid": "task_uuid",
+ "name": "task_name",
+ "_applications_uuid": "application_uuid",
+ },
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ # Every run of every scheduled backup on every standalone database:
+ # databases -> backup configurations -> executions.
+ "backup_executions": CoolifyEndpointConfig(
+ name="backup_executions",
+ path="/databases/{database_uuid}/backups/{scheduled_backup_uuid}/executions",
+ data_selector="executions",
+ partition_key="created_at",
+ # The backup configuration listing this walks through is an undocumented raw model dump,
+ # so keep it out of HTTP samples.
+ captures_http_samples=False,
+ fanout=DependentEndpointConfig(
+ parent_name="database_backups",
+ resolve_param="scheduled_backup_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid", "_databases_uuid"],
+ parent_field_renames={"uuid": "scheduled_backup_uuid", "_databases_uuid": "database_uuid"},
+ child_response_actions=_IGNORE_404,
),
),
"projects": CoolifyEndpointConfig(
name="projects",
path="/projects",
),
+ # Coolify selects only `id`, `name`, and `uuid` here. `id` is what `environment_id` on
+ # applications, databases, and services points at.
+ "project_environments": CoolifyEndpointConfig(
+ name="project_environments",
+ path="/projects/{project_uuid}/environments",
+ fanout=DependentEndpointConfig(
+ parent_name="projects",
+ resolve_param="project_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid"],
+ parent_field_renames={"uuid": "project_uuid"},
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
"servers": CoolifyEndpointConfig(
name="servers",
path="/servers",
@@ -166,6 +259,33 @@ COOLIFY_ENDPOINTS: dict[str, CoolifyEndpointConfig] = {
ENDPOINTS = tuple(COOLIFY_ENDPOINTS.keys())
+# Middle hops of the two-level chains. They are walked to reach their executions but are not
+# tables of their own.
+COOLIFY_FANOUT_PARENTS: dict[str, CoolifyEndpointConfig] = {
+ "application_scheduled_tasks": CoolifyEndpointConfig(
+ name="application_scheduled_tasks",
+ path="/applications/{application_uuid}/scheduled-tasks",
+ fanout=DependentEndpointConfig(
+ parent_name="applications",
+ resolve_param="application_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid"],
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+ "database_backups": CoolifyEndpointConfig(
+ name="database_backups",
+ path="/databases/{database_uuid}/backups",
+ fanout=DependentEndpointConfig(
+ parent_name="databases",
+ resolve_param="database_uuid",
+ resolve_field="uuid",
+ include_from_parent=["uuid"],
+ child_response_actions=_IGNORE_404,
+ ),
+ ),
+}
+
# 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 8ed2820747b5..b19bf8abc1c9 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
@@ -19,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.sch
)
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 (
+ audit_events_permission,
coolify_source,
validate_credentials as validate_coolify_credentials,
)
@@ -65,7 +66,7 @@ class CoolifySource(SimpleSource[CoolifySourceConfig]):
# 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.",
+ "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. Audit events also need a token created by a team admin or owner.",
}
def get_schemas(
@@ -88,6 +89,15 @@ class CoolifySource(SimpleSource[CoolifySourceConfig]):
) -> tuple[bool, str | None]:
return validate_coolify_credentials(config.base_url, config.api_token, team_id=team_id, schema_name=schema_name)
+ def get_endpoint_permissions(
+ self, config: CoolifySourceConfig, team_id: int, endpoints: list[str], api_version: str | None = None
+ ) -> dict[str, str | None]:
+ # Tokens carry global abilities, so only the admin-only audit log can differ per table.
+ permissions: dict[str, str | None] = dict.fromkeys(endpoints)
+ if "audit_events" in permissions:
+ permissions["audit_events"] = audit_events_permission(config.base_url, config.api_token, team_id)
+ return permissions
+
def source_for_pipeline(self, config: CoolifySourceConfig, inputs: SourceInputs) -> SourceResponse:
endpoint_config = COOLIFY_ENDPOINTS[inputs.schema_name]
resource = coolify_source(
@@ -120,9 +130,9 @@ class CoolifySource(SimpleSource[CoolifySourceConfig]):
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Coolify",
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.
+ caption="""Enter your Coolify instance URL and an API token to pull your servers, projects, environments, applications, databases, services, deployments, scheduled task and backup runs, audit events, 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.
+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. Audit events need a token created by a team admin or owner.
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",
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
index 6fd0a8e86428..684fee6b5ff0 100644
--- 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
@@ -11,6 +11,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tes
scripted_network,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify import (
+ AUDIT_EVENTS_FORBIDDEN_ERROR,
+ AuditEventsPaginationTruncatedError,
CoolifyHostNotAllowedError,
DeploymentsPaginationTruncatedError,
_client_config,
@@ -98,7 +100,11 @@ class TestCoolifyClientConfig:
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("audit_events", True, id="change_diffs_in_the_response"),
+ pytest.param("application_task_executions", True, id="command_output_in_the_response"),
+ pytest.param("backup_executions", True, id="raw_backup_configs_in_the_walk"),
pytest.param("projects", False, id="nothing_to_withhold"),
+ pytest.param("project_environments", False, id="environments_nothing_to_withhold"),
],
)
def test_capture_is_disabled_only_where_the_response_must_not_be_sampled(
@@ -192,6 +198,171 @@ class TestCoolifyDeploymentsFanout:
assert paginator.has_next_page is False
+class TestCoolifyNestedFanout:
+ @pytest.mark.parametrize(
+ "endpoint,responses,expected_paths,expected_rows",
+ [
+ pytest.param(
+ "project_environments",
+ [
+ ScriptedResponse(json=[{"uuid": "prj-gone"}, {"uuid": "prj-1"}]),
+ ScriptedResponse(status=404, json={}),
+ ScriptedResponse(json=[{"id": 7, "uuid": "env-1", "name": "production"}]),
+ ],
+ [
+ "/api/v1/projects",
+ "/api/v1/projects/prj-gone/environments",
+ "/api/v1/projects/prj-1/environments",
+ ],
+ [{"id": 7, "uuid": "env-1", "name": "production", "project_uuid": "prj-1"}],
+ id="project_environments",
+ ),
+ pytest.param(
+ "application_task_executions",
+ [
+ ScriptedResponse(json=[{"uuid": "app-gone"}, {"uuid": APP_UUID}]),
+ ScriptedResponse(status=404, json={}),
+ ScriptedResponse(json=[{"uuid": "task-1", "name": "nightly", "command": "secret-cmd"}]),
+ ScriptedResponse(json=[{"uuid": "exe-1", "status": "failed", "message": "token=abc"}]),
+ ],
+ [
+ "/api/v1/applications",
+ "/api/v1/applications/app-gone/scheduled-tasks",
+ f"/api/v1/applications/{APP_UUID}/scheduled-tasks",
+ f"/api/v1/applications/{APP_UUID}/scheduled-tasks/task-1/executions",
+ ],
+ [
+ {
+ "uuid": "exe-1",
+ "status": "failed",
+ "task_uuid": "task-1",
+ "task_name": "nightly",
+ "application_uuid": APP_UUID,
+ }
+ ],
+ id="application_task_executions",
+ ),
+ pytest.param(
+ "backup_executions",
+ [
+ ScriptedResponse(json=[{"uuid": "db-1"}]),
+ ScriptedResponse(json=[{"uuid": "bkp-1", "executions": [{"uuid": "embedded"}]}]),
+ ScriptedResponse(json={"executions": [{"uuid": "bex-1", "status": "success", "size": 42}]}),
+ ],
+ [
+ "/api/v1/databases",
+ "/api/v1/databases/db-1/backups",
+ "/api/v1/databases/db-1/backups/bkp-1/executions",
+ ],
+ [
+ {
+ "uuid": "bex-1",
+ "status": "success",
+ "size": 42,
+ "scheduled_backup_uuid": "bkp-1",
+ "database_uuid": "db-1",
+ }
+ ],
+ id="backup_executions",
+ ),
+ ],
+ )
+ def test_binds_every_parent_id_and_projects_it_onto_the_rows(
+ self,
+ endpoint: str,
+ responses: list[ScriptedResponse],
+ expected_paths: list[str],
+ expected_rows: list[dict],
+ ) -> None:
+ # A wrong resolve field leaves a `{placeholder}` in the child path or binds the wrong id,
+ # and a wrong rename leaves the parent id under its framework-prefixed key, so the rows
+ # can't be joined back. A parent deleted mid-sync must cost only its own rows.
+ result = _driver().run(endpoint, responses)
+
+ assert result.raised is None
+ assert result.paths == expected_paths
+ assert result.rows == expected_rows
+
+
+class TestCoolifyAuditEvents:
+ def test_walks_to_the_last_page_and_drops_rows_shifted_by_new_events(self) -> None:
+ # Coolify pages newest first, so an event recorded between page fetches pushes the last
+ # row of page 1 onto page 2. The table replaces on every sync, so that row must not be
+ # stored twice. Sensitive columns must never reach storage.
+ result = _driver().run(
+ "audit_events",
+ [
+ ScriptedResponse(
+ json={
+ "current_page": 1,
+ "last_page": 2,
+ "data": [
+ {"id": 3, "created_at": "2026-10-03T00:00:00.000000Z", "changes": {"password": "x"}},
+ {"id": 2, "created_at": "2026-10-02T00:00:00.000000Z", "actor_email": "[email protected]"},
+ ],
+ }
+ ),
+ ScriptedResponse(
+ json={
+ "current_page": 2,
+ "last_page": 2,
+ "data": [
+ {"id": 2, "created_at": "2026-10-02T00:00:00.000000Z", "actor_email": "[email protected]"},
+ {"id": 1, "created_at": "2026-10-01T00:00:00.000000Z", "ip_address": "192.0.2.1"},
+ ],
+ }
+ ),
+ ],
+ )
+
+ assert result.raised is None
+ assert result.paths == ["/api/v1/audit-events", "/api/v1/audit-events"]
+ assert result.params("page") == ["1", "2"]
+ assert result.params("per_page") == ["100", "100"]
+ assert result.rows == [
+ {"id": 3, "created_at": "2026-10-03T00:00:00.000000Z"},
+ {"id": 2, "created_at": "2026-10-02T00:00:00.000000Z"},
+ {"id": 1, "created_at": "2026-10-01T00:00:00.000000Z"},
+ ]
+
+ def test_a_page_count_past_the_safety_cap_fails_the_table_instead_of_truncating_it(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.coolify.coolify.MAX_AUDIT_EVENTS_PAGES",
+ 2,
+ ):
+ result = _driver().run(
+ "audit_events",
+ [
+ ScriptedResponse(json={"last_page": 3, "data": [{"id": 2, "created_at": "2026-10-02T00:00:00Z"}]}),
+ ScriptedResponse(json={"last_page": 3, "data": [{"id": 1, "created_at": "2026-10-01T00:00:00Z"}]}),
+ ],
+ )
+
+ # The first page already proves the walk can't complete, so no further page is fetched.
+ assert isinstance(result.raised, AuditEventsPaginationTruncatedError)
+ assert result.paths == ["/api/v1/audit-events"]
+
+ @pytest.mark.parametrize(
+ "status_code,expected",
+ [
+ pytest.param(200, None, id="admin_token"),
+ pytest.param(403, AUDIT_EVENTS_FORBIDDEN_ERROR, id="member_token"),
+ # Not a denial, so the table stays selectable and the sync reports the real error.
+ pytest.param(500, None, id="server_error_is_not_a_denial"),
+ ],
+ )
+ def test_reports_the_admin_only_audit_log_per_table(self, status_code: int, expected: str | None) -> None:
+ with scripted_network(always(ScriptedResponse(status=status_code, json={}))) as network:
+ permissions = CoolifySource().get_endpoint_permissions(
+ CoolifySourceConfig(base_url=BASE_URL, api_token="coolify-token"),
+ team_id=1,
+ endpoints=["servers", "audit_events"],
+ )
+
+ assert permissions == {"servers": None, "audit_events": expected}
+ assert {request.path for request in network.requests_log} == {"/api/v1/audit-events"}
+
+
class TestCoolifyValidateCredentials:
def test_rejects_an_invalid_url_without_a_network_call(self) -> None:
valid, error = validate_credentials("https://[email protected]", "coolify-token")