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.

8.4 KB
Raw Blame
import re
import base64
import dataclasses
from typing import Any, Optional, cast

from requests import Response

from products.warehouse_sources.sources.confluence.settings import CONFLUENCE_ENDPOINTS, ConfluenceEndpointConfig
from products.warehouse_sources.sources.sdk import (
    ClientConfig,
    JSONResponsePaginator,
    Resource,
    RESTAPIConfig,
    ResumableSourceManager,
    SourceResponse,
    build_dependent_resource,
    make_tracked_session,
    rest_api_resource,
    unreachable_vendor_message,
    validate_via_probe,
)

# Confluence Cloud sites always live under <subdomain>.atlassian.net. Building
# the host ourselves from a validated subdomain (rather than accepting an
# arbitrary host) keeps the API token from being sent anywhere off-Atlassian.
_SUBDOMAIN_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9-]{0,62}$")
_ATLASSIAN_HOST_SUFFIX = ".atlassian.net"


@dataclasses.dataclass(frozen=True)
class ConfluenceResumeConfig:
    next_url: str


def _site_origin(subdomain: str) -> str:
    return f"https://{subdomain}.atlassian.net"


def _base_url(subdomain: str) -> str:
    return f"{_site_origin(subdomain)}/wiki/api/v2"


def normalize_subdomain(subdomain: str) -> str:
    """Reduce a pasted host or URL ("https://acme.atlassian.net/wiki/home") to the bare site name."""
    subdomain = subdomain.strip()
    if "://" in subdomain:
        subdomain = subdomain.split("://", 1)[1]
    subdomain = re.split(r"[/?#]", subdomain, maxsplit=1)[0]
    if subdomain.lower().endswith(_ATLASSIAN_HOST_SUFFIX):
        subdomain = subdomain[: -len(_ATLASSIAN_HOST_SUFFIX)]
    return subdomain


def is_valid_subdomain(subdomain: str) -> bool:
    return bool(subdomain) and _SUBDOMAIN_RE.match(subdomain) is not None


def _get_headers(email: str, api_token: str) -> dict[str, str]:
    token = base64.b64encode(f"{email}:{api_token}".encode()).decode()
    return {
        "Authorization": f"Basic {token}",
        "Accept": "application/json",
    }


class ConfluenceLinkPaginator(JSONResponsePaginator):
    """Confluence v2 returns the next page as a site-relative path in ``_links.next``
    (e.g. ``/wiki/api/v2/pages?cursor=...``); resolve it against the site origin so the
    client requests an absolute URL. Absence of the key signals the last page."""

    def __init__(self, site_origin: str) -> None:
        super().__init__(next_url_path="_links.next")
        self._site_origin = site_origin

    def update_state(self, response: Response, data: Optional[list[Any]] = None) -> None:
        super().update_state(response, data)
        if self._has_next_page and self._next_url and not self._next_url.startswith(("http://", "https://")):
            self._next_url = f"{self._site_origin}{self._next_url}"


def _client_config(subdomain: str, email: str, api_token: str) -> ClientConfig:
    return {
        "base_url": _base_url(subdomain),
        # Auth (HTTP Basic) is supplied via the framework auth config so the token is
        # redacted from logs; only the non-secret Accept header is set here.
        "headers": {"Accept": "application/json"},
        "auth": {"type": "http_basic", "username": email, "password": api_token},
        "paginator": ConfluenceLinkPaginator(_site_origin(subdomain)),
    }


def _lift_principal(row: dict[str, Any]) -> dict[str, Any]:
    # The primary key needs the principal at the top level.
    principal = row.pop("principal", None) or {}
    row["principalType"] = principal.get("principalType")
    row["principalId"] = principal.get("principalId")
    return row


def _source_response(config: ConfluenceEndpointConfig, resource: Resource) -> SourceResponse:
    return SourceResponse(
        name=config.name,
        items=lambda: resource,
        primary_keys=config.primary_keys,
        partition_count=1,
        partition_size=1,
        partition_mode="datetime" if config.partition_key else None,
        partition_format="week" if config.partition_key else None,
        partition_keys=[config.partition_key] if config.partition_key else None,
        column_hints=resource.column_hints,
    )


