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.

20.2 KB
Raw Blame
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 products.warehouse_sources.sources.coolify.settings import (
    COOLIFY_ENDPOINTS,
    COOLIFY_FANOUT_PARENTS,
    DEPLOYMENTS_PAGE_SIZE,
    MAX_AUDIT_EVENTS_PAGES,
    MAX_DEPLOYMENTS_OFFSET,
    CoolifyEndpointConfig,
)
from products.warehouse_sources.sources.sdk import (
    BasePaginator,
    ClientConfig,
    Endpoint,
    EndpointResource,
    OffsetPaginator,
    PageNumberPaginator,
    Resource,
    RESTAPIConfig,
    SinglePagePaginator,
    _is_host_safe,
    build_chained_resource,
    build_dependent_resource,
    find_values,
    is_cloud,
    make_parent_key_name,
    make_tracked_session,
    rest_api_resource,
)

# 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"

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


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,
    )


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),
        "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": _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
    # 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": _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.
            page_size_param=None,
        ),
    )


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.
    _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 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 = {
            "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.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


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."


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