: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement gitea import source (#71235)
Tom Owers574388d4307d
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 4a5cfb359d00..7758c8a0fb8a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -217,6 +217,7 @@ the row lists both.| gainsight_px | HTTP | requests | ✅ || gerrit | HTTP | requests | ✅ || gitbook | HTTP | requests | ✅ |+| gitea | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || github | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || giphy | HTTP | requests | ✅ || gitlab | HTTP | requests | ✅ |diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex b53085a7b5a9..dedbd076ac0f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -1727,7 +1727,9 @@ class GitLabSourceConfig(config.Config):@config.configclass GiteaSourceConfig(config.Config):- pass+ base_url: str+ access_token: str+ repository: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.pynew file mode 100644index 000000000000..ae17c9297c75--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/canonical_descriptions.py@@ -0,0 +1,121 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "issues": {+ "description": "Issues opened in the repository, excluding pull requests.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/issue/operation/issueListIssues",+ "columns": {+ "id": "Unique identifier of the issue across the Gitea instance.",+ "number": "Issue number, unique within the repository.",+ "title": "Title of the issue.",+ "body": "Issue description in Markdown.",+ "state": "Current state of the issue: open or closed.",+ "user": "User who opened the issue.",+ "assignee": "User the issue is assigned to, if any.",+ "assignees": "All users the issue is assigned to.",+ "labels": "Labels attached to the issue.",+ "milestone": "Milestone the issue belongs to, if any.",+ "comments": "Number of comments on the issue.",+ "is_locked": "Whether the issue conversation is locked.",+ "due_date": "Due date set on the issue, if any.",+ "created_at": "When the issue was created.",+ "updated_at": "When the issue was last updated.",+ "closed_at": "When the issue was closed, if it is closed.",+ "html_url": "Web URL of the issue on the Gitea instance.",+ },+ },+ "pull_requests": {+ "description": "Pull requests opened against the repository, in any state.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/repository/operation/repoListPullRequests",+ "columns": {+ "id": "Unique identifier of the pull request across the Gitea instance.",+ "number": "Pull request number, unique within the repository.",+ "title": "Title of the pull request.",+ "body": "Pull request description in Markdown.",+ "state": "Current state of the pull request: open or closed.",+ "draft": "Whether the pull request is a draft.",+ "merged": "Whether the pull request has been merged.",+ "merged_at": "When the pull request was merged, if it was.",+ "merged_by": "User who merged the pull request.",+ "merge_commit_sha": "SHA of the merge commit, if merged.",+ "mergeable": "Whether the pull request can be merged cleanly.",+ "base": "Base branch the pull request targets.",+ "head": "Head branch the pull request is from.",+ "user": "User who opened the pull request.",+ "assignees": "All users the pull request is assigned to.",+ "requested_reviewers": "Users whose review has been requested.",+ "labels": "Labels attached to the pull request.",+ "milestone": "Milestone the pull request belongs to, if any.",+ "comments": "Number of comments on the pull request.",+ "review_comments": "Number of review comments on the pull request.",+ "created_at": "When the pull request was created.",+ "updated_at": "When the pull request was last updated.",+ "closed_at": "When the pull request was closed, if it is closed.",+ "html_url": "Web URL of the pull request on the Gitea instance.",+ },+ },+ "commits": {+ "description": "Commits on the repository's default branch.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/repository/operation/repoGetAllCommits",+ "columns": {+ "sha": "Commit SHA — the unique identifier of the commit.",+ "created": "Commit timestamp.",+ "message": "Commit message.",+ "author_name": "Name from the commit's git author identity.",+ "author_email": "Email from the commit's git author identity.",+ "committer_name": "Name from the commit's git committer identity.",+ "committer_email": "Email from the commit's git committer identity.",+ "author_id": "Gitea user id of the author, when the git identity maps to an account.",+ "author_login": "Gitea username of the author, when the git identity maps to an account.",+ "committer_id": "Gitea user id of the committer, when the git identity maps to an account.",+ "committer_login": "Gitea username of the committer, when the git identity maps to an account.",+ "parents": "Parent commits of this commit.",+ "html_url": "Web URL of the commit on the Gitea instance.",+ },+ },+ "releases": {+ "description": "Releases published in the repository, including drafts and pre-releases.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/repository/operation/repoListReleases",+ "columns": {+ "id": "Unique identifier of the release.",+ "tag_name": "Git tag the release is attached to.",+ "target_commitish": "Branch or commit the release targets.",+ "name": "Title of the release.",+ "body": "Release notes in Markdown.",+ "draft": "Whether the release is an unpublished draft.",+ "prerelease": "Whether the release is marked as a pre-release.",+ "author": "User who created the release.",+ "assets": "Files attached to the release.",+ "created_at": "When the release's tagged commit was created.",+ "published_at": "When the release was published.",+ },+ },+ "labels": {+ "description": "Issue and pull request labels defined in the repository.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/issue/operation/issueListLabels",+ "columns": {+ "id": "Unique identifier of the label.",+ "name": "Label name.",+ "color": "Label color as a hex code.",+ "description": "Label description.",+ "exclusive": "Whether the label is part of an exclusive scoped group.",+ "is_archived": "Whether the label is archived.",+ },+ },+ "milestones": {+ "description": "Milestones defined in the repository, in any state.",+ "docs_url": "https://docs.gitea.com/api/1.24/#tag/issue/operation/issueGetMilestonesList",+ "columns": {+ "id": "Unique identifier of the milestone.",+ "title": "Title of the milestone.",+ "description": "Milestone description.",+ "state": "Current state of the milestone: open or closed.",+ "open_issues": "Number of open issues in the milestone.",+ "closed_issues": "Number of closed issues in the milestone.",+ "due_on": "Due date of the milestone, if any.",+ "closed_at": "When the milestone was closed, if it is closed.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.pynew file mode 100644index 000000000000..881c7daec1fe--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/gitea.py@@ -0,0 +1,576 @@+import re+import dataclasses+from collections.abc import AsyncIterator, Callable, Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode, urlparse++import pyarrow as pa+import requests+from asgiref.sync import async_to_sync+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSyncResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.settings import (+ GITEA_ENDPOINTS,+ PAGE_SIZE,+ GiteaEndpointConfig,+)++GITEA_API_PATH = "/api/v1"+REQUEST_TIMEOUT_SECONDS = 60+# Gitea instances have no rate limiting by default, but admins can enable it and+# self-hosted boxes are often small — back off on 429/5xx.+MAX_RETRY_ATTEMPTS = 5++# Managing repo webhooks needs admin rights on the repository; a read-scoped token gets+# 403 (or 404 when the instance hides the resource entirely).+_WEBHOOK_PERMISSION_HINT = "admin access to the repository (or a token with the `write:repository` scope)"+++class GiteaRetryableError(Exception):+ pass+++class GiteaResumeConfig:+ next_url: str+++def normalize_host(host: str) -> str:+ """Normalize the instance URL and reject anything that isn't HTTPS.++ The access token travels in a header to a user-supplied host, so plaintext+ http:// is rejected to keep it off the wire in the clear. Bare hosts default+ to https.+ """+ host = host.strip()+ if not host:+ raise ValueError("Gitea instance URL is required")+ if "://" not in host:+ host = f"https://{host}"+ host = host.rstrip("/")+ # Reject characters that make urlparse (which the SSRF host check trusts) and the HTTP+ # client disagree on the target host. `https://169.254.169.254\@example.com` parses as+ # host example.com here while requests connects to 169.254.169.254 — a backslash or an+ # encoded authority delimiter is the wedge, so refuse them outright.+ lowered = host.lower()+ if "\\" in host or "%5c" in lowered or "%40" in lowered:+ raise ValueError(f"Invalid Gitea instance URL: {host}")+ try:+ parsed = urlparse(host)+ port = parsed.port+ except ValueError:+ raise ValueError(f"Invalid Gitea instance URL: {host}")+ if parsed.scheme != "https" or not parsed.hostname:+ raise ValueError(f"Invalid Gitea instance URL (must be https): {host}")+ # Credentials in the authority (user:pass@host) would ship the token to `host` while the+ # safety check could be aimed elsewhere; require the authority to be exactly host[:port].+ host_part = f"[{parsed.hostname}]" if ":" in parsed.hostname else parsed.hostname+ expected_netloc = host_part + (f":{port}" if port else "")+ if parsed.netloc.lower() != expected_netloc.lower():+ raise ValueError(f"Invalid Gitea instance URL: {host}")+ return host+++def hostname_of(host: str) -> str:+ return urlparse(normalize_host(host)).hostname or ""+++def _api_url(base_url: str, path: str) -> str:+ return f"{normalize_host(base_url)}{GITEA_API_PATH}{path}"+++def _get_session(access_token: str) -> requests.Session:+ # No-redirect session is an SSRF boundary: a user-supplied base_url must not be able+ # to bounce API calls (and the token header) to an internal host via a 3xx.+ return make_tracked_session(+ redact_values=(access_token,),+ headers={"Authorization": f"token {access_token}", "Accept": "application/json"},+ allow_redirects=False,+ )+++def _pinned_url(base_url: str, url: str) -> str:+ """Pin a pagination URL to the validated Gitea origin.++ next_url comes from the response's Link header (and is persisted in resume state), so a+ tampered response must not be able to redirect the token-bearing request to another host,+ port, or a plaintext http:// URL. Anything off the configured https origin is rejected.+ """+ base, target = urlparse(normalize_host(base_url)), urlparse(url)+ if target.scheme != "https" or target.netloc.lower() != base.netloc.lower():+ raise ValueError(f"Gitea pagination URL {url!r} is not on the configured instance {base_url!r}")+ return url+++def _parse_next_url(link_header: str) -> str | None:+ """Return the URL with rel="next" from Gitea'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 _format_timestamp(value: Any) -> str:+ """Format an incremental cursor as the RFC 3339 Z form Gitea's `since` expects."""+ if isinstance(value, datetime):+ dt = value if value.tzinfo else value.replace(tzinfo=UTC)+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")+ if isinstance(value, date):+ return value.strftime("%Y-%m-%dT00:00:00Z")+ return str(value)+++def _build_initial_url(+ config: GiteaEndpointConfig,+ base_url: str,+ repository: str,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> str:+ params: dict[str, Any] = {"limit": PAGE_SIZE, **config.extra_params}+ # `since` is inclusive, so the boundary row is re-fetched and deduped by primary key+ # on merge — safer than missing a row updated in the same second as the watermark.+ if config.supports_since and should_use_incremental_field and db_incremental_field_last_value is not None:+ params["since"] = _format_timestamp(db_incremental_field_last_value)+ path = config.path.format(repository=repository)+ return f"{_api_url(base_url, path)}?{urlencode(params)}"+++def validate_credentials(base_url: str, access_token: str, repository: str) -> tuple[bool, str | None]:+ """Confirm the token can read the configured repository."""+ url = _api_url(base_url, f"/repos/{repository}")+ try:+ response = _get_session(access_token).get(url, timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code == 401:+ return False, "Invalid Gitea access token"+ if response.status_code == 404:+ return False, f"Repository '{repository}' not found or not accessible with this token"+ if 300 <= response.status_code < 400:+ return False, "The Gitea instance URL redirected the request; enter the instance's canonical https URL"++ try:+ message = response.json().get("message", response.text)+ except Exception:+ message = response.text+ return False, message+++def _flatten_commit(item: dict[str, Any]) -> dict[str, Any]:+ """Lift the nested git author/committer info to top-level columns for easy querying."""+ commit_data = item.get("commit")+ if isinstance(commit_data, dict):+ item["message"] = commit_data.get("message")+ author = commit_data.get("author")+ if isinstance(author, dict):+ item["author_name"] = author.get("name")+ item["author_email"] = author.get("email")+ committer = commit_data.get("committer")+ if isinstance(committer, dict):+ item["committer_name"] = committer.get("name")+ item["committer_email"] = committer.get("email")++ # Top-level author/committer are Gitea user objects (null when the git identity+ # doesn't map to an instance account).+ user = item.get("author")+ if isinstance(user, dict):+ item["author_id"] = user.get("id")+ item["author_login"] = user.get("login")+ user = item.get("committer")+ if isinstance(user, dict):+ item["committer_id"] = user.get("id")+ item["committer_login"] = user.get("login")++ return item+++def _get_item_mapper(endpoint: str) -> Callable[[dict[str, Any]], dict[str, Any]] | None:+ if endpoint == "commits":+ return _flatten_commit+ return None+++@retry(+ retry=retry_if_exception_type(+ (+ GiteaRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=2, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, url: str, logger: FilteringBoundLogger) -> requests.Response:+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise GiteaRetryableError(f"Gitea API error (retryable): status={response.status_code}, url={url}")++ # The session never follows redirects (SSRF boundary); a 3xx means the instance is+ # pointing us elsewhere, so treat it as a hard upstream error.+ if 300 <= response.status_code < 400:+ raise ValueError(f"Gitea API returned an unexpected redirect: status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"Gitea API error: status={response.status_code}, body={response.text[:500]}, url={url}")+ response.raise_for_status()++ return response+++def get_rows(+ base_url: str,+ access_token: str,+ repository: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GiteaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[list[dict[str, Any]]]:+ config = GITEA_ENDPOINTS[endpoint]+ session = _get_session(access_token)+ item_mapper = _get_item_mapper(endpoint)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume_config is not None:+ url: str = _pinned_url(base_url, resume_config.next_url)+ logger.debug(f"Gitea: resuming from URL: {url}")+ else:+ url = _build_initial_url(+ config, base_url, repository, should_use_incremental_field, db_incremental_field_last_value+ )++ while True:+ response = _fetch_page(session, url, logger)+ data = response.json()+ if not isinstance(data, list) or not data:+ return++ rows = [item_mapper(item) if item_mapper else item for item in data if isinstance(item, dict)]+ next_url = _parse_next_url(response.headers.get("Link", ""))+ if next_url is not None:+ next_url = _pinned_url(base_url, next_url)++ if rows:+ yield rows++ if not next_url:+ return++ # Save state AFTER yielding so a crash re-yields the in-flight page+ # (merge dedupes on primary key).+ resumable_source_manager.save_state(GiteaResumeConfig(next_url=next_url))+ url = next_url+++def _make_webhook_dedupe_transformer(primary_key: str, version_keys: list[str]) -> Callable[[pa.Table], pa.Table]:+ """Collapse a webhook batch to one row per ``primary_key`` — the one ranking newest by+ ``version_keys`` (newest first, NULLs last). Gitea emits one issue/PR as separate+ opened -> edited -> closed events sharing an id, and the delta merge doesn't dedupe+ within a source batch, so without this it keeps whichever event landed last in batch+ order and can freeze rows at a stale state."""++ def transform(table: pa.Table) -> pa.Table:+ present_version_keys = [key for key in version_keys if key in table.column_names]+ if table.num_rows == 0 or primary_key not in table.column_names or not present_version_keys:+ return table++ ids = table.column(primary_key).to_pylist()+ version_columns = [table.column(key).to_pylist() for key in present_version_keys]++ def rank(row_index: int) -> tuple[tuple[int, Any], ...]:+ # A present value beats NULL (NULLS LAST); among present values a larger one is+ # newer (ISO-8601 timestamps compare correctly as strings). The leading flag keeps+ # NULLs from ever being order-compared against a real value.+ return tuple(+ (1, column[row_index]) if column[row_index] is not None else (0, "") for column in version_columns+ )++ best_index_by_id: dict[Any, int] = {}+ for index, object_id in enumerate(ids):+ if object_id is None:+ continue+ best = best_index_by_id.get(object_id)+ # On a tie (>=, not >) the later-arriving row wins: timestamps are second-coarse,+ # and rows arrive in delivery order, so the later index is the newer event.+ if best is None or rank(index) >= rank(best):+ best_index_by_id[object_id] = index++ # Preserve input order among the survivors. Explicit int64 so an empty result doesn't+ # infer a null-typed index array.+ return table.take(pa.array(sorted(best_index_by_id.values()), type=pa.int64()))++ return transform+++def gitea_source(+ base_url: str,+ access_token: str,+ repository: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[GiteaResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ webhook_source_manager: Optional[WebhookSourceManager] = None,+) -> SourceResponse:+ endpoint_config = GITEA_ENDPOINTS[endpoint]++ # Steady-state webhook ingestion replaces the poll once the initial backfill is+ # complete and the schema is in webhook sync mode; otherwise the poll path runs.+ webhook_enabled = (+ async_to_sync(webhook_source_manager.webhook_enabled)() if webhook_source_manager is not None else False+ )++ def items() -> Iterator[Any] | AsyncIterator[Any]:+ if webhook_enabled:+ assert webhook_source_manager is not None+ # The Hog template lands the nested issue/pull_request object as the row, which+ # matches the polled REST shape (Gitea serializes one struct per resource for+ # both). Collapse each drain batch to the latest event per id.+ transformer = (+ _make_webhook_dedupe_transformer(endpoint_config.primary_key, endpoint_config.version_keys)+ if endpoint_config.version_keys+ else None+ )+ return webhook_source_manager.get_items(table_transformer=transformer)++ return get_rows(+ base_url=base_url,+ access_token=access_token,+ repository=repository,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ )++ return SourceResponse(+ name=endpoint,+ items=items,+ primary_keys=[endpoint_config.primary_key],+ # Incremental endpoints (issues, commits) arrive newest-first while filtering+ # server-side on `since`, so the watermark persists at end of run (desc). See+ # settings.py for the per-endpoint verification notes.+ 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,+ )+++def _is_repo_hook_permission_error(response: requests.Response) -> bool:+ """A token without repo admin rights can't manage webhooks — Gitea returns 403 (or 404+ when the resource is hidden from the token). Treat both as the permission case so+ callers fall back to manual setup instead of retrying."""+ return response.status_code in (403, 404)+++def create_repo_webhook(+ base_url: str, access_token: str, repository: str, webhook_url: str, events: list[str], secret: str+) -> WebhookCreationResult:+ """Create a repo webhook via POST /repos/{repository}/hooks.++ Returns a failed (not raised) result when the token lacks admin rights so the caller+ can surface a manual-setup caption instead of hard-failing.+ """+ payload = {+ "type": "gitea",+ "active": True,+ "branch_filter": "*",+ "events": events,+ "config": {+ "url": webhook_url,+ "content_type": "json",+ "secret": secret,+ },+ }++ try:+ response = _get_session(access_token).post(+ _api_url(base_url, f"/repos/{repository}/hooks"), json=payload, timeout=30+ )+ except requests.exceptions.RequestException as e:+ return WebhookCreationResult(success=False, error=f"Failed to create webhook automatically: {e}")++ if response.status_code in (200, 201):+ # Gitea never echoes the secret back, so return the one we generated as+ # extra_inputs — the framework persists it onto the hog function's signing_secret+ # input, which the template uses to verify X-Gitea-Signature.+ return WebhookCreationResult(success=True, extra_inputs={"signing_secret": secret})++ if _is_repo_hook_permission_error(response):+ return WebhookCreationResult(+ success=False,+ error=(+ f"Your Gitea token lacks {_WEBHOOK_PERMISSION_HINT} needed to create a repository webhook. "+ "Add it and reconnect, or set up the webhook manually following the steps below."+ ),+ )++ return WebhookCreationResult(+ success=False, error=f"Failed to create webhook automatically: {response.status_code} {response.text}"+ )+++def _list_repo_hooks(+ base_url: str, access_token: str, repository: str+) -> tuple[list[dict[str, Any]] | None, str | None]:+ """List repo webhooks via GET /repos/{repository}/hooks. Returns (hooks, error); error is+ ``"permission"`` when the token lacks admin rights so callers can fall back to manual setup."""+ try:+ response = _get_session(access_token).get(+ _api_url(base_url, f"/repos/{repository}/hooks?limit={PAGE_SIZE}"), timeout=30+ )+ except requests.exceptions.RequestException as e:+ return None, str(e)++ if _is_repo_hook_permission_error(response):+ return None, "permission"+ if not response.ok:+ return None, f"{response.status_code} {response.text}"++ hooks = response.json()+ return (hooks if isinstance(hooks, list) else []), None+++def _match_hook_by_url(hooks: list[dict[str, Any]], webhook_url: str) -> dict[str, Any] | None:+ for hook in hooks:+ # `config` can be present-but-null on some hook shapes; `or {}` guards the null case.+ if (hook.get("config") or {}).get("url") == webhook_url:+ return hook+ return None+++def delete_repo_webhook(base_url: str, access_token: str, repository: str, webhook_url: str) -> WebhookDeletionResult:+ """Find the repo webhook matching webhook_url and DELETE /repos/{repository}/hooks/{id}."""+ hooks, error = _list_repo_hooks(base_url, access_token, repository)+ if error == "permission":+ return WebhookDeletionResult(+ success=False,+ error=f"Your Gitea token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",+ )+ if error is not None:+ return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {error}")++ hook = _match_hook_by_url(hooks or [], webhook_url)+ if hook is None:+ # Nothing to delete — the end state we wanted.+ return WebhookDeletionResult(success=True)++ try:+ response = _get_session(access_token).delete(+ _api_url(base_url, f"/repos/{repository}/hooks/{hook['id']}"), timeout=30+ )+ except requests.exceptions.RequestException as e:+ return WebhookDeletionResult(success=False, error=f"Failed to delete webhook: {e}")++ # 404 here means the hook vanished between the list and the DELETE — also the end+ # state we wanted, so don't map it to the permission case.+ if response.status_code in (200, 204, 404):+ return WebhookDeletionResult(success=True)+ if response.status_code == 403:+ return WebhookDeletionResult(+ success=False,+ error=f"Your Gitea token lacks {_WEBHOOK_PERMISSION_HINT}. Please delete the webhook manually.",+ )+ return WebhookDeletionResult(+ success=False, error=f"Failed to delete webhook: {response.status_code} {response.text}"+ )+++def update_repo_webhook_events(+ base_url: str, access_token: str, repository: str, webhook_url: str, events: list[str]+) -> WebhookSyncResult:+ """Add ``events`` to the repo webhook matching ``webhook_url``, writing only on drift.++ Additive on purpose: the PATCH sends the union of current and desired events, so+ events the user subscribed themselves are never dropped. Permission errors return a+ failed (not raised) result so schema-enable can proceed with a warning."""+ if not events:+ return WebhookSyncResult(success=True)++ hooks, error = _list_repo_hooks(base_url, access_token, repository)+ if error == "permission":+ return WebhookSyncResult(+ success=False,+ error=(+ f"Your Gitea token lacks {_WEBHOOK_PERMISSION_HINT} needed to update the repository webhook. "+ f"Add it and reconnect, or add these events to the webhook manually: {', '.join(events)}."+ ),+ )+ if error is not None:+ return WebhookSyncResult(success=False, error=f"Failed to update webhook events: {error}")++ hook = _match_hook_by_url(hooks or [], webhook_url)+ if hook is None:+ # No matching webhook, so nothing to reconcile (creation is handled elsewhere).+ return WebhookSyncResult(success=True)++ current = set(hook.get("events") or [])+ if all(event in current for event in events):+ return WebhookSyncResult(success=True)++ merged = sorted(current | set(events))+ try:+ response = _get_session(access_token).patch(+ _api_url(base_url, f"/repos/{repository}/hooks/{hook['id']}"), json={"events": merged}, timeout=30+ )+ except requests.exceptions.RequestException as e:+ return WebhookSyncResult(success=False, error=f"Failed to update webhook events: {e}")++ if response.ok:+ return WebhookSyncResult(success=True)+ return WebhookSyncResult(+ success=False, error=f"Failed to update webhook events: {response.status_code} {response.text}"+ )+++def get_repo_webhook_info(base_url: str, access_token: str, repository: str, webhook_url: str) -> ExternalWebhookInfo:+ """List repo webhooks and match config.url == webhook_url."""+ hooks, error = _list_repo_hooks(base_url, access_token, repository)+ if error == "permission":+ return ExternalWebhookInfo(+ exists=False,+ error=f"Your Gitea token lacks {_WEBHOOK_PERMISSION_HINT} needed to read repository webhooks.",+ )+ if error is not None:+ return ExternalWebhookInfo(exists=False, error=f"Failed to check webhook status: {error}")++ hook = _match_hook_by_url(hooks or [], webhook_url)+ if hook is None:+ return ExternalWebhookInfo(exists=False)+ return ExternalWebhookInfo(+ exists=True,+ url=webhook_url,+ enabled_events=hook.get("events"),+ status="active" if hook.get("active") else "disabled",+ created_at=hook.get("created_at"),+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.pynew file mode 100644index 000000000000..e456096ddf85--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/settings.py@@ -0,0 +1,119 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++# Gitea's default MAX_RESPONSE_ITEMS is 50 — instances clamp larger `limit` values to it,+# so asking for more only produces confusing short pages.+PAGE_SIZE = 50+++@dataclass+class GiteaEndpointConfig:+ name: str+ path: str # Path template with a {repository} (owner/repo) placeholder+ incremental_fields: list[IncrementalField]+ default_incremental_field: Optional[str] = None+ partition_key: Optional[str] = None+ primary_key: str = "id"+ # The order rows actually arrive in from the API. Verified against a live instance —+ # Gitea ignores sort params on several list endpoints, so don't assume.+ sort_mode: Literal["asc", "desc"] = "asc"+ # True only when the endpoint honors the server-side `since` timestamp filter+ # (verified with a future-date probe; e.g. /pulls accepts `since` but ignores it).+ supports_since: bool = False+ # Extra static query params merged into every request.+ extra_params: dict[str, str] = field(default_factory=dict)+ # Webhook event name (the X-Gitea-Event header value) that can feed this table, if any.+ webhook_event: Optional[str] = None+ # Ordered columns (newest-first, NULLs last) ranking webhook events that share a primary+ # key, so a drain batch collapses to the latest state per id before the delta merge+ # (which doesn't dedupe within a batch).+ version_keys: Optional[list[str]] = None+++GITEA_ENDPOINTS: dict[str, GiteaEndpointConfig] = {+ "issues": GiteaEndpointConfig(+ name="issues",+ # type=issues excludes pull requests, which Gitea otherwise mixes into this list.+ path="/repos/{repository}/issues",+ extra_params={"state": "all", "type": "issues"},+ partition_key="created_at",+ # `since` filters server-side on the issue's updated time (inclusive); rows still+ # arrive newest-created-first, so the watermark persists at end of run (desc).+ supports_since=True,+ sort_mode="desc",+ default_incremental_field="updated_at",+ incremental_fields=[+ {+ "label": "updated_at",+ "type": IncrementalFieldType.DateTime,+ "field": "updated_at",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ webhook_event="issues",+ version_keys=["updated_at"],+ ),+ "pull_requests": GiteaEndpointConfig(+ name="pull_requests",+ # /pulls accepts `since` but silently ignores it (verified with a future-date probe),+ # so this table is full refresh only. sort=oldest gives stable created-asc pagination.+ path="/repos/{repository}/pulls",+ extra_params={"state": "all", "sort": "oldest"},+ partition_key="created_at",+ sort_mode="asc",+ incremental_fields=[],+ webhook_event="pull_request",+ version_keys=["updated_at"],+ ),+ "commits": GiteaEndpointConfig(+ name="commits",+ # stat/verification/files=false trims the per-commit payload (diff stats, GPG+ # verification, file lists) that the warehouse doesn't need.+ path="/repos/{repository}/commits",+ extra_params={"stat": "false", "verification": "false", "files": "false"},+ primary_key="sha",+ # Top-level `created` is the commit timestamp; the list always returns newest-first+ # (git log order) and `since` filters server-side on commit time.+ partition_key="created",+ supports_since=True,+ sort_mode="desc",+ default_incremental_field="created",+ incremental_fields=[+ {+ "label": "created",+ "type": IncrementalFieldType.DateTime,+ "field": "created",+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+ ),+ "releases": GiteaEndpointConfig(+ name="releases",+ # No server-side time filter — full refresh only (release lists are small).+ # The list arrives newest-first.+ path="/repos/{repository}/releases",+ partition_key="created_at",+ sort_mode="desc",+ incremental_fields=[],+ ),+ "labels": GiteaEndpointConfig(+ name="labels",+ # Labels carry no timestamps at all: full refresh, no partitioning.+ path="/repos/{repository}/labels",+ incremental_fields=[],+ ),+ "milestones": GiteaEndpointConfig(+ name="milestones",+ path="/repos/{repository}/milestones",+ extra_params={"state": "all"},+ incremental_fields=[],+ ),+}++ENDPOINTS = tuple(GITEA_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in GITEA_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.pyindex 02ef4c712ff1..50788e4703a0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/source.py@@ -1,30 +1,283 @@-from typing import cast+import secrets+from typing import TYPE_CHECKING, Optional, cast++if TYPE_CHECKING:+ from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDCfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (+ SourceInputs,+ SourceResponse,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (+ ExternalWebhookInfo,+ FieldType,+ ResumableSource,+ WebhookCreationResult,+ WebhookDeletionResult,+ WebhookSource,+ WebhookSyncResult,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import ValidateDatabaseHostMixinfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import WebhookSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GiteaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.gitea import (+ GiteaResumeConfig,+ create_repo_webhook,+ delete_repo_webhook,+ get_repo_webhook_info,+ gitea_source,+ hostname_of,+ update_repo_webhook_events,+ validate_credentials as validate_gitea_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.settings import (+ ENDPOINTS,+ GITEA_ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType+# Schemas that can be fed by Gitea webhooks, mapped to the X-Gitea-Event header value the+# webhook handler routes on (schema_mapping is keyed by these values).+GITEA_WEBHOOK_RESOURCE_MAP: dict[str, str] = {+ name: config.webhook_event for name, config in GITEA_ENDPOINTS.items() if config.webhook_event is not None+}+@SourceRegistry.register-class GiteaSource(SimpleSource[GiteaSourceConfig]):+class GiteaSource(+ ResumableSource[GiteaSourceConfig, GiteaResumeConfig],+ WebhookSource[GiteaSourceConfig],+ ValidateDatabaseHostMixin,+):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.GITEA+ @property+ def connection_host_fields(self) -> list[str]:+ # `base_url` decides where the stored token is sent; `repository` decides which repo that+ # token reads. Retargeting either lets an editor reuse a token they never entered against a+ # host they control or a private repo the token can reach — both must re-require the token.+ return ["base_url", "repository"]++ @property+ def webhook_template(self) -> Optional["HogFunctionTemplateDC"]:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.webhook_template import template++ return template++ @property+ def webhook_resource_map(self) -> dict[str, str]:+ return GITEA_WEBHOOK_RESOURCE_MAP+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.GITEA,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Gitea",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Connect a repository on your Gitea (or Forgejo) instance to sync issues, pull requests, commits, and more.++Create an access token under **Settings > Applications** on your instance with read access to the repository (the `read:repository` and `read:issue` scopes). The instance URL is your Gitea host, e.g. `https://gitea.example.com` — it must be reachable over https from the internet.""",iconPath="/static/services/gitea.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/gitea",+ keywords=["forgejo", "git"],+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="base_url",+ label="Instance URL",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="https://gitea.example.com",+ secret=False,+ ),+ SourceFieldInputConfig(+ name="access_token",+ label="Access token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="repository",+ label="Repository",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="owner/repo",+ secret=False,+ ),+ ],+ ),+ webhookSetupCaption="""To set up the webhook manually:++1. Go to your repository's **Settings > Webhooks** on your Gitea instance+2. Click **Add webhook** and choose **Gitea**+3. Paste the webhook URL shown below into the **Target URL** field+4. Set **HTTP method** to **POST** and **POST content type** to **application/json**+5. Enter a **Secret** and add the same value to the **Signing secret** field below+6. Under **Trigger on**, choose **Custom events** and tick **Issues** and **Pull request**+7. Click **Add webhook**++If automatic creation failed, your token needs admin access to the repository — add it and reconnect, or set the webhook up manually using the steps above.""",+ webhookFields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="signing_secret",+ label="Signing secret",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="your webhook secret",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Your Gitea access token is invalid or expired. Please generate a new token and reconnect.",+ "403 Client Error": "Your Gitea token does not have permission to access this resource. Please check the token's scopes and repository access.",+ "404 Client Error": "Repository not found. Please verify the instance URL, repository name, and token access.",+ "Invalid Gitea instance URL": "The Gitea instance URL is invalid. Please enter the instance's canonical https URL.",+ }++ def get_schemas(+ self,+ config: GiteaSourceConfig,+ 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)),+ supports_webhooks=endpoint in GITEA_WEBHOOK_RESOURCE_MAP,+ 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: GiteaSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ try:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.base_url), team_id)+ except ValueError:+ return False, "Invalid Gitea instance URL"+ if not host_valid:+ return False, host_error++ return validate_gitea_credentials(config.base_url, config.access_token, config.repository)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[GiteaResumeConfig]:+ return ResumableSourceManager[GiteaResumeConfig](inputs, GiteaResumeConfig)++ def get_webhook_source_manager(self, inputs: SourceInputs) -> WebhookSourceManager:+ return WebhookSourceManager(inputs, inputs.logger)++ def get_desired_webhook_events(+ self, config: GiteaSourceConfig, eligible_schema_names: list[str]+ ) -> list[str] | None:+ return [+ GITEA_WEBHOOK_RESOURCE_MAP[name] for name in eligible_schema_names if name in GITEA_WEBHOOK_RESOURCE_MAP+ ]++ def create_webhook(self, config: GiteaSourceConfig, webhook_url: str, team_id: int) -> WebhookCreationResult:+ # Gitea's webhook secret is creator-supplied, so mint one, hand it to Gitea as the+ # hook's config.secret, and return it via extra_inputs so it lands on the hog+ # function for signature verification.+ secret = secrets.token_hex(32)+ # Subscribe to every webhook-capable event, not just the enabled schemas: an+ # unmapped event no-ops in the hog function, so over-subscribing is harmless while+ # enabling a table later is free.+ events = self.get_desired_webhook_events(config, list(GITEA_WEBHOOK_RESOURCE_MAP.keys())) or []+ return create_repo_webhook(config.base_url, config.access_token, config.repository, webhook_url, events, secret)++ def sync_webhook_events(+ self,+ config: GiteaSourceConfig,+ webhook_url: str,+ team_id: int,+ eligible_schema_names: list[str],+ ) -> WebhookSyncResult:+ # Every mapped event, not just the enabled schemas': mirrors create_webhook's stance+ # and auto-heals webhooks created before GITEA_WEBHOOK_RESOURCE_MAP gained new events.+ desired_events = self.get_desired_webhook_events(config, list(GITEA_WEBHOOK_RESOURCE_MAP.keys())) or []+ return update_repo_webhook_events(+ config.base_url, config.access_token, config.repository, webhook_url, desired_events+ )++ def delete_webhook(self, config: GiteaSourceConfig, webhook_url: str, team_id: int) -> WebhookDeletionResult:+ return delete_repo_webhook(config.base_url, config.access_token, config.repository, webhook_url)++ def get_external_webhook_info(+ self, config: GiteaSourceConfig, webhook_url: str, team_id: int+ ) -> ExternalWebhookInfo:+ return get_repo_webhook_info(config.base_url, config.access_token, config.repository, webhook_url)++ def source_for_pipeline(+ self,+ config: GiteaSourceConfig,+ resumable_source_manager: ResumableSourceManager[GiteaResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ host_valid, host_error = self.is_database_host_valid(hostname_of(config.base_url), inputs.team_id)+ if not host_valid:+ raise ValueError(host_error or "Invalid Gitea host")++ # Only the webhook-capable schemas need the manager — skip its webhook_enabled()+ # DB lookup for the poll-only endpoints (commits, releases, ...).+ webhook_source_manager = (+ self.get_webhook_source_manager(inputs) if inputs.schema_name in GITEA_WEBHOOK_RESOURCE_MAP else None+ )++ return gitea_source(+ base_url=config.base_url,+ access_token=config.access_token,+ repository=config.repository,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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,+ webhook_source_manager=webhook_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.pynew file mode 100644index 000000000000..d601d87a2804--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea.py@@ -0,0 +1,467 @@+from collections.abc import Iterable+from datetime import UTC, datetime+from typing import Any, cast++import pytest+from unittest import mock++import pyarrow as pa++from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.gitea import (+ GiteaResumeConfig,+ _flatten_commit,+ _make_webhook_dedupe_transformer,+ _parse_next_url,+ create_repo_webhook,+ delete_repo_webhook,+ get_repo_webhook_info,+ get_rows,+ gitea_source,+ hostname_of,+ normalize_host,+ update_repo_webhook_events,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.settings import ENDPOINTS, GITEA_ENDPOINTS++_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gitea.gitea"++BASE_URL = "https://gitea.example.com"+REPO = "owner/repo"+++def _make_manager(resume_state: GiteaResumeConfig | None = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = resume_state is not None+ manager.load_state.return_value = resume_state+ return manager+++def _response(body: Any, status_code: int = 200, headers: dict[str, str] | None = None) -> mock.MagicMock:+ resp = mock.MagicMock()+ resp.json.return_value = body+ resp.status_code = status_code+ resp.ok = status_code < 400+ resp.headers = headers or {}+ return resp+++class TestNormalizeHost:+ @pytest.mark.parametrize(+ "value, expected",+ [+ ("https://gitea.example.com", "https://gitea.example.com"),+ ("gitea.example.com", "https://gitea.example.com"),+ ("https://gitea.example.com/", "https://gitea.example.com"),+ ],+ )+ def test_valid_hosts(self, value, expected):+ assert normalize_host(value) == expected++ @pytest.mark.parametrize(+ "value",+ [+ "",+ " ",+ "ftp://example.com",+ "https://",+ "http://gitea.example.com",+ # Parser-differential SSRF: urlparse sees example.com, requests connects to the IP.+ "https://169.254.169.254\\@example.com",+ "https://169.254.169.254%40example.com",+ "https://gitea.example.com%[email protected]",+ # Credentials in the authority would ship the token to `host`.+ "https://user:[email protected]",+ "https://[email protected]",+ ],+ )+ def test_invalid_hosts_raise(self, value):+ with pytest.raises(ValueError):+ normalize_host(value)++ def test_hostname_of(self):+ assert hostname_of("https://gitea.example.com/") == "gitea.example.com"+++class TestParseNextUrl:+ def test_parses_next_rel_among_others(self):+ header = (+ f'<{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=2>; rel="next",'+ f'<{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=9>; rel="last"'+ )+ assert _parse_next_url(header) == f"{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=2"++ @pytest.mark.parametrize("header", ["", f'<{BASE_URL}/x?page=1>; rel="last"'])+ def test_no_next_returns_none(self, header):+ assert _parse_next_url(header) is None+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code, expected_valid, expected_error_fragment",+ [+ (200, True, None),+ (401, False, "Invalid Gitea access token"),+ (404, False, "not found or not accessible"),+ (302, False, "redirected"),+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_status_mapping(self, mock_session, status_code, expected_valid, expected_error_fragment):+ mock_session.return_value.get.return_value = _response({"message": "boom"}, status_code=status_code)++ is_valid, error = validate_credentials(BASE_URL, "tok", REPO)++ assert is_valid is expected_valid+ if expected_error_fragment:+ assert expected_error_fragment in (error or "")+ url = mock_session.return_value.get.call_args.args[0]+ assert url == f"{BASE_URL}/api/v1/repos/{REPO}"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_session_carries_token_header_and_never_redirects(self, mock_session):+ mock_session.return_value.get.return_value = _response({})++ validate_credentials(BASE_URL, "tok", REPO)++ kwargs = mock_session.call_args.kwargs+ assert kwargs["headers"]["Authorization"] == "token tok"+ assert kwargs["allow_redirects"] is False+ assert kwargs["redact_values"] == ("tok",)+++class TestGetRows:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_paginates_via_link_header_and_saves_state_after_yield(self, mock_session):+ page_2_url = f"{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=2"+ mock_session.return_value.get.side_effect = [+ _response([{"id": 1}], headers={"Link": f'<{page_2_url}>; rel="next"'}),+ _response([{"id": 2}]),+ ]+ manager = _make_manager()++ rows_iter = get_rows(BASE_URL, "tok", REPO, "issues", mock.MagicMock(), manager)+ first_batch = next(rows_iter)++ # State is saved AFTER the batch is yielded, so a crash re-yields it (merge dedupes).+ assert first_batch == [{"id": 1}]+ assert manager.save_state.call_count == 0++ assert next(rows_iter) == [{"id": 2}]+ assert [call.args[0].next_url for call in manager.save_state.call_args_list] == [page_2_url]++ with pytest.raises(StopIteration):+ next(rows_iter)+ # The last page has no next link — no state saved for it.+ assert manager.save_state.call_count == 1++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_resumes_from_saved_url(self, mock_session):+ resume_url = f"{BASE_URL}/api/v1/repos/{REPO}/issues?limit=50&page=7"+ mock_session.return_value.get.return_value = _response([])++ list(+ get_rows(+ BASE_URL, "tok", REPO, "issues", mock.MagicMock(), _make_manager(GiteaResumeConfig(next_url=resume_url))+ )+ )++ assert mock_session.return_value.get.call_args.args[0] == resume_url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_incremental_issues_pass_since_and_static_params(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ list(+ get_rows(+ BASE_URL,+ "tok",+ REPO,+ "issues",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, 3, 4, 5, tzinfo=UTC),+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert "since=2024-01-02T03%3A04%3A05Z" in url+ # type=issues keeps pull requests out of the issues table.+ assert "type=issues" in url+ assert "state=all" in url++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_full_refresh_omits_since(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ list(get_rows(BASE_URL, "tok", REPO, "issues", mock.MagicMock(), _make_manager()))++ assert "since=" not in mock_session.return_value.get.call_args.args[0]++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_pull_requests_never_send_since(self, mock_session):+ # /pulls accepts `since` but silently ignores it — sending it would fake an+ # incremental sync that actually re-reads everything.+ mock_session.return_value.get.return_value = _response([])++ list(+ get_rows(+ BASE_URL,+ "tok",+ REPO,+ "pull_requests",+ mock.MagicMock(),+ _make_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 2, tzinfo=UTC),+ )+ )++ url = mock_session.return_value.get.call_args.args[0]+ assert "since=" not in url+ assert "sort=oldest" in url++ @pytest.mark.parametrize(+ "evil_next_url",+ [+ # Plaintext downgrade would send the token header in the clear.+ "http://gitea.example.com/api/v1/repos/owner/repo/issues?page=2",+ # Off-origin host would hand the token to another server (SSRF/exfiltration).+ "https://169.254.169.254/api/v1/repos/owner/repo/issues?page=2",+ "https://gitea.example.com:8443/api/v1/repos/owner/repo/issues?page=2",+ ],+ )+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_off_origin_link_header_url_is_rejected(self, mock_session, evil_next_url):+ mock_session.return_value.get.return_value = _response(+ [{"id": 1}], headers={"Link": f'<{evil_next_url}>; rel="next"'}+ )++ with pytest.raises(ValueError, match="not on the configured instance"):+ list(get_rows(BASE_URL, "tok", REPO, "issues", mock.MagicMock(), _make_manager()))++ # The poisoned URL is never fetched.+ assert mock_session.return_value.get.call_count == 1++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_off_origin_resume_url_is_rejected(self, mock_session):+ manager = _make_manager(GiteaResumeConfig(next_url="https://evil.example.com/api/v1/x"))++ with pytest.raises(ValueError, match="not on the configured instance"):+ list(get_rows(BASE_URL, "tok", REPO, "issues", mock.MagicMock(), manager))++ mock_session.return_value.get.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_commits_are_flattened(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ [+ {+ "sha": "abc",+ "created": "2024-01-01T00:00:00Z",+ "commit": {+ "message": "fix: thing",+ "author": {"name": "Alice", "email": "[email protected]", "date": "2024-01-01T00:00:00Z"},+ "committer": {"name": "Bob", "email": "[email protected]", "date": "2024-01-01T00:00:00Z"},+ },+ "author": {"id": 7, "login": "alice"},+ "committer": None,+ }+ ]+ )++ batches = list(get_rows(BASE_URL, "tok", REPO, "commits", mock.MagicMock(), _make_manager()))++ row = batches[0][0]+ assert row["message"] == "fix: thing"+ assert row["author_name"] == "Alice"+ assert row["author_email"] == "[email protected]"+ assert row["committer_name"] == "Bob"+ assert row["author_id"] == 7+ assert row["author_login"] == "alice"+ # The commit timestamp survives as the cursor/partition column.+ assert row["created"] == "2024-01-01T00:00:00Z"+++class TestFlattenCommit:+ def test_missing_nested_objects_do_not_crash(self):+ assert _flatten_commit({"sha": "abc"}) == {"sha": "abc"}+++class TestGiteaSourceResponse:+ @pytest.mark.parametrize("endpoint", list(ENDPOINTS))+ def test_response_metadata_per_endpoint(self, endpoint):+ response = gitea_source(BASE_URL, "tok", REPO, endpoint, mock.MagicMock(), _make_manager())++ config = GITEA_ENDPOINTS[endpoint]+ assert response.name == endpoint+ assert response.primary_keys == [config.primary_key]+ assert response.sort_mode == config.sort_mode+ if config.partition_key:+ assert response.partition_keys == [config.partition_key]+ assert response.partition_mode == "datetime"+ else:+ assert response.partition_keys is None++ def test_commits_key_on_sha(self):+ response = gitea_source(BASE_URL, "tok", REPO, "commits", mock.MagicMock(), _make_manager())+ assert response.primary_keys == ["sha"]++ def test_webhook_enabled_drains_webhook_items_with_dedupe(self):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=True)+ sentinel = mock.MagicMock()+ webhook_manager.get_items.return_value = sentinel++ response = gitea_source(+ BASE_URL, "tok", REPO, "issues", mock.MagicMock(), _make_manager(), webhook_source_manager=webhook_manager+ )++ assert response.items() is sentinel+ # Issues declare version_keys, so the drain must collapse a batch to one row per id.+ assert webhook_manager.get_items.call_args.kwargs["table_transformer"] is not None++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_webhook_disabled_falls_back_to_poll(self, mock_session):+ webhook_manager = mock.MagicMock()+ webhook_manager.webhook_enabled = mock.AsyncMock(return_value=False)+ mock_session.return_value.get.return_value = _response([])++ response = gitea_source(+ BASE_URL, "tok", REPO, "issues", mock.MagicMock(), _make_manager(), webhook_source_manager=webhook_manager+ )++ assert list(cast(Iterable[Any], response.items())) == []+ webhook_manager.get_items.assert_not_called()+++class TestWebhookDedupeTransformer:+ def _table(self, rows: list[dict[str, Any]]) -> pa.Table:+ return pa.Table.from_pylist(rows)++ def test_keeps_newest_state_per_id(self):+ transform = _make_webhook_dedupe_transformer("id", ["updated_at"])+ table = self._table(+ [+ {"id": 1, "state": "open", "updated_at": "2024-01-01T00:00:00Z"},+ {"id": 2, "state": "open", "updated_at": "2024-01-01T00:00:00Z"},+ {"id": 1, "state": "closed", "updated_at": "2024-01-02T00:00:00Z"},+ ]+ )++ result = transform(table).to_pylist()++ assert result == [+ {"id": 2, "state": "open", "updated_at": "2024-01-01T00:00:00Z"},+ {"id": 1, "state": "closed", "updated_at": "2024-01-02T00:00:00Z"},+ ]++ def test_tie_keeps_later_arriving_row(self):+ transform = _make_webhook_dedupe_transformer("id", ["updated_at"])+ table = self._table(+ [+ {"id": 1, "state": "open", "updated_at": "2024-01-01T00:00:00Z"},+ {"id": 1, "state": "closed", "updated_at": "2024-01-01T00:00:00Z"},+ ]+ )++ assert transform(table).to_pylist() == [{"id": 1, "state": "closed", "updated_at": "2024-01-01T00:00:00Z"}]++ def test_missing_version_column_leaves_table_unchanged(self):+ transform = _make_webhook_dedupe_transformer("id", ["updated_at"])+ table = self._table([{"id": 1}, {"id": 1}])++ assert transform(table).num_rows == 2+++class TestWebhookManagement:+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_create_posts_gitea_hook_and_returns_secret(self, mock_session):+ mock_session.return_value.post.return_value = _response({"id": 5}, status_code=201)++ result = create_repo_webhook(BASE_URL, "tok", REPO, "https://ph.example/webhook", ["issues"], "s3cret")++ assert result.success is True+ # Gitea never echoes the secret back — it must flow to the hog function via extra_inputs.+ assert result.extra_inputs == {"signing_secret": "s3cret"}+ call = mock_session.return_value.post.call_args+ assert call.args[0] == f"{BASE_URL}/api/v1/repos/{REPO}/hooks"+ payload = call.kwargs["json"]+ assert payload["type"] == "gitea"+ assert payload["events"] == ["issues"]+ assert payload["config"] == {"url": "https://ph.example/webhook", "content_type": "json", "secret": "s3cret"}++ @pytest.mark.parametrize("status_code", [403, 404])+ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_create_permission_error_returns_failed_result(self, mock_session, status_code):+ mock_session.return_value.post.return_value = _response({}, status_code=status_code)++ result = create_repo_webhook(BASE_URL, "tok", REPO, "https://ph.example/webhook", ["issues"], "s3cret")++ assert result.success is False+ assert "manually" in (result.error or "")++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_delete_matches_hook_by_url(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ [+ {"id": 1, "config": {"url": "https://other.example/hook"}},+ {"id": 2, "config": {"url": "https://ph.example/webhook"}},+ ]+ )+ mock_session.return_value.delete.return_value = _response(None, status_code=204)++ result = delete_repo_webhook(BASE_URL, "tok", REPO, "https://ph.example/webhook")++ assert result.success is True+ assert mock_session.return_value.delete.call_args.args[0] == f"{BASE_URL}/api/v1/repos/{REPO}/hooks/2"++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_delete_with_no_matching_hook_is_success(self, mock_session):+ mock_session.return_value.get.return_value = _response([])++ result = delete_repo_webhook(BASE_URL, "tok", REPO, "https://ph.example/webhook")++ assert result.success is True+ mock_session.return_value.delete.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_update_events_merges_additively(self, mock_session):+ # A user-subscribed event (push) must survive the reconcile PATCH.+ mock_session.return_value.get.return_value = _response(+ [{"id": 2, "config": {"url": "https://ph.example/webhook"}, "events": ["push", "issues"]}]+ )+ mock_session.return_value.patch.return_value = _response({}, status_code=200)++ result = update_repo_webhook_events(BASE_URL, "tok", REPO, "https://ph.example/webhook", ["pull_request"])++ assert result.success is True+ assert mock_session.return_value.patch.call_args.kwargs["json"] == {+ "events": ["issues", "pull_request", "push"]+ }++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_update_events_skips_write_when_already_covered(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ [{"id": 2, "config": {"url": "https://ph.example/webhook"}, "events": ["issues", "pull_request"]}]+ )++ result = update_repo_webhook_events(BASE_URL, "tok", REPO, "https://ph.example/webhook", ["issues"])++ assert result.success is True+ mock_session.return_value.patch.assert_not_called()++ @mock.patch(f"{_MODULE}.make_tracked_session")+ def test_webhook_info_found_and_missing(self, mock_session):+ mock_session.return_value.get.return_value = _response(+ [{"id": 2, "config": {"url": "https://ph.example/webhook"}, "events": ["issues"], "active": True}]+ )++ info = get_repo_webhook_info(BASE_URL, "tok", REPO, "https://ph.example/webhook")+ assert info.exists is True+ assert info.status == "active"+ assert info.enabled_events == ["issues"]++ missing = get_repo_webhook_info(BASE_URL, "tok", REPO, "https://nope.example/webhook")+ assert missing.exists is Falsediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.pynew file mode 100644index 000000000000..cfc503436fdc--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_source.py@@ -0,0 +1,208 @@+import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import GiteaSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.gitea import GiteaResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.source import (+ GITEA_WEBHOOK_RESOURCE_MAP,+ GiteaSource,+)+from products.warehouse_sources.backend.types import ExternalDataSourceType++_SOURCE_MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.gitea.source"+++class TestGiteaSource:+ def setup_method(self):+ self.source = GiteaSource()+ self.team_id = 123+ self.config = GiteaSourceConfig(+ base_url="https://gitea.example.com", access_token="tok", repository="owner/repo"+ )++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.GITEA++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "Gitea"+ assert config.label == "Gitea"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # The scaffold shipped hidden; a finished source must be visible.+ assert config.unreleasedSource is None+ assert [f.name for f in config.fields] == ["base_url", "access_token", "repository"]++ def test_access_token_field_is_secret_password(self):+ config = self.source.get_source_config+ token_field = next(+ f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "access_token"+ )+ assert token_field.type == SourceFieldInputConfigType.PASSWORD+ assert token_field.secret is True+ assert token_field.required is True++ def test_connection_host_fields_cover_base_url_and_repository(self):+ # `base_url` is where the token is sent; `repository` is which repo it reads. Changing+ # either must force token re-entry so a stored token can't be reused against a new target.+ assert self.source.connection_host_fields == ["base_url", "repository"]++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://gitea.example.com/api/v1/repos/owner/repo/issues",+ "403 Client Error: Forbidden for url: https://gitea.example.com/api/v1/repos/owner/repo/issues",+ "404 Client Error: Not Found for url: https://gitea.example.com/api/v1/repos/owner/repo",+ ],+ )+ def test_non_retryable_errors_match_known_failures(self, observed_error):+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())++ @pytest.mark.parametrize(+ "other_error",+ [+ "500 Server Error for url: https://gitea.example.com/api/v1/repos/owner/repo/issues",+ "429 Client Error: Too Many Requests for url: https://gitea.example.com/api/v1/repos/owner/repo",+ ],+ )+ def test_non_retryable_errors_do_not_match_transient_failures(self, other_error):+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())++ def test_get_schemas(self):+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {schema.name for schema in schemas} == set(ENDPOINTS)+ by_name = {schema.name: schema for schema in schemas}+ # Only the endpoints with a real server-side `since` filter are incremental.+ assert {name for name, schema in by_name.items() if schema.supports_incremental} == {"issues", "commits"}+ assert {name for name, schema in by_name.items() if schema.supports_webhooks} == {"issues", "pull_requests"}+ assert by_name["issues"].incremental_fields == INCREMENTAL_FIELDS["issues"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["issues"])+ assert [schema.name for schema in schemas] == ["issues"]++ def test_webhook_resource_map(self):+ assert GITEA_WEBHOOK_RESOURCE_MAP == {"issues": "issues", "pull_requests": "pull_request"}+ assert self.source.webhook_resource_map == GITEA_WEBHOOK_RESOURCE_MAP++ def test_webhook_template_present(self):+ template = self.source.webhook_template+ assert template is not None+ assert template.id == "template-warehouse-source-gitea"+ assert template.type == "warehouse_source_webhook"++ def test_get_desired_webhook_events_maps_schema_names(self):+ events = self.source.get_desired_webhook_events(self.config, ["issues", "pull_requests", "commits"])+ assert events == ["issues", "pull_request"]++ @mock.patch(f"{_SOURCE_MODULE}.create_repo_webhook")+ def test_create_webhook_mints_secret_and_subscribes_all_events(self, mock_create):+ self.source.create_webhook(self.config, "https://ph.example/webhook", self.team_id)++ args = mock_create.call_args.args+ assert args[:4] == ("https://gitea.example.com", "tok", "owner/repo", "https://ph.example/webhook")+ assert args[4] == ["issues", "pull_request"]+ # A fresh random secret is minted per webhook.+ assert len(args[5]) == 64++ @mock.patch(f"{_SOURCE_MODULE}.validate_gitea_credentials")+ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_validate_credentials_happy_path(self, mock_host_valid, mock_validate):+ mock_host_valid.return_value = (True, None)+ mock_validate.return_value = (True, None)++ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert (is_valid, error) == (True, None)+ mock_host_valid.assert_called_once_with("gitea.example.com", self.team_id)+ mock_validate.assert_called_once_with("https://gitea.example.com", "tok", "owner/repo")++ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_validate_credentials_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")++ is_valid, error = self.source.validate_credentials(self.config, self.team_id)++ assert (is_valid, error) == (False, "Host is not allowed")++ def test_validate_credentials_rejects_invalid_url(self):+ config = GiteaSourceConfig(base_url="ftp://nope", access_token="tok", repository="owner/repo")++ is_valid, error = self.source.validate_credentials(config, self.team_id)++ assert (is_valid, error) == (False, "Invalid Gitea instance URL")++ def test_get_resumable_source_manager_binds_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())++ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is GiteaResumeConfig++ @mock.patch(f"{_SOURCE_MODULE}.gitea_source")+ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_source_for_pipeline_plumbs_arguments(self, mock_host_valid, mock_gitea_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "issues"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = True+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_gitea_source.call_args.kwargs+ assert kwargs["base_url"] == "https://gitea.example.com"+ assert kwargs["access_token"] == "tok"+ assert kwargs["repository"] == "owner/repo"+ assert kwargs["endpoint"] == "issues"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2024-01-02T03:04:05Z"+ # Issues are webhook-capable, so the drain manager is wired in.+ assert kwargs["webhook_source_manager"] is not None++ @mock.patch(f"{_SOURCE_MODULE}.gitea_source")+ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_source_for_pipeline_skips_webhook_manager_for_poll_only_schemas(self, mock_host_valid, mock_gitea_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "commits"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = False++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_gitea_source.call_args.kwargs["webhook_source_manager"] is None++ @mock.patch(f"{_SOURCE_MODULE}.gitea_source")+ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_source_for_pipeline_omits_last_value_on_full_refresh(self, mock_host_valid, mock_gitea_source):+ mock_host_valid.return_value = (True, None)+ inputs = mock.MagicMock()+ inputs.schema_name = "pull_requests"+ inputs.team_id = self.team_id+ inputs.should_use_incremental_field = False+ inputs.db_incremental_field_last_value = "2024-01-02T03:04:05Z"++ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)++ assert mock_gitea_source.call_args.kwargs["db_incremental_field_last_value"] is None++ @mock.patch.object(GiteaSource, "is_database_host_valid")+ def test_source_for_pipeline_rejects_unsafe_host(self, mock_host_valid):+ mock_host_valid.return_value = (False, "Host is not allowed")+ inputs = mock.MagicMock()+ inputs.schema_name = "issues"+ inputs.team_id = self.team_id++ with pytest.raises(ValueError, match="Host is not allowed"):+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_webhook_template.pynew file mode 100644index 000000000000..f80e2314e30b--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/tests/test_gitea_webhook_template.py@@ -0,0 +1,108 @@+import hmac+import json+import hashlib+from typing import Any++from posthog.cdp.templates.helpers import BaseHogFunctionTemplateTest++from products.warehouse_sources.backend.temporal.data_imports.sources.gitea.webhook_template import template+++class TestGiteaWarehouseWebhookTemplate(BaseHogFunctionTemplateTest):+ template = template++ def createHogGlobals(self, globals=None) -> dict:+ data: dict = {+ "request": {+ "method": "POST",+ "headers": {},+ "body": {},+ "query": {},+ "stringBody": "",+ "ip": "127.0.0.1",+ },+ }+ if globals and globals.get("request"):+ data["request"].update(globals["request"])+ return data++ def _run(+ self,+ event_type: str,+ body: dict[str, Any],+ schema_mapping: dict[str, str],+ inputs: dict[str, Any] | None = None,+ extra_headers: dict[str, str] | None = None,+ ) -> Any:+ return self.run_function(+ {"signing_secret": "", "bypass_signature_check": True, "schema_mapping": schema_mapping, **(inputs or {})},+ globals={+ "request": {+ "method": "POST",+ "headers": {"x-gitea-event": event_type, **(extra_headers or {})},+ "body": body,+ "stringBody": json.dumps(body),+ "query": {},+ }+ },+ )++ def test_issues_event_lands_nested_issue_object(self):+ # The 'issues' event nests its object under the singular 'issue' key — the template+ # must remap it or every issue webhook 200-skips and the table silently goes stale.+ issue = {"id": 42, "number": 7, "state": "open", "updated_at": "2026-01-20T10:00:00Z"}+ self._run("issues", {"action": "opened", "number": 7, "issue": issue}, {"issues": "schema_issues"})++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(issue, "schema_issues")++ def test_pull_request_event_lands_nested_object(self):+ pull_request = {"id": 9, "number": 3, "state": "open", "merged": False}+ self._run(+ "pull_request",+ {"action": "opened", "number": 3, "pull_request": pull_request},+ {"pull_request": "schema_prs"},+ )++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(pull_request, "schema_prs")++ def test_unmapped_event_type_no_ops(self):+ # Gitea repos commonly have push/release events enabled too; those must 200-skip.+ res = self._run("push", {"ref": "refs/heads/main"}, {"issues": "schema_issues"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_missing_object_in_payload_is_skipped_with_200(self):+ res = self._run("issues", {"action": "opened"}, {"issues": "schema_issues"})++ assert res.result["httpResponse"]["status"] == 200+ self.mock_produce_to_warehouse_webhooks.assert_not_called()++ def test_valid_bare_hex_signature_is_accepted(self):+ # Gitea sends the bare hex HMAC (no sha256= prefix, unlike GitHub) — a prefix+ # comparison regression would reject every genuine delivery.+ issue = {"id": 42}+ body = {"action": "opened", "issue": issue}+ signature = hmac.new(b"s3cret", json.dumps(body).encode(), hashlib.sha256).hexdigest()++ self._run(+ "issues",+ body,+ {"issues": "schema_issues"},+ inputs={"signing_secret": "s3cret", "bypass_signature_check": False},+ extra_headers={"x-gitea-signature": signature},+ )++ self.mock_produce_to_warehouse_webhooks.assert_called_once_with(issue, "schema_issues")++ def test_bad_signature_is_rejected(self):+ res = self._run(+ "issues",+ {"action": "opened", "issue": {"id": 42}},+ {"issues": "schema_issues"},+ inputs={"signing_secret": "s3cret", "bypass_signature_check": False},+ extra_headers={"x-gitea-signature": "deadbeef"},+ )++ assert res.result["httpResponse"]["status"] == 400+ self.mock_produce_to_warehouse_webhooks.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/webhook_template.py b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/webhook_template.pynew file mode 100644index 000000000000..3211a7c2ff3d--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/gitea/webhook_template.py@@ -0,0 +1,140 @@+from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC++template: HogFunctionTemplateDC = HogFunctionTemplateDC(+ status="alpha",+ free=False,+ type="warehouse_source_webhook",+ id="template-warehouse-source-gitea",+ name="Gitea warehouse source webhook",+ description="Receive Gitea webhook events for data warehouse ingestion",+ icon_url="/static/services/gitea.png",+ category=["Data warehouse"],+ code_language="hog",+ code="""\+if (request.method != 'POST') {+ return {+ 'httpResponse': {+ 'status': 405,+ 'body': 'Method not allowed'+ }+ }+}++if (not inputs.bypass_signature_check) {+ if (empty(inputs.signing_secret)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Signing secret not configured',+ }+ }+ }++ let signatureHeader := request.headers['x-gitea-signature']++ if (empty(signatureHeader)) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Missing signature',+ }+ }+ }++ // Gitea sends the bare hex HMAC-SHA256 of the raw request body keyed by the+ // webhook secret (no sha256= prefix, unlike GitHub).+ let computedSignature := sha256HmacChainHex([inputs.signing_secret, request.stringBody])++ if (computedSignature != signatureHeader) {+ return {+ 'httpResponse': {+ 'status': 400,+ 'body': 'Bad signature',+ }+ }+ }+}++// Event type comes from the X-Gitea-Event header, not the body.+let eventType := request.headers['x-gitea-event']++if (empty(eventType)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': 'No event type found, skipping'+ }+ }+}++let schemaId := inputs.schema_mapping?.[eventType]++if (empty(schemaId)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No schema mapping for event type: {eventType}, skipping'+ }+ }+}++// The poll endpoints land the issue/pull_request objects themselves, so the webhook+// lands the same nested object. Gitea serializes one struct per resource, so the+// nested webhook object matches the REST list response shape. The 'issues' event+// nests its object under the singular 'issue' key; other events use the event name.+let bodyKey := eventType+if (eventType = 'issues') {+ bodyKey := 'issue'+}++let row := request.body?.[bodyKey]++if (empty(row)) {+ return {+ 'httpResponse': {+ 'status': 200,+ 'body': f'No {bodyKey} object in payload, skipping'+ }+ }+}++produceToWarehouseWebhooks(row, schemaId)""",+ inputs_schema=[+ {+ "type": "string",+ "key": "signing_secret",+ "label": "Signing secret",+ "required": False,+ "secret": True,+ "hidden": False,+ "description": "Used to validate the webhook came from your Gitea instance. Set as the webhook's Secret in the repo's Settings > Webhooks.",+ },+ {+ "type": "boolean",+ "key": "bypass_signature_check",+ "label": "Bypass signature check",+ "description": "If set, the X-Gitea-Signature header will not be checked. This is not recommended.",+ "default": False,+ "required": False,+ "secret": False,+ },+ {+ "type": "json",+ "key": "schema_mapping",+ "label": "Schema mapping",+ "description": "Maps Gitea event types (issues, pull_request) to ExternalDataSchema IDs",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ {+ "type": "string",+ "key": "source_id",+ "label": "Source ID",+ "description": "The ExternalDataSource ID this webhook is associated with",+ "required": True,+ "secret": False,+ "hidden": True,+ },+ ],+)