def _fanout_source(
    config: ConfluenceEndpointConfig,
    subdomain: str,
    email: str,
    api_token: str,
    team_id: int,
    job_id: str,
) -> SourceResponse:
    assert config.fanout is not None

    # The helper types its return loosely, but it is the framework Resource it built.
    resource = cast(
        Resource,
        build_dependent_resource(
            endpoint_configs=CONFLUENCE_ENDPOINTS,
            child_endpoint=config.name,
            fanout=config.fanout,
            client_config=_client_config(subdomain, email, api_token),
            path_format_values={},
            team_id=team_id,
            job_id=job_id,
            # Permission endpoints have no server-side time filter, so the fan-out is always full refresh.
            db_incremental_field_last_value=None,
            parent_endpoint_extra={"data_selector": "results"},
            child_endpoint_extra={"data_selector": "results"},
            # No resume: the framework checkpoints the full list of completed parents after each
            # parent, which grows with every page or blog post on the site.
        ),
    )

    return _source_response(config, resource.add_map(_lift_principal))


def confluence_source(
    subdomain: str,
    email: str,
    api_token: str,
    endpoint: str,
    team_id: int,
    job_id: str,
    resumable_source_manager: ResumableSourceManager[ConfluenceResumeConfig],
    db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
    config = CONFLUENCE_ENDPOINTS[endpoint]
    subdomain = normalize_subdomain(subdomain)

    if config.fanout is not None:
        return _fanout_source(config, subdomain, email, api_token, team_id, job_id)

    rest_config: RESTAPIConfig = {
        "client": _client_config(subdomain, email, api_token),
        "resources": [
            {
                "name": endpoint,
                "endpoint": {
                    "path": config.path,
                    "params": {"limit": config.limit},
                    # v2 list endpoints wrap rows in `results`; a missing key means an empty page.
                    "data_selector": "results",
                },
            }
        ],
    }

    initial_paginator_state: Optional[dict[str, Any]] = None
    if resumable_source_manager.can_resume():
        resume = resumable_source_manager.load_state()
        if resume is not None:
            initial_paginator_state = {"next_url": resume.next_url}

    def save_checkpoint(state: Optional[dict[str, Any]]) -> None:
        # Persist only when a next page remains; save AFTER a page is yielded so a crash re-fetches
        # the page we just emitted (merge dedupes on primary key) rather than skipping it.
        if state and state.get("next_url"):
            resumable_source_manager.save_state(ConfluenceResumeConfig(next_url=state["next_url"]))

    resource = rest_api_resource(
        rest_config,
        team_id,
        job_id,
        db_incremental_field_last_value,
        resume_hook=save_checkpoint,
        initial_paginator_state=initial_paginator_state,
    )

    return _source_response(config, resource)


def validate_credentials(
    subdomain: str, email: str, api_token: str, schema_name: str | None = None
) -> tuple[bool, str | None]:
    """Probe the Confluence API to confirm the credentials are genuine.

    A 403 at source-create (``schema_name is None``) is accepted: the token may
    be valid but lack access to the probed resource. Once a specific schema is
    being validated we surface the 403.
    """
    subdomain = normalize_subdomain(subdomain)
    if not is_valid_subdomain(subdomain):
        return (
            False,
            "Invalid Confluence subdomain. Use just the site name, e.g. 'your-domain' for your-domain.atlassian.net.",
        )

    url = f"{_base_url(subdomain)}{CONFLUENCE_ENDPOINTS['spaces'].path}?limit=1"
    _ok, status = validate_via_probe(
        lambda: make_tracked_session(redact_values=(api_token,)),
        url,
        headers=_get_headers(email, api_token),
    )

    if status == 200:
        return True, None
    if status == 401:
        return False, "Invalid Confluence credentials. Check your email and API token."
    if status == 403:
        if schema_name is None:
            return True, None
        return False, "Your Confluence account does not have permission to access this resource."
    if status is None:
        return False, unreachable_vendor_message("Confluence")

    return False, f"Confluence API returned status {status}."