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 gitlab import source (#61664)

Tom Owers9be77c1de54f
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index 0f34702040d9..99af98c2a8ff 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -76,6 +76,7 @@ the row lists both.
| eventbrite | HTTP | requests | ✅ |
| front | HTTP | requests | ✅ |
| github | HTTP | requests | ✅ |
+| gitlab | HTTP | requests | ✅ |
| gong | HTTP | requests | ✅ |
| google_ads | gRPC | google-ads (googleads.client) | ✅ |
| google_sheets | HTTP (vendor SDK) | gspread | ✅ |
@@ -196,7 +197,6 @@ doesn't conflict with concurrent PRs.
- facebook_pages
- firebase
- fullstory
-- gitlab
- google_analytics
- google_drive
- helpscout
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index b5de287c9f7b..9de1c28425b0 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -390,7 +390,9 @@ class FullStorySourceConfig(config.Config):
@config.config
class GitLabSourceConfig(config.Config):
- pass
+ personal_access_token: str
+ project: str
+ gitlab_host: str | None = None
@config.config
diff --git a/posthog/temporal/data_imports/sources/gitlab/gitlab.py b/posthog/temporal/data_imports/sources/gitlab/gitlab.py
new file mode 100644
index 000000000000..956e910fdd8e
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gitlab/gitlab.py
@@ -0,0 +1,393 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+from urllib.parse import quote, urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.mixins import _is_host_safe
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.gitlab.settings import GITLAB_ENDPOINTS, GitLabEndpointConfig
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRIES = 5
+MAX_RETRY_AFTER_SECONDS = 60
+
+DEFAULT_HOST = "https://gitlab.com"
+HOST_NOT_ALLOWED_ERROR = "GitLab host is not allowed"
+HTTP_NOT_ALLOWED_ERROR = "GitLab host must use HTTPS"
+
+
+class GitLabRetryableError(Exception):
+ def __init__(self, message: str, retry_after: float | None = None) -> None:
+ super().__init__(message)
+ self.retry_after = retry_after
+
+
+class GitLabHostNotAllowedError(Exception):
+ pass
+
+
+class GitLabResumeConfig:
+ next_url: str
+
+
+def normalize_host(host: str | None) -> str:
+ """Turn whatever the user typed into a bare GitLab base URL.
+
+ Accepts ``gitlab.com``, ``https://gitlab.example.com/``, or
+ ``https://gitlab.example.com/api/v4`` and returns ``https://gitlab.example.com``.
+ Defaults to https when no scheme is given (the GitLab API is https-only on .com).
+ """
+ host = (host or "").strip()
+ if not host:
+ return DEFAULT_HOST
+ if not re.match(r"^https?://", host, flags=re.IGNORECASE):
+ host = f"https://{host}"
+ host = host.rstrip("/")
+ host = re.sub(r"/api/v4$", "", host, flags=re.IGNORECASE)
+ return host.rstrip("/")
+
+
+def _base_url(host: str | None) -> str:
+ return f"{normalize_host(host)}/api/v4"
+
+
+def _host_only(host: str | None) -> str:
+ return (urlparse(normalize_host(host)).hostname or "").lower()
+
+
+def _is_https(host: str | None) -> bool:
+ # The personal access token rides in the Authorization header, so refuse plaintext HTTP to
+ # keep an on-path attacker from capturing it.
+ return urlparse(normalize_host(host)).scheme == "https"
+
+
+def _encode_project(project: str) -> str:
+ """GitLab accepts either a numeric project id or a URL-encoded ``group/project`` path."""
+ return quote(project.strip().strip("/"), safe="")
+
+
+def _get_headers(personal_access_token: str) -> dict[str, str]:
+ # GitLab accepts a personal access token as a bearer token. We use `Authorization` rather than
+ # `PRIVATE-TOKEN` so the token is redacted by the tracked transport's sample scrubber, which
+ # masks `authorization` by name but not `private-token`.
+ return {
+ "Authorization": f"Bearer {personal_access_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_incremental_value(value: Any) -> str:
+ """GitLab timestamp filters want ISO 8601; we normalize to UTC with a literal Z."""
+ if isinstance(value, datetime):
+ dt = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _active_incremental_field(
+ config: GitLabEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> str | None:
+ """The field we actually filter/sort on this run, or None for a full / first sync."""
+ if not (should_use_incremental_field and db_incremental_field_last_value and config.incremental_filter_params):
+ return None
+ field = incremental_field or config.default_incremental_field
+ if field not in config.incremental_filter_params:
+ raise ValueError(
+ f"Unsupported GitLab incremental field '{field}' for endpoint '{config.name}'. "
+ f"Expected one of: {sorted(config.incremental_filter_params)}."
+ )
+ return field
+
+
+def _build_initial_params(
+ config: GitLabEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {"per_page": config.page_size}
+
+ active_field = _active_incremental_field(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ if active_field is not None:
+ filter_param = config.incremental_filter_params[active_field]
+ params[filter_param] = _format_incremental_value(db_incremental_field_last_value)
+
+ if config.supports_order_by:
+ order_by = active_field or config.stable_order_by
+ if order_by:
+ params["order_by"] = order_by
+ params["sort"] = config.sort_mode
+
+ return params
+
+
+def _build_initial_url(host: str | None, config: GitLabEndpointConfig, project: str, params: dict[str, Any]) -> str:
+ path = config.path.format(project=_encode_project(project))
+ url = f"{_base_url(host)}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+def _parse_next_url(link_header: str) -> str | None:
+ """Return the URL with ``rel="next"`` from GitLab's ``Link`` header, if any."""
+ if not link_header:
+ return None
+ for part in link_header.split(","):
+ part = part.strip()
+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)
+ if match:
+ return match.group(1)
+ return None
+
+
+def _is_same_host(url: str, host: str | None) -> bool:
+ """Whether ``url`` points at the configured GitLab host over HTTPS.
+
+ Pagination/resume URLs are server-controlled (Link header / Redis), so we pin them to the
+ validated host to avoid being redirected at an arbitrary internal address (SSRF). We also
+ require HTTPS and a matching port so the token in the Authorization header is never sent to a
+ plaintext (or otherwise mismatched) URL that merely shares the configured hostname.
+ """
+ try:
+ parsed = urlparse(url)
+ configured = urlparse(normalize_host(host))
+ return (
+ parsed.scheme == "https"
+ and (parsed.hostname or "").lower() == (configured.hostname or "").lower()
+ and (parsed.port or 443) == (configured.port or 443)
+ )
+ except Exception:
+ return False
+
+
+def validate_credentials(
+ host: str | None, personal_access_token: str, project: str, team_id: Optional[int] = None
+) -> tuple[bool, str | None]:
+ """Probe the configured project to confirm the token is genuine and has access."""
+ if not personal_access_token:
+ return False, "Missing personal access token"
+ if not project or not project.strip():
+ return False, "Missing project id or path"
+
+ host_only = _host_only(host)
+ if not host_only:
+ return False, "Invalid GitLab host"
+
+ # Refuse plaintext HTTP before sending the token in the Authorization header.
+ if not _is_https(host):
+ return False, HTTP_NOT_ALLOWED_ERROR
+
+ # The host is customer-controlled (self-hosted GitLab), so block hosts that resolve to
+ # private/internal addresses (SSRF). Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(host_only, team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ url = f"{_base_url(host)}/projects/{_encode_project(project)}"
+ try:
+ # Don't follow redirects: the validated host could 3xx to an internal address (SSRF).
+ response = make_tracked_session().get(
+ url, headers=_get_headers(personal_access_token), timeout=10, allow_redirects=False
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ 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 == 401:
+ return False, "Invalid GitLab personal access token"
+
+ if response.status_code == 404:
+ return False, f"Project '{project}' not found or not accessible with this token"
+
+ try:
+ body = response.json()
+ return False, body.get("message", response.text)
+ except Exception:
+ return False, response.text
+
+
+def _parse_retry_after(response: requests.Response) -> float | None:
+ """GitLab sends ``Retry-After`` in whole seconds on 429. Ignore HTTP-date forms."""
+ raw = response.headers.get("Retry-After")
+ if raw and raw.strip().isdigit():
+ return min(float(raw.strip()), MAX_RETRY_AFTER_SECONDS)
+ return None
+
+
+def _retry_wait(retry_state: RetryCallState) -> float:
+ exc = retry_state.outcome.exception() if retry_state.outcome else None
+ if isinstance(exc, GitLabRetryableError) and exc.retry_after is not None:
+ return exc.retry_after
+ return wait_exponential_jitter(initial=1, max=30)(retry_state)
+
+
+def get_rows(
+ host: str | None,
+ personal_access_token: str,
+ project: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GitLabResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = GITLAB_ENDPOINTS[endpoint]
+ headers = _get_headers(personal_access_token)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+
+ # The token rides in the Authorization header, so refuse plaintext HTTP at run time too in case
+ # the host was edited after source creation. Non-retryable — see get_non_retryable_errors().
+ if not _is_https(host):
+ raise GitLabHostNotAllowedError(HTTP_NOT_ALLOWED_ERROR)
+
+ # Re-check at run time (not just at source-create) in case the host was edited or now resolves
+ # to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_only(host), team_id)
+ if not host_ok:
+ # Prefix with HOST_NOT_ALLOWED_ERROR so get_non_retryable_errors() matches and the workflow
+ # fails fast instead of retrying an SSRF/host failure (_is_host_safe returns its own message).
+ raise GitLabHostNotAllowedError(f"{HOST_NOT_ALLOWED_ERROR}: {host_err}" if host_err else HOST_NOT_ALLOWED_ERROR)
+
+ params = _build_initial_params(
+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ initial_url = _build_initial_url(host, config, project, params)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None and _is_same_host(resume_config.next_url, host):
+ url: str = resume_config.next_url
+ logger.debug(f"GitLab: resuming from URL: {url}")
+ else:
+ if resume_config is not None:
+ logger.warning("GitLab: ignoring resume URL whose host does not match the configured host")
+ url = initial_url
+
+ @retry(
+ retry=retry_if_exception_type((GitLabRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(MAX_RETRIES),
+ wait=_retry_wait,
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> requests.Response:
+ # Don't follow redirects: an attacker-controlled host could 3xx to an internal address (SSRF).
+ response = make_tracked_session().get(
+ page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS, allow_redirects=False
+ )
+
+ if response.status_code == 429 or response.status_code >= 500:
+ retry_after = _parse_retry_after(response) if response.status_code == 429 else None
+ raise GitLabRetryableError(
+ f"GitLab API error (retryable): status={response.status_code}, url={page_url}",
+ retry_after=retry_after,
+ )
+
+ if response.is_redirect or response.is_permanent_redirect:
+ raise GitLabHostNotAllowedError(
+ f"{HOST_NOT_ALLOWED_ERROR}: GitLab API returned an unexpected redirect "
+ f"(status={response.status_code}); refusing to follow it"
+ )
+
+ if not response.ok:
+ logger.error(f"GitLab API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response
+
+ while True:
+ response = fetch_page(url)
+
+ data = response.json()
+ if not isinstance(data, list) or not data:
+ break
+
+ next_url = _parse_next_url(response.headers.get("Link", ""))
+
+ # Page and chunk boundaries don't line up, so checkpoint the CURRENT page URL. On resume we
+ # re-fetch it and rely on primary-key merge semantics to dedupe already-yielded rows.
+ checkpoint_url = url
+
+ for item in data:
+ batcher.batch(item)
+
+ if batcher.should_yield():
+ py_table = batcher.get_table()
+ yield py_table
+ resumable_source_manager.save_state(GitLabResumeConfig(next_url=checkpoint_url))
+
+ if not next_url:
+ break
+
+ # The next-page URL is server-controlled; only follow it if it stays on the configured host.
+ if not _is_same_host(next_url, host):
+ logger.warning("GitLab: stopping pagination, next URL host does not match the configured host")
+ break
+
+ url = next_url
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ py_table = batcher.get_table()
+ yield py_table
+
+
+def gitlab_source(
+ host: str | None,
+ personal_access_token: str,
+ project: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[GitLabResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = GITLAB_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ personal_access_token=personal_access_token,
+ project=project,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=[endpoint_config.primary_key],
+ sort_mode=endpoint_config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
diff --git a/posthog/temporal/data_imports/sources/gitlab/settings.py b/posthog/temporal/data_imports/sources/gitlab/settings.py
new file mode 100644
index 000000000000..bb22e8325e5f
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gitlab/settings.py
@@ -0,0 +1,137 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class GitLabEndpointConfig:
+ name: str
+ path: str # Path template with a {project} placeholder (project id or URL-encoded path)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Maps an incremental field name to the server-side query param that bounds it.
+ # e.g. {"updated_at": "updated_after", "created_at": "created_after"} for issues/merge requests,
+ # {"created_at": "since"} for commits. Only fields listed here actually filter server-side.
+ incremental_filter_params: dict[str, str] = field(default_factory=dict)
+ # Whether the list endpoint accepts order_by=<field>&sort=<dir>. When it does we pin the order
+ # to a stable column so offset pages don't shift while we paginate.
+ supports_order_by: bool = False
+ # Column to order by on a full / first sync (must be a value the endpoint's order_by accepts).
+ stable_order_by: Optional[str] = None
+ partition_key: Optional[str] = None
+ primary_key: str = "id"
+ page_size: int = 100 # GitLab default & max per_page
+ # The order rows are emitted in. Endpoints we sort ascending stay "asc"; commits cannot be
+ # sorted server-side and always come newest-first, so they are "desc".
+ sort_mode: Literal["asc", "desc"] = "asc"
+
+
+# Project-scoped endpoints. We cover the resources a user most commonly wants to analyze and that
+# the canonical GitLab connectors (Airbyte/Fivetran) expose. Incremental support is only declared
+# where a server-side timestamp filter actually drops rows (verified against the live API).
+GITLAB_ENDPOINTS: dict[str, GitLabEndpointConfig] = {
+ "issues": GitLabEndpointConfig(
+ name="issues",
+ path="/projects/{project}/issues",
+ incremental_fields=[
+ _datetime_incremental_field("updated_at"),
+ _datetime_incremental_field("created_at"),
+ ],
+ default_incremental_field="updated_at",
+ incremental_filter_params={"updated_at": "updated_after", "created_at": "created_after"},
+ supports_order_by=True,
+ stable_order_by="created_at",
+ partition_key="created_at",
+ ),
+ "merge_requests": GitLabEndpointConfig(
+ name="merge_requests",
+ path="/projects/{project}/merge_requests",
+ incremental_fields=[
+ _datetime_incremental_field("updated_at"),
+ _datetime_incremental_field("created_at"),
+ ],
+ default_incremental_field="updated_at",
+ incremental_filter_params={"updated_at": "updated_after", "created_at": "created_after"},
+ supports_order_by=True,
+ stable_order_by="created_at",
+ partition_key="created_at",
+ ),
+ "commits": GitLabEndpointConfig(
+ name="commits",
+ path="/projects/{project}/repository/commits",
+ incremental_fields=[
+ _datetime_incremental_field("created_at"),
+ ],
+ default_incremental_field="created_at",
+ # The commits endpoint exposes no order_by/sort; it always returns newest-first and only
+ # accepts a `since` filter (bounded by commit/created date).
+ incremental_filter_params={"created_at": "since"},
+ supports_order_by=False,
+ partition_key="created_at",
+ sort_mode="desc",
+ ),
+ "pipelines": GitLabEndpointConfig(
+ name="pipelines",
+ path="/projects/{project}/pipelines",
+ incremental_fields=[
+ _datetime_incremental_field("updated_at"),
+ ],
+ default_incremental_field="updated_at",
+ # Pipelines accept updated_after/updated_before; order_by does NOT accept created_at, only
+ # updated_at (among id/status/ref/user_id), so updated_at is the stable order too.
+ incremental_filter_params={"updated_at": "updated_after"},
+ supports_order_by=True,
+ stable_order_by="updated_at",
+ partition_key="created_at",
+ ),
+ "releases": GitLabEndpointConfig(
+ name="releases",
+ path="/projects/{project}/releases",
+ # No documented server-side timestamp filter -> full refresh only. Releases have no `id`;
+ # tag_name is unique within a project.
+ primary_key="tag_name",
+ partition_key="created_at",
+ ),
+ "milestones": GitLabEndpointConfig(
+ name="milestones",
+ path="/projects/{project}/milestones",
+ # No reliable server-side updated filter -> full refresh only.
+ partition_key="created_at",
+ ),
+ "branches": GitLabEndpointConfig(
+ name="branches",
+ path="/projects/{project}/repository/branches",
+ # Branches have no stable id/timestamp; name is the unique key. Full refresh.
+ primary_key="name",
+ ),
+ "tags": GitLabEndpointConfig(
+ name="tags",
+ path="/projects/{project}/repository/tags",
+ # Tag name is the unique key. created_at can be absent for some tags, so don't partition.
+ primary_key="name",
+ ),
+ "labels": GitLabEndpointConfig(
+ name="labels",
+ path="/projects/{project}/labels",
+ ),
+ "members": GitLabEndpointConfig(
+ name="members",
+ path="/projects/{project}/members/all",
+ ),
+}
+
+ENDPOINTS = tuple(GITLAB_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in GITLAB_ENDPOINTS.items()
+}
diff --git a/posthog/temporal/data_imports/sources/gitlab/source.py b/posthog/temporal/data_imports/sources/gitlab/source.py
index 31562f9a1cab..0a71a15f59e2 100644
--- a/posthog/temporal/data_imports/sources/gitlab/source.py
+++ b/posthog/temporal/data_imports/sources/gitlab/source.py
@@ -1,29 +1,142 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
from posthog.temporal.data_imports.sources.generated_configs import GitLabSourceConfig
+from posthog.temporal.data_imports.sources.gitlab.gitlab import (
+ HOST_NOT_ALLOWED_ERROR,
+ HTTP_NOT_ALLOWED_ERROR,
+ GitLabResumeConfig,
+ gitlab_source,
+ validate_credentials as validate_gitlab_credentials,
+)
+from posthog.temporal.data_imports.sources.gitlab.settings import ENDPOINTS, INCREMENTAL_FIELDS
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class GitLabSource(SimpleSource[GitLabSourceConfig]):
+class GitLabSource(ResumableSource[GitLabSourceConfig, GitLabResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.GITLAB
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # `gitlab_host` is where the stored token is sent; retargeting it must re-require the token.
+ return ["gitlab_host"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.GIT_LAB,
label="GitLab",
- iconPath="/static/services/gitlab.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Sync issues, merge requests, commits, pipelines, and more from a GitLab project.
+
+Create a personal access token in your GitLab **User settings > Access tokens** with the `read_api` scope.
+For self-managed GitLab, set the instance URL (for example `https://gitlab.example.com`); leave it as `https://gitlab.com` for GitLab.com.""",
+ iconPath="/static/services/gitlab.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/gitlab",
unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="gitlab_host",
+ label="GitLab instance URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://gitlab.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="personal_access_token",
+ label="Personal access token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="glpat-...",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="project",
+ label="Project",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="group/project or numeric project id",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid GitLab personal access token. Please generate a new token and reconnect.",
+ "403 Client Error": "Your GitLab token lacks the required permissions (needs the `read_api` scope). Please check the token and try again.",
+ "404 Client Error": "Project not found. Please verify the project id/path and the token's access.",
+ HOST_NOT_ALLOWED_ERROR: "The GitLab host is not allowed. Please use a publicly reachable instance URL.",
+ HTTP_NOT_ALLOWED_ERROR: "The GitLab host must use HTTPS. Please update the instance URL to use https://.",
+ }
+
+ def get_schemas(
+ self,
+ config: GitLabSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ supports_append=bool(INCREMENTAL_FIELDS.get(endpoint)),
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: GitLabSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_gitlab_credentials(config.gitlab_host, config.personal_access_token, config.project, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GitLabResumeConfig]:
+ return ResumableSourceManager[GitLabResumeConfig](inputs, GitLabResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: GitLabSourceConfig,
+ resumable_source_manager: ResumableSourceManager[GitLabResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return gitlab_source(
+ host=config.gitlab_host,
+ personal_access_token=config.personal_access_token,
+ project=config.project,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
diff --git a/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab.py b/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab.py
new file mode 100644
index 000000000000..a503bf07a888
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab.py
@@ -0,0 +1,528 @@
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import pytest
+from unittest import mock
+
+from posthog.temporal.data_imports.sources.gitlab import gitlab as gitlab_module
+from posthog.temporal.data_imports.sources.gitlab.gitlab import (
+ HOST_NOT_ALLOWED_ERROR,
+ GitLabResumeConfig,
+ _build_initial_params,
+ _build_initial_url,
+ _encode_project,
+ _format_incremental_value,
+ _get_headers,
+ _parse_next_url,
+ get_rows,
+ gitlab_source,
+ normalize_host,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.gitlab.settings import GITLAB_ENDPOINTS
+
+
+def _response(
+ *, status_code: int = 200, json_data: Any = None, link: Optional[str] = None, text: str = ""
+) -> mock.MagicMock:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ response.ok = 200 <= status_code < 400
+ response.is_redirect = status_code in (301, 302, 303, 307, 308)
+ response.is_permanent_redirect = status_code in (301, 308)
+ response.text = text
+ response.json.return_value = json_data
+ response.headers = {"Link": link} if link else {}
+ return response
+
+
+class _FakeBatcher:
+ """Yields whatever is buffered on every ``should_yield`` check, so the per-item save_state
+ path in ``get_rows`` is exercised without needing thousands of rows."""
+
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
+ self._buf: list[Any] = []
+
+ def batch(self, item: Any) -> None:
+ self._buf.append(item)
+
+ def should_yield(self, include_incomplete_chunk: bool = False) -> bool:
+ return len(self._buf) > 0
+
+ def get_table(self) -> list[Any]:
+ rows, self._buf = self._buf, []
+ return rows
+
+
+class TestNormalizeHost:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ (None, "https://gitlab.com"),
+ ("", "https://gitlab.com"),
+ ("gitlab.com", "https://gitlab.com"),
+ ("https://gitlab.com", "https://gitlab.com"),
+ ("https://gitlab.com/", "https://gitlab.com"),
+ (" gitlab.example.com ", "https://gitlab.example.com"),
+ ("https://gitlab.example.com/api/v4", "https://gitlab.example.com"),
+ ("http://gitlab.example.com:8080/api/v4/", "http://gitlab.example.com:8080"),
+ ],
+ )
+ def test_normalize_host(self, raw, expected):
+ assert normalize_host(raw) == expected
+
+
+class TestGetHeaders:
+ def test_uses_authorization_bearer_not_private_token(self):
+ # The token must ride the `Authorization` header so the tracked transport's sample scrubber
+ # redacts it; `PRIVATE-TOKEN` is not on the scrubber's denylist and would leak the token.
+ headers = _get_headers("glpat-secret")
+ assert headers["Authorization"] == "Bearer glpat-secret"
+ assert "PRIVATE-TOKEN" not in headers
+
+
+class TestEncodeProject:
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("278964", "278964"),
+ ("group/project", "group%2Fproject"),
+ ("/group/sub/project/", "group%2Fsub%2Fproject"),
+ (" group/project ", "group%2Fproject"),
+ ],
+ )
+ def test_encode_project(self, raw, expected):
+ assert _encode_project(raw) == expected
+
+
+class TestFormatIncrementalValue:
+ @pytest.mark.parametrize(
+ "value, expected",
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("already-a-cursor", "already-a-cursor"),
+ ],
+ )
+ def test_format(self, value, expected):
+ assert _format_incremental_value(value) == expected
+
+ def test_no_offset_suffix(self):
+ assert "+00:00" not in _format_incremental_value(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestBuildInitialParams:
+ def test_issues_incremental_updated_at(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["issues"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert params["updated_after"] == "2024-01-01T00:00:00Z"
+ assert params["order_by"] == "updated_at"
+ assert params["sort"] == "asc"
+ assert params["per_page"] == 100
+
+ def test_issues_incremental_created_at_uses_created_after(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["issues"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert params["created_after"] == "2024-01-01T00:00:00Z"
+ assert params["order_by"] == "created_at"
+ assert "updated_after" not in params
+
+ def test_issues_full_refresh_uses_stable_order_by(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["issues"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert "updated_after" not in params and "created_after" not in params
+ assert params["order_by"] == "created_at"
+ assert params["sort"] == "asc"
+
+ def test_incremental_without_watermark_has_no_filter(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["issues"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="updated_at",
+ )
+ assert "updated_after" not in params
+ assert params["order_by"] == "created_at"
+
+ def test_commits_incremental_uses_since_and_no_order_by(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["commits"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="created_at",
+ )
+ assert params["since"] == "2024-01-01T00:00:00Z"
+ assert "order_by" not in params
+ assert "sort" not in params
+
+ def test_pipelines_incremental_uses_updated_after(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["pipelines"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="updated_at",
+ )
+ assert params["updated_after"] == "2024-01-01T00:00:00Z"
+ assert params["order_by"] == "updated_at"
+ assert params["sort"] == "asc"
+
+ def test_full_refresh_endpoint_only_per_page(self):
+ params = _build_initial_params(
+ GITLAB_ENDPOINTS["releases"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field=None,
+ )
+ assert params == {"per_page": 100}
+
+ def test_unsupported_incremental_field_raises(self):
+ with pytest.raises(ValueError):
+ _build_initial_params(
+ GITLAB_ENDPOINTS["issues"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="merged_at",
+ )
+
+
+class TestBuildInitialUrl:
+ def test_builds_url_with_params_and_encoded_project(self):
+ url = _build_initial_url("https://gitlab.com", GITLAB_ENDPOINTS["issues"], "group/project", {"per_page": 100})
+ assert url == "https://gitlab.com/api/v4/projects/group%2Fproject/issues?per_page=100"
+
+ def test_builds_url_without_params(self):
+ url = _build_initial_url("gitlab.example.com", GITLAB_ENDPOINTS["branches"], "42", {})
+ assert url == "https://gitlab.example.com/api/v4/projects/42/repository/branches"
+
+
+class TestParseNextUrl:
+ @pytest.mark.parametrize(
+ "header, expected",
+ [
+ ("", None),
+ ('<https://gitlab.com/api/v4/projects/1/issues?page=1>; rel="first"', None),
+ (
+ '<https://gitlab.com/api/v4/projects/1/issues?page=2>; rel="next", '
+ '<https://gitlab.com/api/v4/projects/1/issues?page=1>; rel="first"',
+ "https://gitlab.com/api/v4/projects/1/issues?page=2",
+ ),
+ ],
+ )
+ def test_parse(self, header, expected):
+ assert _parse_next_url(header) == expected
+
+
+class TestValidateCredentials:
+ def _patch_session(self, response=None, raises=None):
+ session = mock.MagicMock()
+ if raises is not None:
+ session.get.side_effect = raises
+ else:
+ session.get.return_value = response
+ return mock.patch.object(gitlab_module, "make_tracked_session", return_value=session)
+
+ @pytest.mark.parametrize(
+ "status_code, expected_valid, expected_msg_substr",
+ [
+ (200, True, None),
+ (401, False, "Invalid GitLab personal access token"),
+ (404, False, "not found"),
+ ],
+ )
+ def test_status_code_mapping(self, status_code, expected_valid, expected_msg_substr):
+ with self._patch_session(_response(status_code=status_code)):
+ valid, msg = validate_credentials("https://gitlab.com", "tok", "group/project")
+ assert valid is expected_valid
+ if expected_msg_substr is None:
+ assert msg is None
+ else:
+ assert expected_msg_substr in (msg or "")
+
+ @pytest.mark.parametrize(
+ "host, token, project, expected_msg",
+ [
+ ("https://gitlab.com", "", "group/project", "Missing personal access token"),
+ ("https://gitlab.com", "tok", " ", "Missing project id or path"),
+ ],
+ )
+ def test_missing_inputs_short_circuit(self, host, token, project, expected_msg):
+ valid, msg = validate_credentials(host, token, project)
+ assert valid is False
+ assert msg == expected_msg
+
+ def test_request_exception_returns_failure(self):
+ import requests
+
+ with self._patch_session(raises=requests.exceptions.ConnectionError("boom")):
+ valid, msg = validate_credentials("https://gitlab.com", "tok", "group/project")
+ assert valid is False
+ assert "boom" in (msg or "")
+
+ def test_rejects_redirect_response(self):
+ with self._patch_session(_response(status_code=302)) as patched:
+ valid, msg = validate_credentials("https://gitlab.com", "tok", "group/project")
+ assert valid is False
+ assert msg == gitlab_module.HOST_NOT_ALLOWED_ERROR
+ assert patched.return_value.get.call_args.kwargs["allow_redirects"] is False
+
+ def test_blocks_unsafe_host(self):
+ with (
+ mock.patch.object(gitlab_module, "_is_host_safe", return_value=(False, "internal address")),
+ self._patch_session(_response(status_code=200)) as patched,
+ ):
+ valid, msg = validate_credentials("https://10.0.0.1", "tok", "group/project", team_id=99)
+ assert valid is False
+ assert msg == "internal address"
+ patched.return_value.get.assert_not_called()
+
+ @pytest.mark.parametrize("host", ["http://gitlab.example.com", "http://gitlab.example.com:8080/api/v4"])
+ def test_rejects_plaintext_http(self, host):
+ # The token rides the Authorization header, so a plaintext HTTP host must be refused before
+ # any request is issued.
+ with self._patch_session(_response(status_code=200)) as patched:
+ valid, msg = validate_credentials(host, "tok", "group/project")
+ assert valid is False
+ assert msg == gitlab_module.HTTP_NOT_ALLOWED_ERROR
+ patched.return_value.get.assert_not_called()
+
+
+class TestGitLabSourceResponse:
+ @pytest.mark.parametrize(
+ "endpoint, primary_key, partition_key, sort_mode",
+ [
+ ("issues", "id", "created_at", "asc"),
+ ("merge_requests", "id", "created_at", "asc"),
+ ("commits", "id", "created_at", "desc"),
+ ("pipelines", "id", "created_at", "asc"),
+ ("releases", "tag_name", "created_at", "asc"),
+ ("milestones", "id", "created_at", "asc"),
+ ("branches", "name", None, "asc"),
+ ("tags", "name", None, "asc"),
+ ("labels", "id", None, "asc"),
+ ("members", "id", None, "asc"),
+ ],
+ )
+ def test_response_shape(self, endpoint, primary_key, partition_key, sort_mode):
+ response = gitlab_source(
+ host="https://gitlab.com",
+ personal_access_token="tok",
+ project="group/project",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=mock.MagicMock(),
+ team_id=1,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == [primary_key]
+ assert response.sort_mode == sort_mode
+ if partition_key:
+ assert response.partition_keys == [partition_key]
+ assert response.partition_mode == "datetime"
+ else:
+ assert response.partition_keys is None
+ assert response.partition_mode is None
+
+
+class TestGetRows:
+ def _run(self, manager, responses, endpoint="issues"):
+ session = mock.MagicMock()
+ session.get.side_effect = responses
+ with (
+ mock.patch.object(gitlab_module, "make_tracked_session", return_value=session),
+ mock.patch.object(gitlab_module, "Batcher", _FakeBatcher),
+ ):
+ rows: list[Any] = []
+ for table in get_rows(
+ host="https://gitlab.com",
+ personal_access_token="tok",
+ project="group/project",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ ):
+ rows.extend(table)
+ return rows, session
+
+ def test_follows_link_header_across_pages(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _response(
+ json_data=[{"id": 1}, {"id": 2}],
+ link='<https://gitlab.com/api/v4/projects/1/issues?page=2>; rel="next"',
+ )
+ page2 = _response(json_data=[{"id": 3}])
+ rows, session = self._run(manager, [page1, page2])
+
+ assert [r["id"] for r in rows] == [1, 2, 3]
+ second_url = session.get.call_args_list[1].args[0]
+ assert second_url == "https://gitlab.com/api/v4/projects/1/issues?page=2"
+
+ def test_saves_state_after_yielding(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ self._run(manager, [_response(json_data=[{"id": 1}])])
+
+ assert manager.save_state.called
+ saved = manager.save_state.call_args.args[0]
+ assert isinstance(saved, GitLabResumeConfig)
+
+ def test_resumes_from_saved_state(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = GitLabResumeConfig(
+ next_url="https://gitlab.com/api/v4/projects/1/issues?page=5"
+ )
+ rows, session = self._run(manager, [_response(json_data=[{"id": 9}])])
+
+ first_url = session.get.call_args_list[0].args[0]
+ assert first_url == "https://gitlab.com/api/v4/projects/1/issues?page=5"
+ assert [r["id"] for r in rows] == [9]
+
+ def test_empty_page_terminates(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ empty = _response(
+ json_data=[],
+ link='<https://gitlab.com/api/v4/projects/1/issues?page=2>; rel="next"',
+ )
+ rows, session = self._run(manager, [empty])
+
+ assert rows == []
+ assert session.get.call_count == 1
+
+ def test_does_not_follow_next_url_on_foreign_host(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _response(
+ json_data=[{"id": 1}],
+ link='<http://169.254.169.254/latest/meta-data/>; rel="next"',
+ )
+ rows, session = self._run(manager, [page1])
+
+ assert [r["id"] for r in rows] == [1]
+ assert session.get.call_count == 1
+
+ def test_ignores_resume_url_on_foreign_host(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = GitLabResumeConfig(next_url="http://169.254.169.254/latest/meta-data/")
+ rows, session = self._run(manager, [_response(json_data=[{"id": 1}])])
+
+ first_url = session.get.call_args_list[0].args[0]
+ assert first_url.startswith("https://gitlab.com/api/v4/projects/group%2Fproject/issues")
+ assert [r["id"] for r in rows] == [1]
+
+ def test_does_not_follow_plaintext_next_url_on_same_host(self):
+ # A Link header that downgrades to http on the configured host must not receive the token.
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ page1 = _response(
+ json_data=[{"id": 1}],
+ link='<http://gitlab.com/api/v4/projects/1/issues?page=2>; rel="next"',
+ )
+ rows, session = self._run(manager, [page1])
+
+ assert [r["id"] for r in rows] == [1]
+ assert session.get.call_count == 1
+
+ def test_ignores_plaintext_resume_url_on_same_host(self):
+ # A saved resume URL that downgraded to http must be ignored in favour of the https initial URL.
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = True
+ manager.load_state.return_value = GitLabResumeConfig(
+ next_url="http://gitlab.com/api/v4/projects/1/issues?page=5"
+ )
+ rows, session = self._run(manager, [_response(json_data=[{"id": 1}])])
+
+ first_url = session.get.call_args_list[0].args[0]
+ assert first_url.startswith("https://gitlab.com/api/v4/projects/group%2Fproject/issues")
+ assert [r["id"] for r in rows] == [1]
+
+ def test_does_not_follow_redirects(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ with pytest.raises(gitlab_module.GitLabHostNotAllowedError) as exc:
+ self._run(manager, [_response(status_code=302)])
+ # Message carries the non-retryable marker so the workflow fails fast on SSRF/redirect.
+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)
+
+ def test_unsafe_host_error_is_marked_non_retryable(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ with (
+ mock.patch.object(gitlab_module, "_is_host_safe", return_value=(False, "internal address")),
+ pytest.raises(gitlab_module.GitLabHostNotAllowedError) as exc,
+ ):
+ self._run(manager, [_response(json_data=[{"id": 1}])])
+ assert HOST_NOT_ALLOWED_ERROR in str(exc.value)
+
+ def test_rejects_plaintext_http_before_request(self):
+ # A plaintext HTTP host must be refused at run time (host could have been edited after
+ # source creation) before the token-bearing request goes out.
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ session = mock.MagicMock()
+ with (
+ mock.patch.object(gitlab_module, "make_tracked_session", return_value=session),
+ mock.patch.object(gitlab_module, "Batcher", _FakeBatcher),
+ pytest.raises(gitlab_module.GitLabHostNotAllowedError) as exc,
+ ):
+ list(
+ get_rows(
+ host="http://gitlab.example.com",
+ personal_access_token="tok",
+ project="group/project",
+ endpoint="issues",
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ team_id=1,
+ )
+ )
+ assert gitlab_module.HTTP_NOT_ALLOWED_ERROR in str(exc.value)
+ session.get.assert_not_called()
+
+ def test_passes_allow_redirects_false(self):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ _rows, session = self._run(manager, [_response(json_data=[{"id": 1}])])
+ assert session.get.call_args.kwargs["allow_redirects"] is False
+
+
+class TestRetryAfter:
+ @pytest.mark.parametrize(
+ "header, expected",
+ [
+ ({"Retry-After": "5"}, 5.0),
+ ({"Retry-After": " 9 "}, 9.0),
+ ({"Retry-After": "100000"}, 60.0), # capped
+ ({"Retry-After": "Wed, 21 Oct 2025 07:28:00 GMT"}, None), # HTTP-date ignored
+ ({}, None),
+ ],
+ )
+ def test_parse_retry_after(self, header, expected):
+ from posthog.temporal.data_imports.sources.gitlab.gitlab import _parse_retry_after
+
+ response = mock.MagicMock()
+ response.headers = header
+ assert _parse_retry_after(response) == expected
+
+ def test_retry_wait_prefers_retry_after(self):
+ from posthog.temporal.data_imports.sources.gitlab.gitlab import GitLabRetryableError, _retry_wait
+
+ state = mock.MagicMock()
+ state.outcome.exception.return_value = GitLabRetryableError("rate limited", retry_after=7.0)
+ assert _retry_wait(state) == 7.0
diff --git a/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py b/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py
new file mode 100644
index 000000000000..8920bdd28128
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/gitlab/tests/test_gitlab_source.py
@@ -0,0 +1,150 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.gitlab.gitlab import GitLabResumeConfig
+from posthog.temporal.data_imports.sources.gitlab.settings import ENDPOINTS
+from posthog.temporal.data_imports.sources.gitlab.source import GitLabSource
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+
+class TestGitLabSource:
+ def setup_method(self):
+ self.source = GitLabSource()
+ self.team_id = 123
+ self.config = mock.MagicMock()
+ self.config.gitlab_host = "https://gitlab.com"
+ self.config.personal_access_token = "glpat-token"
+ self.config.project = "group/project"
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.GITLAB
+
+ def test_connection_host_fields(self):
+ assert self.source.connection_host_fields == ["gitlab_host"]
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "GitLab"
+ assert config.label == "GitLab"
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/gitlab.svg"
+
+ field_names = [f.name for f in config.fields]
+ assert field_names == ["gitlab_host", "personal_access_token", "project"]
+
+ host_field, token_field, project_field = config.fields
+ assert isinstance(host_field, SourceFieldInputConfig)
+ assert host_field.type == SourceFieldInputConfigType.TEXT
+ assert host_field.required is False
+ assert host_field.secret is False
+
+ assert isinstance(token_field, SourceFieldInputConfig)
+ assert token_field.type == SourceFieldInputConfigType.PASSWORD
+ assert token_field.secret is True
+ assert token_field.required is True
+
+ assert isinstance(project_field, SourceFieldInputConfig)
+ assert project_field.required is True
+ assert project_field.secret is False
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error", "404 Client Error"])
+ def test_non_retryable_errors(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self):
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "endpoint, incremental",
+ [
+ ("issues", True),
+ ("merge_requests", True),
+ ("commits", True),
+ ("pipelines", True),
+ ("releases", False),
+ ("milestones", False),
+ ("branches", False),
+ ("tags", False),
+ ("labels", False),
+ ("members", False),
+ ],
+ )
+ def test_schema_incremental_support(self, endpoint, incremental):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert schemas[endpoint].supports_incremental is incremental
+ assert schemas[endpoint].supports_append is incremental
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["issues"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "issues"
+
+ def test_get_schemas_unknown_name_returns_empty(self):
+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []
+
+ @pytest.mark.parametrize(
+ "mock_return, expected",
+ [
+ ((True, None), (True, None)),
+ ((False, "Invalid GitLab personal access token"), (False, "Invalid GitLab personal access token")),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.gitlab.source.validate_gitlab_credentials")
+ def test_validate_credentials(self, mock_validate, mock_return, expected):
+ mock_validate.return_value = mock_return
+
+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="issues")
+
+ assert result == expected
+ mock_validate.assert_called_once_with(
+ self.config.gitlab_host, self.config.personal_access_token, self.config.project, self.team_id
+ )
+
+ def test_get_resumable_source_manager(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is GitLabResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.gitlab.source.gitlab_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_gitlab_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "issues"
+ inputs.team_id = 42
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"
+ inputs.incremental_field = "updated_at"
+
+ manager = mock.MagicMock()
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_gitlab_source.assert_called_once()
+ kwargs = mock_gitlab_source.call_args.kwargs
+ assert kwargs["host"] == "https://gitlab.com"
+ assert kwargs["personal_access_token"] == "glpat-token"
+ assert kwargs["project"] == "group/project"
+ assert kwargs["endpoint"] == "issues"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["team_id"] == 42
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2024-01-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "updated_at"
+
+ @mock.patch("posthog.temporal.data_imports.sources.gitlab.source.gitlab_source")
+ def test_source_for_pipeline_omits_last_value_when_not_incremental(self, mock_gitlab_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "branches"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "ignored"
+ inputs.incremental_field = None
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_gitlab_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
index ec019529010d..212cb9467b19 100644
--- a/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
+++ b/posthog/temporal/data_imports/sources/tests/test_generated_configs.py
@@ -2,6 +2,7 @@ from posthog.temporal.data_imports.sources.generated_configs import (
BigQuerySourceConfig,
ChargebeeSourceConfig,
DoItSourceConfig,
+ GitLabSourceConfig,
GoogleAdsSourceConfig,
GoogleSheetsSourceConfig,
GorgiasSourceConfig,
@@ -63,6 +64,20 @@ def test_doit_config():
assert config.api_key == "api_key"
+def test_gitlab_config():
+ config = GitLabSourceConfig.from_dict(
+ {"personal_access_token": "glpat-token", "project": "group/project", "gitlab_host": "https://gitlab.com"}
+ )
+ assert config.personal_access_token == "glpat-token"
+ assert config.project == "group/project"
+ assert config.gitlab_host == "https://gitlab.com"
+
+
+def test_gitlab_config_without_host():
+ config = GitLabSourceConfig.from_dict({"personal_access_token": "glpat-token", "project": "42"})
+ assert config.gitlab_host is None
+
+
def test_google_ads_config():
config = GoogleAdsSourceConfig.from_dict({"customer_id": "123", "google_ads_integration_id": 1})
assert config.customer_id == "123"