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 jenkins import source (#71184)

Tom Owers6533fe592b93
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index c14a0499c31b..14b5ce087abe 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -286,6 +286,7 @@ the row lists both.
| iterable | HTTP | requests | ✅ |
| jamf_pro | HTTP | requests | ✅ |
| jellyfish | HTTP | requests | ✅ |
+| jenkins | HTTP | requests | ✅ |
| jfrog_artifactory | HTTP | requests | ✅ |
| jira | HTTP | requests | ✅ |
| jobnimbus | HTTP | requests | ✅ |
@@ -759,7 +760,6 @@ doesn't conflict with concurrent PRs.
- instagram
- instantly
- interzoid
-- jenkins
- jobber
- judgeme_reviews
- justsift
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.py
index 11e66715e0e2..cf94b1766add 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
@@ -2252,7 +2252,9 @@ class JellyfishSourceConfig(config.Config):
@config.config
class JenkinsSourceConfig(config.Config):
- pass
+ host: str
+ username: str
+ api_token: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/canonical_descriptions.py
new file mode 100644
index 000000000000..fb9324f37a91
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/canonical_descriptions.py
@@ -0,0 +1,40 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Curated from the Jenkins remote access API (https://www.jenkins.io/doc/book/using/remote-access-api/).
+# Keyed by the endpoint/schema name from settings.ENDPOINTS.
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "jobs": {
+ "description": "A job (project) in Jenkins, discovered by recursing into Folders and Multibranch Pipelines.",
+ "docs_url": "https://www.jenkins.io/doc/book/using/remote-access-api/",
+ "columns": {
+ "id": "Stable identifier for the job — its API URL.",
+ "name": "Short name of the job within its parent folder.",
+ "fullName": "Fully qualified name including any parent folders (e.g. team/service/build).",
+ "url": "Absolute URL of the job on the Jenkins instance.",
+ "color": "Health/status indicator for the job's last build (e.g. blue, red, yellow; the _anime suffix means a build is running).",
+ "_class": "Jenkins class of the job, distinguishing freestyle, pipeline, folder, and multibranch types.",
+ "buildable": "Whether the job can currently be built (false for folders and disabled jobs).",
+ },
+ },
+ "builds": {
+ "description": "A single run of a job, carrying its result, duration, and start time.",
+ "docs_url": "https://www.jenkins.io/doc/book/using/remote-access-api/",
+ "columns": {
+ "job_url": "Absolute URL of the job this build belongs to.",
+ "created_at": "Build start time as an ISO 8601 datetime, derived from the epoch-millisecond timestamp.",
+ "url": "Absolute URL of the build — globally unique and used as the primary key.",
+ "number": "Sequential build number within its job (strictly monotonic per job).",
+ "id": "Build id string (equal to the build number on modern Jenkins).",
+ "result": "Outcome of the build (SUCCESS, FAILURE, UNSTABLE, ABORTED, or null while running).",
+ "duration": "How long the build took, in milliseconds (0 while still running).",
+ "estimatedDuration": "Jenkins' estimate of the build duration, in milliseconds.",
+ "timestamp": "Build start time in epoch milliseconds.",
+ "fullDisplayName": "Human-readable name including the job name and build number.",
+ "displayName": "Display name of the build (usually #<number>).",
+ "building": "Whether the build was still running when synced.",
+ "queueId": "Identifier of the queue item this build came from.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
new file mode 100644
index 000000000000..ef822dd2ca87
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/jenkins.py
@@ -0,0 +1,519 @@
+import threading
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional, cast
+from urllib.parse import urlparse
+
+import urllib3
+import requests
+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.batcher import Batcher
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+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.jenkins.settings import JENKINS_ENDPOINTS
+
+REQUEST_TIMEOUT_SECONDS = 60
+MAX_RETRY_ATTEMPTS = 5
+# Builds are windowed by index range (`tree=builds[...]{start,end}`). Jenkins has no cursor, so we
+# advance the range ourselves; 100 keeps each request small while limiting round trips.
+BUILDS_PAGE_SIZE = 100
+# Guard against pathological Folder / Multibranch nesting when discovering jobs recursively.
+MAX_JOB_DEPTH = 10
+# MAX_JOB_DEPTH caps nesting; this caps breadth. The customer configures the host, so a hostile or
+# misconfigured server could return unbounded folder fan-out at every level and hold a worker issuing
+# an effectively unlimited number of authenticated requests. Stop discovery once this many jobs have
+# been emitted (far above any real Jenkins instance).
+MAX_TOTAL_JOBS = 100_000
+# Cap the decoded response body we buffer per request. The customer configures the host, so a hostile
+# or misconfigured server could otherwise return an arbitrarily large (or highly compressed) body and
+# exhaust the import worker. The `tree=` selectors keep real responses tiny; this only trips on abuse.
+MAX_RESPONSE_BYTES = 50 * 1024 * 1024
+RESPONSE_CHUNK_BYTES = 1024 * 1024
+# Hard wall-clock deadline for reading a single response body. REQUEST_TIMEOUT_SECONDS is a per-read
+# socket timeout that resets whenever a byte arrives, so a server dripping data slowly could otherwise
+# hold the read loop open indefinitely; this bounds the total download regardless of drip rate.
+MAX_DOWNLOAD_SECONDS = 300
+# Bound windowed build pagination per job. A server returning a full page for every window would
+# otherwise loop forever; 1000 pages (~100k builds at BUILDS_PAGE_SIZE) is far above any real job.
+MAX_BUILD_PAGES_PER_JOB = 1000
+
+# Field selectors passed to Jenkins' `tree` param. Keeping them explicit (rather than `depth=`) means
+# we only pull the columns we store and never accidentally fetch large nested build/console payloads.
+JOB_TREE_FIELDS = "name,fullName,url,color,_class,buildable"
+BUILD_TREE_FIELDS = (
+ "number,url,result,duration,estimatedDuration,timestamp,id,fullDisplayName,displayName,building,queueId"
+)
+
+
+class JenkinsRetryableError(Exception):
+ pass
+
+
+class JenkinsResumeConfig:
+ # The next job (by stable URL) to fetch builds for. A URL bookmark rather than a positional index
+ # so jobs added/removed between a crash and the retry can't resume us into the wrong job. None for
+ # the jobs catalog, which is a single full-refresh pass with no cursor.
+ next_job_url: str | None = None
+
+
+def normalize_base_url(host: str | None) -> str:
+ """Normalize the self-hosted Jenkins URL and reject anything that isn't plain http(s).
+
+ Jenkins has no vendor-hosted API, so the customer always supplies their instance URL. Rejects
+ URLs where the host `urlparse` reports could diverge from the host the HTTP client actually dials
+ (backslash tricks, userinfo before `@`, query/fragment), which would let a caller slip past the
+ downstream SSRF allowlist that validates the parsed hostname.
+ """
+ raw = (host or "").strip()
+ if not raw:
+ raise ValueError("Jenkins URL is required")
+ if "://" not in raw:
+ raw = f"https://{raw}"
+ if "\\" in raw or "%5c" in raw.lower():
+ raise ValueError(f"Invalid Jenkins URL: {host}")
+ raw = raw.rstrip("/")
+ parsed = urlparse(raw)
+ if parsed.scheme not in ("http", "https") or not parsed.hostname:
+ raise ValueError(f"Invalid Jenkins URL: {host}")
+ if parsed.username is not None or parsed.password is not None or "@" in parsed.netloc:
+ raise ValueError(f"Invalid Jenkins URL: {host}")
+ if parsed.query or parsed.fragment or parsed.params:
+ raise ValueError(f"Invalid Jenkins URL: {host}")
+ return raw
+
+
+def hostname_of(host: str | None) -> str:
+ return urlparse(normalize_base_url(host)).hostname or ""
+
+
+def scheme_of(host: str | None) -> str:
+ return urlparse(normalize_base_url(host)).scheme
+
+
+def _api_json_url(object_url: str, tree: str) -> str:
+ """Build an `/api/json` URL for any Jenkins object, selecting `tree` fields.
+
+ `object_url` is an absolute Jenkins URL (the instance root or a job's own `url`, which the API
+ always returns with a trailing slash). Brackets/braces in `tree` are sent literally — Jenkins
+ requires them unencoded, and every value here is constructed internally, never user input.
+ """
+ base = object_url if object_url.endswith("/") else f"{object_url}/"
+ return f"{base}api/json?tree={tree}"
+
+
+def _headers() -> dict[str, str]:
+ return {"Accept": "application/json"}
+
+
+def _request_timeout() -> urllib3.Timeout:
+ """Timeout that also bounds the connection + response-header phase, not just idle-socket reads.
+
+ A plain read timeout resets whenever a byte arrives, so a host dripping response-header bytes just
+ under it could block `session.get` (which returns only after the status line and headers are read)
+ before the body watchdog is ever armed. urllib3's `total` caps the whole connect + header phase, so
+ a header drip can't outrun it; the streamed body read stays additionally guarded by the watchdog.
+ """
+ return urllib3.Timeout(connect=REQUEST_TIMEOUT_SECONDS, read=REQUEST_TIMEOUT_SECONDS, total=MAX_DOWNLOAD_SECONDS)
+
+
+def _is_job_container(job: dict[str, Any]) -> bool:
+ """Whether a job actually holds nested jobs (Folder, Organization Folder, Multibranch Pipeline).
+
+ Jenkins ships several nesting plugins with different `_class` values, so match on the stable
+ suffixes rather than exact class names.
+ """
+ cls = job.get("_class") or ""
+ return cls.endswith("Folder") or "MultiBranch" in cls or "OrganizationFolder" in cls
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ JenkinsRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch(
+ session: requests.Session,
+ url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+) -> requests.Response:
+ # Stream so the status/headers arrive before the body, letting us cap the decoded size (see
+ # _read_body_capped) rather than letting `requests` buffer an unbounded response up front.
+ # `requests` accepts a urllib3.Timeout at runtime but its stubs only type the numeric forms.
+ response = session.get(url, auth=auth, headers=_headers(), timeout=cast(Any, _request_timeout()), stream=True)
+
+ # No documented rate limits (bounded by the customer's own server), but honor 429 if a reverse
+ # proxy imposes one, and retry transient 5xx.
+ if response.status_code == 429 or response.status_code >= 500:
+ response.close()
+ raise JenkinsRetryableError(f"Jenkins API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ response.close()
+ logger.error(f"Jenkins API error: status={response.status_code}, url={url}")
+ response.raise_for_status()
+
+ _read_body_capped(response, url)
+ return response
+
+
+def _read_body_capped(response: requests.Response, url: str) -> None:
+ """Buffer the streamed body under a size + wall-clock cap, then cache it so `.json()` still works.
+
+ `requests`' timeout only bounds an idle socket, and `raw.read(n)` blocks until it has `n` bytes,
+ so a hostile host can trickle one byte before each read timeout to keep a read blocked forever
+ while staying under the byte cap — a between-chunks deadline check would never run. A watchdog
+ closes the response at the wall-clock deadline, which unblocks the read; we surface that as a
+ non-retryable error. Both caps are non-retryable — the condition won't clear on retry.
+ """
+ timed_out = threading.Event()
+
+ def _abort_on_deadline() -> None:
+ timed_out.set()
+ response.close()
+
+ watchdog = threading.Timer(MAX_DOWNLOAD_SECONDS, _abort_on_deadline)
+ watchdog.start()
+ try:
+ buffer = bytearray()
+ while True:
+ try:
+ chunk = response.raw.read(RESPONSE_CHUNK_BYTES, decode_content=True)
+ except Exception:
+ # The watchdog closing the socket surfaces here as a read error; report the deadline.
+ if timed_out.is_set():
+ raise ValueError(
+ f"Jenkins response exceeded the {MAX_DOWNLOAD_SECONDS}s download deadline: url={url}"
+ )
+ raise
+ if not chunk:
+ break
+ buffer += chunk
+ if len(buffer) > MAX_RESPONSE_BYTES:
+ raise ValueError(f"Jenkins response exceeded the {MAX_RESPONSE_BYTES}-byte limit: url={url}")
+ # The read can also finish (e.g. at EOF) right as the deadline fires; treat that as a timeout.
+ if timed_out.is_set():
+ raise ValueError(f"Jenkins response exceeded the {MAX_DOWNLOAD_SECONDS}s download deadline: url={url}")
+ # Cache the decoded body so downstream `.json()` reads from memory rather than the consumed stream.
+ response._content = bytes(buffer)
+ except Exception:
+ response.close()
+ raise
+ finally:
+ watchdog.cancel()
+
+
+def validate_credentials(
+ host: str | None, username: str, api_token: str, schema_name: str | None = None
+) -> tuple[bool, str | None]:
+ """Probe the instance root `/api/json` to confirm the username + API token are genuine.
+
+ A read-only GET needs no CSRF crumb. Both streams need the same Overall/Read permission, so the
+ root probe covers per-schema checks too.
+ """
+ try:
+ url = _api_json_url(normalize_base_url(host), "nodeName")
+ except ValueError as e:
+ return False, str(e)
+
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+ try:
+ # Stream and only read the status line: the probe never needs the body, so a hostile host
+ # can't make us buffer a large response just to validate credentials. The total-bounded
+ # timeout also stops a dripped-header response from stalling the probe indefinitely.
+ response = session.get(
+ url, auth=(username, api_token), headers=_headers(), timeout=cast(Any, _request_timeout()), stream=True
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ status_code = response.status_code
+ response.close()
+
+ if status_code == 200:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Jenkins username or API token"
+ if status_code == 403:
+ return False, "The Jenkins user lacks Overall/Read permission"
+ return False, f"Jenkins returned status {status_code}"
+
+
+def _to_epoch_ms(value: Any) -> int | None:
+ """Convert a datetime/date/ISO-string incremental cursor to epoch milliseconds.
+
+ Jenkins build timestamps are epoch ms, so the watermark is compared in the same unit. Returns
+ None when the value can't be interpreted (treated as "no watermark", i.e. full history)."""
+ if value is None:
+ return None
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return int(aware.timestamp() * 1000)
+ if isinstance(value, date):
+ return int(datetime.combine(value, datetime.min.time(), tzinfo=UTC).timestamp() * 1000)
+ if isinstance(value, (int, float)):
+ return int(value)
+ if isinstance(value, str):
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ aware = parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+ return int(aware.timestamp() * 1000)
+ return None
+
+
+def _pin_job_url(base_url: str, url: Any) -> str | None:
+ """Re-anchor a response-supplied job URL onto the configured origin, trusting only its path.
+
+ Discovered job URLs are fetched later with the stored Basic credentials, so they must never
+ steer a request off the validated instance: a compromised response could otherwise hand back an
+ attacker URL (receiving the token in cleartext) or an internal address the configured-host SSRF
+ check never examined. Rebuilding from the configured scheme + netloc plus the response path also
+ drops any userinfo/query/fragment, and keeps discovery working when Jenkins' self-configured
+ root URL differs from the URL the user connected with (a common reverse-proxy setup).
+ """
+ if not isinstance(url, str) or "\\" in url or "%5c" in url.lower():
+ return None
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ if not parsed.path.startswith("/"):
+ return None
+ base = urlparse(base_url)
+ return f"{base.scheme}://{base.netloc}{parsed.path}"
+
+
+def _discover_jobs(
+ session: requests.Session,
+ base_url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+) -> Iterator[dict[str, Any]]:
+ """Yield every job in the instance, recursing into Folders / Multibranch Pipelines.
+
+ Each yielded row carries the raw Jenkins job fields plus a `depth`. Container jobs (folders) are
+ yielded too — they're part of the catalog — but recursion also descends into them.
+ """
+ # (object_url, depth) frontier. Start at the instance root.
+ frontier: list[tuple[str, int]] = [(base_url, 0)]
+ seen_urls: set[str] = set()
+ discovered = 0
+
+ while frontier:
+ object_url, depth = frontier.pop()
+ response = _fetch(session, _api_json_url(object_url, f"jobs[{JOB_TREE_FIELDS}]"), auth, logger)
+ body = response.json()
+ jobs = body.get("jobs", []) if isinstance(body, dict) else []
+
+ for job in jobs:
+ if not isinstance(job, dict):
+ continue
+ # The pinned URL is the globally unique, stable identifier; skip anything without one
+ # and guard against a plugin that links a folder back into its own subtree.
+ job_url = _pin_job_url(base_url, job.get("url"))
+ if not job_url or job_url in seen_urls:
+ continue
+ seen_urls.add(job_url)
+ yield {**job, "id": job_url, "url": job_url}
+
+ discovered += 1
+ if discovered >= MAX_TOTAL_JOBS:
+ logger.warning(f"Jenkins: reached the {MAX_TOTAL_JOBS}-job discovery limit; stopping traversal")
+ return
+
+ if _is_job_container(job) and depth + 1 < MAX_JOB_DEPTH:
+ frontier.append((job_url, depth + 1))
+ elif _is_job_container(job):
+ logger.warning(f"Jenkins: max job nesting depth reached, not descending into {job_url}")
+
+
+def _iter_buildable_job_urls(
+ session: requests.Session,
+ base_url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ """The stable-ordered list of job URLs to fetch builds for (leaf, buildable jobs only)."""
+ urls = [
+ job["url"] for job in _discover_jobs(session, base_url, auth, logger) if job.get("buildable") and job.get("url")
+ ]
+ # Deterministic order so the resume bookmark resolves the same way across runs.
+ return sorted(urls)
+
+
+def _normalize_build(build: dict[str, Any], job_url: str) -> dict[str, Any]:
+ """Stamp the parent job URL and a stable `created_at` datetime onto a build row.
+
+ `created_at` is derived from the epoch-ms `timestamp` so both the partition key and the
+ incremental cursor are proper datetimes.
+ """
+ timestamp_ms = build.get("timestamp")
+ created_at = None
+ if isinstance(timestamp_ms, (int, float)):
+ created_at = datetime.fromtimestamp(timestamp_ms / 1000, tz=UTC).isoformat()
+ return {"job_url": job_url, "created_at": created_at, **build}
+
+
+def _iter_job_builds(
+ session: requests.Session,
+ job_url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+ watermark_ms: int | None,
+) -> Iterator[dict[str, Any]]:
+ """Yield a job's builds newest-first, windowing by index range and stopping at the watermark.
+
+ Jenkins returns builds strictly newest-first and has no server-side time filter, so on an
+ incremental sync we walk index ranges from the newest build and stop as soon as we reach a build
+ at or before `watermark_ms` — everything older is already synced. The boundary build (equal
+ timestamp) is re-emitted and deduped by merge on the primary key.
+ """
+ start = 0
+ for _page in range(MAX_BUILD_PAGES_PER_JOB):
+ tree = f"builds[{BUILD_TREE_FIELDS}]{{{start},{start + BUILDS_PAGE_SIZE}}}"
+ response = _fetch(session, _api_json_url(job_url, tree), auth, logger)
+ body = response.json()
+ builds = body.get("builds", []) if isinstance(body, dict) else []
+ if not builds:
+ return
+
+ for build in builds:
+ if not isinstance(build, dict):
+ continue
+ build_ts = build.get("timestamp")
+ if watermark_ms is not None and isinstance(build_ts, (int, float)) and build_ts < watermark_ms:
+ # Reached already-synced builds; the rest of this (and every later) page is older.
+ return
+ yield _normalize_build(build, job_url)
+
+ # A short page means we've reached the oldest build for this job.
+ if len(builds) < BUILDS_PAGE_SIZE:
+ return
+ start += BUILDS_PAGE_SIZE
+
+ # Ran the page cap without reaching a short page — a real job never has this many builds, so a
+ # server returning full pages forever is hostile/misconfigured. Stop rather than loop unbounded.
+ logger.warning(f"Jenkins: reached the {MAX_BUILD_PAGES_PER_JOB}-page build cap for {job_url}; stopping pagination")
+
+
+def _get_jobs_rows(
+ session: requests.Session,
+ base_url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+) -> Iterator[Any]:
+ for job in _discover_jobs(session, base_url, auth, logger):
+ batcher.batch(job)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+
+def _get_build_rows(
+ session: requests.Session,
+ base_url: str,
+ auth: tuple[str, str],
+ logger: FilteringBoundLogger,
+ batcher: Batcher,
+ resumable_source_manager: ResumableSourceManager[JenkinsResumeConfig],
+ watermark_ms: int | None,
+) -> Iterator[Any]:
+ job_urls = _iter_buildable_job_urls(session, base_url, auth, logger)
+
+ # Resolve the saved bookmark to the slice of jobs still to process. If the bookmarked job no
+ # longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ remaining = job_urls
+ if resume is not None and resume.next_job_url is not None and resume.next_job_url in job_urls:
+ remaining = job_urls[job_urls.index(resume.next_job_url) :]
+ logger.debug(f"Jenkins: resuming builds fan-out from {resume.next_job_url}")
+
+ for index, job_url in enumerate(remaining):
+ for build in _iter_job_builds(session, job_url, auth, logger, watermark_ms):
+ batcher.batch(build)
+ if batcher.should_yield():
+ yield batcher.get_table()
+
+ # Bookmark the NEXT job only after the current one is fully yielded, so a crash resumes at an
+ # unprocessed job rather than re-emitting one whose rows already landed. The incremental
+ # watermark finalizes at job end (desc sort_mode), so a bounded re-pull on crash is safe.
+ if index + 1 < len(remaining):
+ resumable_source_manager.save_state(JenkinsResumeConfig(next_job_url=remaining[index + 1]))
+
+
+def get_rows(
+ host: str | None,
+ username: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JenkinsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = JENKINS_ENDPOINTS[endpoint]
+ base_url = normalize_base_url(host)
+ auth = (username, api_token)
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # User-supplied host: never follow redirects (SSRF boundary) and redact the token from telemetry.
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False)
+
+ if config.fans_out_over_jobs:
+ watermark_ms = _to_epoch_ms(db_incremental_field_last_value) if should_use_incremental_field else None
+ yield from _get_build_rows(session, base_url, auth, logger, batcher, resumable_source_manager, watermark_ms)
+ else:
+ yield from _get_jobs_rows(session, base_url, auth, logger, batcher)
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def jenkins_source(
+ host: str | None,
+ username: str,
+ api_token: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[JenkinsResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = JENKINS_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ host=host,
+ username=username,
+ api_token=api_token,
+ 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,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Builds arrive newest-first and finalize the incremental watermark at job end (see
+ # _get_build_rows); the jobs catalog is a full-refresh pass.
+ 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/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/settings.py
new file mode 100644
index 000000000000..37765b928a3c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/settings.py
@@ -0,0 +1,62 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class JenkinsEndpointConfig:
+ name: str
+ incremental_fields: list[IncrementalField]
+ # STABLE field used to partition the Delta table — never an updated_at style field, which would
+ # rewrite partitions on every sync. None for endpoints with no stable timestamp (e.g. jobs).
+ partition_key: Optional[str] = None
+ sort_mode: Literal["asc", "desc"] = "asc"
+ primary_keys: list[str] = field(default_factory=lambda: ["url"])
+ # True for endpoints that iterate one child request per discovered job (builds).
+ fans_out_over_jobs: bool = False
+
+
+# Jenkins exposes machine-readable data at any object's `/api/json`. There is no vendor-hosted
+# instance and no cursor/page-token pagination — field selection and windowing use the `tree` query
+# param (e.g. `tree=builds[number,result,timestamp]{0,100}`). The two streams a data team actually
+# wants for DORA metrics are the job catalog and per-job build history.
+#
+# Jenkins has NO server-side "updated since" / timestamp filter on any endpoint. Builds are still
+# synced incrementally because Jenkins returns a job's builds strictly newest-first and lets us
+# window by index range, so we walk pages from the newest build and stop client-side as soon as we
+# reach builds we've already synced (the `created_at` watermark) — a genuine bounded fetch, not a
+# full-history re-walk. The job catalog itself has no stable cursor, so it is full refresh.
+JENKINS_ENDPOINTS: dict[str, JenkinsEndpointConfig] = {
+ "jobs": JenkinsEndpointConfig(
+ name="jobs",
+ # Jobs carry no creation timestamp, so there is no stable cursor or partition key. Discovery
+ # recurses into Folders / Multibranch Pipelines, so the row set is the full flattened catalog.
+ incremental_fields=[],
+ ),
+ "builds": JenkinsEndpointConfig(
+ name="builds",
+ # `timestamp` is the build's start time in epoch milliseconds and never changes once set. We
+ # normalize it into a `created_at` ISO 8601 datetime on each row and both partition and sync
+ # incrementally on that. A build's `result`/`duration` mutate after it first appears (a build
+ # still running when synced), so a build that finishes after newer builds have landed won't be
+ # re-fetched once it drops below the watermark — a full refresh re-pulls everything.
+ partition_key="created_at",
+ sort_mode="desc",
+ fans_out_over_jobs=True,
+ incremental_fields=[
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+}
+
+ENDPOINTS = tuple(JENKINS_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in JENKINS_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/source.py
index 8ad02180d357..5b7e5e936430 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/source.py
@@ -1,19 +1,47 @@
-from typing import cast
+from typing import Optional, cast
from 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 posthog.cloud_utils import is_cloud
+
+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 FieldType, ResumableSource
+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 ValidateDatabaseHostMixin
from 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.generated_configs import JenkinsSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.jenkins import (
+ JenkinsResumeConfig,
+ hostname_of,
+ jenkins_source,
+ scheme_of,
+ validate_credentials as validate_jenkins_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class JenkinsSource(SimpleSource[JenkinsSourceConfig]):
+class JenkinsSource(ResumableSource[JenkinsSourceConfig, JenkinsResumeConfig], ValidateDatabaseHostMixin):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.JENKINS
@@ -23,8 +51,137 @@ class JenkinsSource(SimpleSource[JenkinsSourceConfig]):
return SourceConfig(
name=SchemaExternalDataSourceType.JENKINS,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Jenkins (jenkins.io)",
+ keywords=["ci", "cd", "continuous integration"],
+ label="Jenkins",
+ releaseStatus=ReleaseStatus.ALPHA,
+ docsUrl="https://posthog.com/docs/cdp/sources/jenkins",
+ caption="""Enter your Jenkins URL, username, and API token to sync your CI/CD data into the PostHog Data warehouse.
+
+Jenkins is self-hosted, so enter the base URL of your own instance (for example `https://jenkins.example.com`).
+
+Create an API token from your Jenkins user page under **Configure > API Token**. The account needs **Overall/Read** plus **Job/Read** permission on the jobs you want to sync.""",
iconPath="/static/services/jenkins.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="host",
+ label="Jenkins URL",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="https://jenkins.example.com",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="username",
+ label="Username",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="jenkins-user",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # An invalid or revoked token surfaces as a 401 when `_fetch` calls `raise_for_status()`.
+ # Retrying can never satisfy a credential problem, so stop the sync.
+ "401 Client Error: Unauthorized for url": "Your Jenkins username or API token is invalid or has been revoked. Create a new API token on your Jenkins user page, then reconnect.",
+ # 403 at sync time means the account is missing Overall/Read or Job/Read on a synced job.
+ "403 Client Error: Forbidden for url": "The Jenkins account is missing the read permission needed to sync this data. Grant Overall/Read and Job/Read, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: JenkinsSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ descriptions = {
+ "jobs": "Every job in the instance, recursing into Folders and Multibranch Pipelines. Full refresh — jobs carry no creation timestamp to sync incrementally on.",
+ "builds": "Per-job build history (number, result, duration, timestamp). Incrementally synced newest-first on the build start time; a build's result and duration won't update once it drops below the watermark.",
+ }
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ has_incremental = bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=descriptions.get(endpoint),
+ )
+
+ schemas = [_build_schema(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_host(self, host: str | None, team_id: int) -> tuple[bool, str | None]:
+ try:
+ host_valid, host_error = self.is_database_host_valid(hostname_of(host), team_id)
+ scheme = scheme_of(host)
+ except ValueError:
+ return False, "Invalid Jenkins URL"
+ if not host_valid:
+ return False, host_error
+ # On Cloud the API token would otherwise be sent in cleartext to a customer-supplied http://
+ # host. Self-hosted PostHog may still reach a Jenkins instance over http on its own network.
+ if is_cloud() and scheme != "https":
+ return False, "Jenkins URL must use https"
+ return True, None
+
+ def validate_credentials(
+ self, config: JenkinsSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ host_valid, host_error = self._validate_host(config.host, team_id)
+ if not host_valid:
+ return False, host_error
+
+ return validate_jenkins_credentials(config.host, config.username, config.api_token, schema_name)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[JenkinsResumeConfig]:
+ return ResumableSourceManager[JenkinsResumeConfig](inputs, JenkinsResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: JenkinsSourceConfig,
+ resumable_source_manager: ResumableSourceManager[JenkinsResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ host_valid, host_error = self._validate_host(config.host, inputs.team_id)
+ if not host_valid:
+ raise ValueError(host_error or "Invalid Jenkins URL")
+
+ return jenkins_source(
+ host=config.host,
+ username=config.username,
+ api_token=config.api_token,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins.py
new file mode 100644
index 000000000000..698d125d5a0a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins.py
@@ -0,0 +1,422 @@
+import threading
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest import mock
+from unittest.mock import MagicMock
+
+import urllib3
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins import jenkins
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.jenkins import (
+ JenkinsResumeConfig,
+ _discover_jobs,
+ _get_build_rows,
+ _is_job_container,
+ _iter_job_builds,
+ _pin_job_url,
+ _to_epoch_ms,
+ normalize_base_url,
+ validate_credentials,
+)
+
+
+def _resp(payload: Any, status: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.json.return_value = payload
+ response.status_code = status
+ response.ok = 200 <= status < 400
+ return response
+
+
+class TestNormalizeBaseUrl:
+ @parameterized.expand(
+ [
+ ("adds_https_scheme", "jenkins.example.com", "https://jenkins.example.com"),
+ ("keeps_http", "http://jenkins.local", "http://jenkins.local"),
+ ("strips_trailing_slash", "https://jenkins.example.com/", "https://jenkins.example.com"),
+ ("keeps_subpath", "https://ci.example.com/jenkins", "https://ci.example.com/jenkins"),
+ ]
+ )
+ def test_normalizes(self, _name: str, raw: str, expected: str) -> None:
+ assert normalize_base_url(raw) == expected
+
+ @parameterized.expand(
+ [
+ # Each of these would let the dialed host diverge from the host the SSRF allowlist checks,
+ # or is otherwise not a plain http(s) base URL.
+ ("empty", ""),
+ ("blank", " "),
+ ("backslash_host_spoof", "https://169.254.169.254\\@internal"),
+ ("userinfo_hides_host", "https://[email protected]"),
+ ("bad_scheme", "ftp://jenkins.example.com"),
+ ("has_query", "https://jenkins.example.com?a=1"),
+ ("has_fragment", "https://jenkins.example.com#frag"),
+ ]
+ )
+ def test_rejects(self, _name: str, raw: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_base_url(raw)
+
+
+class TestPinJobUrl:
+ @parameterized.expand(
+ [
+ # Response-supplied job URLs are fetched with the stored Basic credentials, so only their
+ # path may be trusted — an off-origin URL must be re-anchored, never dialed as returned.
+ ("same_origin_passthrough", "https://j/job/svc/", "https://j/job/svc/"),
+ ("off_host_reanchored", "http://evil.example/steal/", "https://j/steal/"),
+ ("internal_ip_reanchored", "http://169.254.169.254/latest/", "https://j/latest/"),
+ ("userinfo_dropped", "https://user:pw@j/job/svc/", "https://j/job/svc/"),
+ ("query_and_fragment_dropped", "https://j/job/svc/?a=1#f", "https://j/job/svc/"),
+ ("backslash_rejected", "https://j\\@evil/job/", None),
+ ("relative_path_rejected", "job/svc/", None),
+ ("non_string_rejected", 123, None),
+ ("none_rejected", None, None),
+ ]
+ )
+ def test_pins_to_configured_origin(self, _name: str, url: Any, expected: str | None) -> None:
+ assert _pin_job_url("https://j", url) == expected
+
+
+class TestIsJobContainer:
+ @parameterized.expand(
+ [
+ ("folder", "com.cloudbees.hudson.plugins.folder.Folder", True),
+ ("org_folder", "jenkins.branch.OrganizationFolder", True),
+ ("multibranch", "org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject", True),
+ ("freestyle", "hudson.model.FreeStyleProject", False),
+ ("pipeline", "org.jenkinsci.plugins.workflow.job.WorkflowJob", False),
+ ("missing_class", None, False),
+ ]
+ )
+ def test_container_detection(self, _name: str, cls: str | None, expected: bool) -> None:
+ # Mis-detecting containers would either skip nested jobs (false negative) or issue a
+ # pointless recursion into a leaf job (false positive), so the suffix match is load-bearing.
+ assert _is_job_container({"_class": cls} if cls is not None else {}) is expected
+
+
+class TestToEpochMs:
+ @parameterized.expand(
+ [
+ # Jenkins build timestamps are epoch milliseconds; the watermark must be compared in ms,
+ # so a datetime cursor has to be scaled up by 1000 (a seconds bug would break incremental).
+ ("utc_datetime", datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC), 1767323045000),
+ ("naive_datetime", datetime(2026, 1, 2, 3, 4, 5), 1767323045000),
+ ("date_value", date(2026, 1, 2), 1767312000000),
+ ("iso_string", "2026-01-02T03:04:05Z", 1767323045000),
+ ("passthrough_int", 1767323045000, 1767323045000),
+ ("none", None, None),
+ ("garbage_string", "not-a-date", None),
+ ]
+ )
+ def test_to_epoch_ms(self, _name: str, value: Any, expected: int | None) -> None:
+ assert _to_epoch_ms(value) == expected
+
+
+class TestIterJobBuilds:
+ def _builds(self, *timestamps: int) -> list[dict[str, Any]]:
+ return [{"number": i, "url": f"https://j/{i}/", "timestamp": ts} for i, ts in enumerate(timestamps)]
+
+ def test_full_refresh_yields_all_with_derived_fields(self) -> None:
+ page = self._builds(3000, 2000, 1000)
+ with mock.patch.object(jenkins, "_fetch", return_value=_resp({"builds": page})):
+ rows = list(_iter_job_builds(MagicMock(), "https://j/", ("u", "t"), MagicMock(), watermark_ms=None))
+ assert [r["number"] for r in rows] == [0, 1, 2]
+ # Every row carries the parent job URL and a created_at derived from the epoch-ms timestamp.
+ assert all(r["job_url"] == "https://j/" for r in rows)
+ assert rows[0]["created_at"] == datetime.fromtimestamp(3000 / 1000, tz=UTC).isoformat()
+
+ def test_stops_at_watermark(self) -> None:
+ # Newest-first; watermark falls between the 2nd and 3rd builds, so only the two newer ones
+ # (>= watermark) are emitted and the walk stops without paging further.
+ page = self._builds(3000, 2000, 1000)
+ with mock.patch.object(jenkins, "_fetch", return_value=_resp({"builds": page})) as fetch:
+ rows = list(_iter_job_builds(MagicMock(), "https://j/", ("u", "t"), MagicMock(), watermark_ms=2000))
+ assert [r["timestamp"] for r in rows] == [3000, 2000]
+ assert fetch.call_count == 1
+
+ def test_advances_index_window_across_full_pages(self) -> None:
+ # A full page means more builds may remain, so the window must advance; a short page ends it.
+ pages = [_resp({"builds": self._builds(4000, 3000)}), _resp({"builds": self._builds(2000)})]
+ with mock.patch.object(jenkins, "BUILDS_PAGE_SIZE", 2):
+ with mock.patch.object(jenkins, "_fetch", side_effect=pages) as fetch:
+ rows = list(_iter_job_builds(MagicMock(), "https://j/", ("u", "t"), MagicMock(), watermark_ms=None))
+ assert fetch.call_count == 2
+ assert len(rows) == 3
+
+ def test_empty_page_terminates(self) -> None:
+ with mock.patch.object(jenkins, "_fetch", return_value=_resp({"builds": []})) as fetch:
+ rows = list(_iter_job_builds(MagicMock(), "https://j/", ("u", "t"), MagicMock(), watermark_ms=None))
+ assert rows == []
+ assert fetch.call_count == 1
+
+ def test_stops_at_page_cap(self) -> None:
+ # A server returning a full page for every window would loop forever; the page cap bounds it.
+ full_page = _resp({"builds": self._builds(2, 1)})
+ with mock.patch.object(jenkins, "BUILDS_PAGE_SIZE", 2):
+ with mock.patch.object(jenkins, "MAX_BUILD_PAGES_PER_JOB", 3):
+ with mock.patch.object(jenkins, "_fetch", return_value=full_page) as fetch:
+ rows = list(_iter_job_builds(MagicMock(), "https://j/", ("u", "t"), MagicMock(), watermark_ms=None))
+ assert fetch.call_count == 3
+ assert len(rows) == 6
+
+
+class TestDiscoverJobs:
+ def test_recurses_into_containers_and_dedupes(self) -> None:
+ root = {
+ "jobs": [
+ {"name": "svc", "url": "https://j/job/svc/", "_class": "hudson.model.FreeStyleProject"},
+ {"name": "team", "url": "https://j/job/team/", "_class": "com.cloudbees.hudson.plugins.folder.Folder"},
+ ]
+ }
+ team = {
+ "jobs": [
+ {
+ "name": "api",
+ "url": "https://j/job/team/job/api/",
+ "_class": "org.jenkinsci.plugins.workflow.job.WorkflowJob",
+ },
+ # A plugin linking the folder back to an already-seen job must not be re-emitted.
+ {"name": "svc", "url": "https://j/job/svc/", "_class": "hudson.model.FreeStyleProject"},
+ ]
+ }
+
+ def fake_fetch(_session: Any, url: str, *_args: Any, **_kwargs: Any) -> MagicMock:
+ return _resp(team) if "team" in url else _resp(root)
+
+ with mock.patch.object(jenkins, "_fetch", side_effect=fake_fetch):
+ urls = [job["url"] for job in _discover_jobs(MagicMock(), "https://j", ("u", "t"), MagicMock())]
+
+ assert sorted(urls) == ["https://j/job/svc/", "https://j/job/team/", "https://j/job/team/job/api/"]
+
+ def test_off_origin_job_urls_are_never_fetched(self) -> None:
+ # A compromised response marks an attacker URL as a buildable folder; recursion and the
+ # yielded row must both stay pinned to the configured origin so the Basic credentials are
+ # never sent off-instance.
+ root = {
+ "jobs": [
+ {
+ "name": "evil",
+ "url": "http://evil.example/exfil/",
+ "_class": "com.cloudbees.hudson.plugins.folder.Folder",
+ "buildable": True,
+ },
+ ]
+ }
+
+ fetched: list[str] = []
+
+ def fake_fetch(_session: Any, url: str, *_args: Any, **_kwargs: Any) -> MagicMock:
+ fetched.append(url)
+ return _resp(root if len(fetched) == 1 else {"jobs": []})
+
+ with mock.patch.object(jenkins, "_fetch", side_effect=fake_fetch):
+ rows = list(_discover_jobs(MagicMock(), "https://j", ("u", "t"), MagicMock()))
+
+ assert [r["url"] for r in rows] == ["https://j/exfil/"]
+ assert all(url.startswith("https://j/") for url in fetched)
+
+ def test_respects_total_job_budget(self) -> None:
+ # Breadth cap: a server returning a huge flat fan-out must stop once the budget is hit rather
+ # than yielding (and, for folders, recursing into) an unbounded number of jobs.
+ many = {
+ "jobs": [
+ {"name": f"j{i}", "url": f"https://j/job/j{i}/", "_class": "hudson.model.FreeStyleProject"}
+ for i in range(10)
+ ]
+ }
+ with mock.patch.object(jenkins, "MAX_TOTAL_JOBS", 3):
+ with mock.patch.object(jenkins, "_fetch", return_value=_resp(many)):
+ rows = list(_discover_jobs(MagicMock(), "https://j", ("u", "t"), MagicMock()))
+ assert len(rows) == 3
+
+ def test_respects_depth_cap(self) -> None:
+ # Every level returns a folder pointing one level deeper; the cap must bound the fetches so a
+ # pathological (or cyclic) folder tree can't loop forever.
+ def fake_fetch(_session: Any, url: str, *_args: Any, **_kwargs: Any) -> MagicMock:
+ depth = url.count("/job/")
+ return _resp(
+ {"jobs": [{"name": "f", "url": f"{url.split('/api')[0]}/job/f{depth}/", "_class": "...Folder"}]}
+ )
+
+ with mock.patch.object(jenkins, "MAX_JOB_DEPTH", 3):
+ with mock.patch.object(jenkins, "_fetch", side_effect=fake_fetch) as fetch:
+ list(_discover_jobs(MagicMock(), "https://j", ("u", "t"), MagicMock()))
+ # Fetches happen at depths 0, 1, 2; the cap blocks descending to depth 3.
+ assert fetch.call_count == 3
+
+
+class _FakeRaw:
+ def __init__(self, data: bytes) -> None:
+ self._data = data
+ self._pos = 0
+
+ def read(self, amt: int, decode_content: bool = False) -> bytes:
+ chunk = self._data[self._pos : self._pos + amt]
+ self._pos += len(chunk)
+ return chunk
+
+ def close(self) -> None:
+ pass
+
+
+class _BlockingRaw:
+ """A raw stream that blocks on read until the response is closed, then raises.
+
+ Mimics a hostile host that keeps a socket read blocked (under the byte cap and idle socket
+ timeout) until the download watchdog closes the connection.
+ """
+
+ def __init__(self) -> None:
+ self._closed = threading.Event()
+
+ def read(self, amt: int, decode_content: bool = False) -> bytes:
+ if self._closed.wait(timeout=5):
+ raise OSError("connection closed")
+ return b""
+
+ def close(self) -> None:
+ self._closed.set()
+
+
+class _FakeResponse:
+ def __init__(self, data: bytes = b"", raw: Any = None) -> None:
+ self.raw = raw if raw is not None else _FakeRaw(data)
+ self.closed = False
+ self._content: bytes | None = None
+
+ def close(self) -> None:
+ self.closed = True
+ self.raw.close()
+
+
+class TestReadBodyCapped:
+ def test_rejects_response_over_cap(self) -> None:
+ # A hostile/misconfigured host returning a body past the cap must raise (and release the
+ # connection) instead of buffering the whole thing into worker memory.
+ response: Any = _FakeResponse(b"y" * 50)
+ with mock.patch.object(jenkins, "MAX_RESPONSE_BYTES", 10):
+ with pytest.raises(ValueError):
+ jenkins._read_body_capped(response, "https://j/")
+ assert response.closed
+
+ def test_caches_body_under_cap(self) -> None:
+ # Under the cap the decoded body is cached so downstream `.json()` reads from memory.
+ response: Any = _FakeResponse(b'{"ok": true}')
+ jenkins._read_body_capped(response, "https://j/")
+ assert response._content == b'{"ok": true}'
+
+ def test_aborts_on_download_deadline(self) -> None:
+ # A read kept blocked below the socket idle timeout must be cut off by the watchdog closing
+ # the response, surfaced as a non-retryable deadline error, rather than holding the worker.
+ response: Any = _FakeResponse(raw=_BlockingRaw())
+ with mock.patch.object(jenkins, "MAX_DOWNLOAD_SECONDS", 0.05):
+ with pytest.raises(ValueError, match="download deadline"):
+ jenkins._read_body_capped(response, "https://j/")
+ assert response.closed
+
+
+def _fake_manager(state: JenkinsResumeConfig | None) -> MagicMock:
+ """A mock satisfying the ResumableSourceManager surface without Redis.
+
+ Saved states accumulate on `.saved` for assertions.
+ """
+ manager = MagicMock(spec=ResumableSourceManager)
+ manager.saved = []
+ manager.can_resume.return_value = state is not None
+ manager.load_state.return_value = state
+ manager.save_state.side_effect = manager.saved.append
+ return manager
+
+
+class TestGetBuildRows:
+ def _run(self, manager: MagicMock) -> None:
+ job_urls = ["https://j/a/", "https://j/b/", "https://j/c/"]
+ batcher = MagicMock()
+ batcher.should_yield.return_value = False
+ with mock.patch.object(jenkins, "_iter_buildable_job_urls", return_value=job_urls):
+ with mock.patch.object(jenkins, "_iter_job_builds", return_value=iter([])):
+ list(
+ _get_build_rows(
+ MagicMock(), "https://j", ("u", "t"), MagicMock(), batcher, manager, watermark_ms=None
+ )
+ )
+
+ def test_bookmarks_next_job_after_each_completes(self) -> None:
+ # After finishing job a, the bookmark points at b; after b, at c. The last job saves nothing,
+ # so a resume never restarts at a job whose rows already fully landed.
+ manager = _fake_manager(state=None)
+ self._run(manager)
+ assert [s.next_job_url for s in manager.saved] == ["https://j/b/", "https://j/c/"]
+
+ def test_resumes_from_saved_bookmark(self) -> None:
+ manager = _fake_manager(state=JenkinsResumeConfig(next_job_url="https://j/b/"))
+ with mock.patch.object(jenkins, "_iter_job_builds", return_value=iter([])) as iter_builds:
+ with mock.patch.object(
+ jenkins, "_iter_buildable_job_urls", return_value=["https://j/a/", "https://j/b/", "https://j/c/"]
+ ):
+ batcher = MagicMock()
+ batcher.should_yield.return_value = False
+ list(
+ _get_build_rows(
+ MagicMock(), "https://j", ("u", "t"), MagicMock(), batcher, manager, watermark_ms=None
+ )
+ )
+ # Only b and c are processed; a (already synced) is skipped.
+ processed = [call.args[1] for call in iter_builds.call_args_list]
+ assert processed == ["https://j/b/", "https://j/c/"]
+
+ def test_stale_bookmark_restarts_from_beginning(self) -> None:
+ # The bookmarked job was deleted between runs; fall back to the full list rather than syncing
+ # nothing (merge dedupes the re-pulled rows).
+ manager = _fake_manager(state=JenkinsResumeConfig(next_job_url="https://j/gone/"))
+ with mock.patch.object(jenkins, "_iter_job_builds", return_value=iter([])) as iter_builds:
+ with mock.patch.object(jenkins, "_iter_buildable_job_urls", return_value=["https://j/a/", "https://j/b/"]):
+ batcher = MagicMock()
+ batcher.should_yield.return_value = False
+ list(
+ _get_build_rows(
+ MagicMock(), "https://j", ("u", "t"), MagicMock(), batcher, manager, watermark_ms=None
+ )
+ )
+ processed = [call.args[1] for call in iter_builds.call_args_list]
+ assert processed == ["https://j/a/", "https://j/b/"]
+
+
+class TestValidateCredentials:
+ @parameterized.expand(
+ [
+ ("ok", 200, True),
+ ("unauthorized", 401, False),
+ ("forbidden", 403, False),
+ ("server_error", 500, False),
+ ]
+ )
+ def test_status_mapping(self, _name: str, status: int, expected_ok: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = _resp({}, status=status)
+ with mock.patch.object(jenkins, "make_tracked_session", return_value=session):
+ ok, error = validate_credentials("https://jenkins.example.com", "user", "token")
+ assert ok is expected_ok
+ assert (error is None) is expected_ok
+
+ def test_invalid_url_short_circuits_without_request(self) -> None:
+ with mock.patch.object(jenkins, "make_tracked_session") as make_session:
+ ok, error = validate_credentials("https://[email protected]", "user", "token")
+ assert ok is False
+ make_session.assert_not_called()
+
+ def test_request_uses_total_bounded_timeout(self) -> None:
+ # A total-bounded timeout is what stops a dripped-header response from stalling the request
+ # before the body watchdog is armed; a plain int read timeout would reintroduce that hang.
+ session = MagicMock()
+ session.get.return_value = _resp({}, status=200)
+ with mock.patch.object(jenkins, "make_tracked_session", return_value=session):
+ validate_credentials("https://jenkins.example.com", "user", "token")
+ timeout = session.get.call_args.kwargs["timeout"]
+ assert isinstance(timeout, urllib3.Timeout)
+ assert timeout.total == jenkins.MAX_DOWNLOAD_SECONDS
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins_source.py
new file mode 100644
index 000000000000..b415dda05a12
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/jenkins/tests/test_jenkins_source.py
@@ -0,0 +1,199 @@
+from typing import Any
+
+from unittest import mock
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig
+
+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 JenkinsSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.jenkins import JenkinsResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source import JenkinsSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+def _config() -> JenkinsSourceConfig:
+ return JenkinsSourceConfig(host="https://jenkins.example.com", username="ci-bot", api_token="token")
+
+
+class TestJenkinsSource:
+ def setup_method(self) -> None:
+ self.source = JenkinsSource()
+ self.team_id = 123
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.JENKINS
+
+ def test_source_is_released_not_hidden(self) -> None:
+ # A finished source must be visible (no unreleasedSource) and labelled ALPHA.
+ config = self.source.get_source_config
+ assert not config.unreleasedSource
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_source_config_fields(self) -> None:
+ config = self.source.get_source_config
+ by_name: dict[str, SourceFieldInputConfig] = {}
+ for field in config.fields:
+ assert isinstance(field, SourceFieldInputConfig)
+ by_name[field.name] = field
+ assert set(by_name) == {"host", "username", "api_token"}
+ # Only the API token is a secret; the URL and username are not.
+ assert by_name["api_token"].secret is True
+ assert by_name["host"].secret is False
+ assert by_name["username"].secret is False
+
+ def test_get_schemas_lists_every_endpoint(self) -> None:
+ schemas = {s.name for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas == set(ENDPOINTS)
+
+ @parameterized.expand(
+ [
+ # Jenkins has no server-side time filter; builds sync incrementally via newest-first index
+ # windowing on the derived start time, jobs are full refresh (no stable cursor).
+ ("builds", True),
+ ("jobs", False),
+ ]
+ )
+ def test_incremental_support_per_endpoint(self, endpoint: str, expected: bool) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(_config(), team_id=self.team_id)}
+ assert schemas[endpoint].supports_incremental is expected
+ assert schemas[endpoint].supports_append is expected
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(_config(), team_id=self.team_id, names=["builds"])
+ assert [s.name for s in schemas] == ["builds"]
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://jenkins.example.com/api/json"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://jenkins.example.com/job/x/api/json"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ assert any(key in observed_error for key in self.source.get_non_retryable_errors())
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='jenkins.example.com', port=443): Read timed out."),
+ ("server_error", "Jenkins API error (retryable): status=503"),
+ ("rate_limited", "Jenkins API error (retryable): status=429"),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:
+ assert not any(key in other_error for key in self.source.get_non_retryable_errors())
+
+ def test_canonical_descriptions_cover_every_endpoint(self) -> None:
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+ assert self.source.get_canonical_descriptions() is CANONICAL_DESCRIPTIONS
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas does no I/O, so the static catalog is safe to render in public docs.
+ assert self.source.lists_tables_without_credentials is True
+ assert {t["name"] for t in self.source.get_documented_tables()} == set(ENDPOINTS)
+
+ def test_get_resumable_source_manager_binds_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(MagicMock())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is JenkinsResumeConfig
+
+ def test_validate_credentials_delegates_when_host_valid(self) -> None:
+ with mock.patch.object(self.source, "_validate_host", return_value=(True, None)):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source.validate_jenkins_credentials",
+ return_value=(True, None),
+ ) as mock_validate:
+ result = self.source.validate_credentials(_config(), team_id=self.team_id, schema_name="builds")
+ assert result == (True, None)
+ mock_validate.assert_called_once_with("https://jenkins.example.com", "ci-bot", "token", "builds")
+
+ def test_validate_credentials_rejects_bad_host_without_probing(self) -> None:
+ with mock.patch.object(self.source, "_validate_host", return_value=(False, "bad host")):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source.validate_jenkins_credentials"
+ ) as mock_validate:
+ result = self.source.validate_credentials(_config(), team_id=self.team_id)
+ assert result == (False, "bad host")
+ mock_validate.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("cloud_http_rejected", True, "http://jenkins.example.com", False),
+ ("cloud_https_ok", True, "https://jenkins.example.com", True),
+ ("self_hosted_http_ok", False, "http://jenkins.local", True),
+ ]
+ )
+ def test_validate_host_https_requirement_on_cloud(
+ self, _name: str, is_cloud: bool, host: str, expected_ok: bool
+ ) -> None:
+ # On Cloud the API token would otherwise be sent in cleartext to a customer-supplied http host.
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source.is_cloud",
+ return_value=is_cloud,
+ ):
+ with mock.patch.object(self.source, "is_database_host_valid", return_value=(True, None)):
+ ok, _error = self.source._validate_host(host, self.team_id)
+ assert ok is expected_ok
+
+ def test_source_for_pipeline_plumbs_arguments(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "builds"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ manager = MagicMock()
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> MagicMock:
+ captured.update(kwargs)
+ return MagicMock()
+
+ with mock.patch.object(self.source, "_validate_host", return_value=(True, None)):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source.jenkins_source",
+ side_effect=fake_source,
+ ):
+ self.source.source_for_pipeline(_config(), manager, inputs)
+
+ assert captured["host"] == "https://jenkins.example.com"
+ assert captured["username"] == "ci-bot"
+ assert captured["api_token"] == "token"
+ assert captured["endpoint"] == "builds"
+ assert captured["should_use_incremental_field"] is True
+ assert captured["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert captured["resumable_source_manager"] is manager
+
+ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "jobs"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ captured: dict[str, Any] = {}
+
+ def fake_source(**kwargs: Any) -> str:
+ captured.update(kwargs)
+ return "response"
+
+ with mock.patch.object(self.source, "_validate_host", return_value=(True, None)):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.jenkins.source.jenkins_source",
+ side_effect=fake_source,
+ ):
+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)
+
+ assert captured["db_incremental_field_last_value"] is None
+
+ def test_source_for_pipeline_raises_on_invalid_host(self) -> None:
+ inputs = MagicMock()
+ inputs.schema_name = "jobs"
+ with mock.patch.object(self.source, "_validate_host", return_value=(False, "Jenkins URL must use https")):
+ try:
+ self.source.source_for_pipeline(_config(), MagicMock(), inputs)
+ except ValueError as e:
+ assert "https" in str(e)
+ else:
+ raise AssertionError("expected ValueError for invalid host")