: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 northpass_lms import source (#67798)
Tom Owers782cfc4b0bc4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 956f30ab33b0..2ff3f8fa94da 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -206,6 +206,7 @@ the row lists both.| mysql | DB protocol | pymysql | ➖ || new_york_times | HTTP | requests | ✅ || okta | HTTP | requests | ✅ |+| northpass_lms | HTTP | requests | ✅ || notion | HTTP | requests | ✅ || omnisend | HTTP | requests | ✅ || orb | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -532,7 +533,6 @@ doesn't conflict with concurrent PRs.- nexiopay- ninjaone_rmm- nocrm-- northpass_lms- nutshell- nylas- oncehubdiff --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 00ae99a579ea..619e18b1c0bd 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@@ -2160,7 +2160,7 @@ class NoCRMSourceConfig(config.Config):@config.configclass NorthpassLMSSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.pynew file mode 100644index 000000000000..f97348757c23--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/canonical_descriptions.py@@ -0,0 +1,128 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Descriptions taken from the Northpass (Gainsight Customer Education) API reference:+# https://developers.northpass.com/reference+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "people": {+ "description": "Learners and admins in your Northpass school. One row per person.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-people",+ "columns": {+ "id": "Unique identifier (UUID) for the person.",+ "type": "JSON:API resource type, always 'people'.",+ "email": "The person's email address.",+ "first_name": "The person's first name.",+ "last_name": "The person's last name.",+ "full_name": "The person's full name.",+ "name": "Display name for the person.",+ "registration_status": "Where the person is in the registration flow.",+ "disabled": "Whether the person's account is disabled.",+ "unsubscribed": "Whether the person has unsubscribed from emails.",+ "custom_avatar_url": "URL of the person's custom avatar image, if set.",+ "activated_at": "Timestamp when the person's account was activated.",+ "created_at": "Timestamp when the person was created.",+ "updated_at": "Timestamp when the person was last updated.",+ },+ },+ "courses": {+ "description": "Courses available in your Northpass school. One row per course.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-courses",+ "columns": {+ "id": "Unique identifier (UUID) for the course.",+ "type": "JSON:API resource type, always 'courses'.",+ "name": "The course name.",+ "status": "Publication status of the course (e.g. draft, published, archived).",+ "permalink": "URL-safe slug for the course.",+ "short_description": "Short description of the course.",+ "full_description": "Full description of the course.",+ "enrollments_count": "Number of enrollments in the course.",+ "credential_achievement_count": "Number of credentials achieved through the course.",+ "list_image_url": "URL of the course's list image.",+ "ribbon": "Ribbon label shown on the course card, if any.",+ "unpublished_changes": "Whether the course has unpublished draft changes.",+ "dependent_course_names": "Names of courses this course depends on.",+ "created_at": "Timestamp when the course was created.",+ "updated_at": "Timestamp when the course was last updated.",+ },+ },+ "learning_paths": {+ "description": "Learning paths (ordered collections of courses). One row per learning path.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-learning-paths",+ "columns": {+ "id": "Unique identifier (UUID) for the learning path.",+ "type": "JSON:API resource type, always 'learning_paths'.",+ "name": "The learning path name.",+ "description": "Description of the learning path.",+ "navigation_mode": "How learners move through the path (e.g. linear).",+ "picture_url": "URL of the learning path's image.",+ "learning_path_enrollment_link": "Public enrollment link for the learning path.",+ "share_learning_path_link": "Public share link for the learning path.",+ "created_at": "Timestamp when the learning path was created.",+ "updated_at": "Timestamp when the learning path was last updated.",+ },+ },+ "categories": {+ "description": "Categories used to organize courses. One row per category.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-categories",+ "columns": {+ "id": "Unique identifier (UUID) for the category.",+ "type": "JSON:API resource type, always 'categories'.",+ "name": "The category name.",+ "created_at": "Timestamp when the category was created.",+ "updated_at": "Timestamp when the category was last updated.",+ },+ },+ "groups": {+ "description": "Groups that people can belong to. One row per group.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-groups",+ "columns": {+ "id": "Unique identifier (UUID) for the group.",+ "type": "JSON:API resource type, always 'groups'.",+ "name": "The group name.",+ "memberships_count": "Number of members in the group.",+ "membership_count": "Number of members in the group (legacy field).",+ "group_enrollment_link": "Public enrollment link for the group.",+ "created_at": "Timestamp when the group was created.",+ "updated_at": "Timestamp when the group was last updated.",+ },+ },+ "quizzes": {+ "description": "Quizzes configured across your courses. One row per quiz.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-quizzes",+ "columns": {+ "id": "Unique identifier (UUID) for the quiz.",+ "type": "JSON:API resource type, always 'quizzes'.",+ "name": "The quiz name.",+ "quiz_type": "The quiz type (e.g. Quizzes::Static).",+ "legacy_id": "Legacy integer identifier for the quiz.",+ "created_at": "Timestamp when the quiz was created.",+ },+ },+ "course_enrollments": {+ "description": "Course enrollments, one row per person enrolled in a course. Fanned out per course.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-courses-course-uuid-enrollments",+ "columns": {+ "id": "Unique identifier (UUID) for the enrollment.",+ "type": "JSON:API resource type, always 'course_enrollments'.",+ "course_id": "UUID of the course the enrollment belongs to.",+ "person_id": "UUID of the enrolled person.",+ "progress": "Completion progress of the enrollment (0-100).",+ "enrolled_at": "Timestamp when the person enrolled.",+ "last_active_on": "Timestamp of the person's last activity in the course.",+ },+ },+ "learning_path_enrollments": {+ "description": "Learning path enrollments, one row per person enrolled in a learning path. Fanned out per learning path.",+ "docs_url": "https://developers.northpass.com/reference/get_v2-learning-paths-learning-path-uuid-enrollments",+ "columns": {+ "id": "Unique identifier (UUID) for the enrollment.",+ "type": "JSON:API resource type, always 'learning_path_enrollments'.",+ "learning_path_id": "UUID of the learning path the enrollment belongs to.",+ "person_id": "UUID of the enrolled person.",+ "progress": "Completion progress of the enrollment (0-100).",+ "enrolled_at": "Timestamp when the person enrolled.",+ "last_active_on": "Timestamp of the person's last activity in the learning path.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.pynew file mode 100644index 000000000000..57a12d8eb108--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/northpass_lms.py@@ -0,0 +1,268 @@+import dataclasses+from collections.abc import Iterator+from typing import Any, Optional+from urllib.parse import urlencode, urlsplit++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.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.northpass_lms.settings import (+ NORTHPASS_ENDPOINTS,+ NorthpassEndpointConfig,+)++NORTHPASS_BASE_URL = "https://api.northpass.com/v2"+# Northpass serves every account from this single shared host (no per-account subdomains).+NORTHPASS_HOST = "api.northpass.com"+# Northpass doesn't publish its max page size; 100 is a conventional cap that keeps payloads small.+PAGE_SIZE = 100+++def _is_northpass_url(url: str) -> bool:+ """Pin a URL to Northpass's HTTPS host.++ Pagination follows `links.next` from the response body, which is attacker-controlled if the+ upstream is compromised or spoofed. Since that URL is fetched with the API key attached, a+ hostile `next` pointing off-host would leak the credential. Northpass only ever serves from a+ single fixed host, so anything else is rejected before we fetch it.+ """+ parts = urlsplit(url)+ return parts.scheme == "https" and parts.netloc == NORTHPASS_HOST+++class NorthpassRetryableError(Exception):+ pass+++class NorthpassResumeConfig:+ # Full URL of the next page to fetch (JSON:API `links.next`). None means "start from the first+ # page". For fan-out endpoints it's the next page within the current parent resource.+ next_url: str | None = None+ # Fan-out only: the parent resource id currently being processed. A stable id bookmark (not a+ # positional index) so parents added/removed between a crash and retry can't resume us into the+ # wrong parent. None for top-level endpoints.+ parent_id: str | None = None+++def _headers(api_key: str) -> dict[str, str]:+ return {"X-Api-Key": api_key, "Accept": "application/json"}+++def _build_url(path: str, params: dict[str, Any]) -> str:+ base = f"{NORTHPASS_BASE_URL}{path}"+ return f"{base}?{urlencode(params)}" if params else base+++@retry(+ retry=retry_if_exception_type(+ (+ NorthpassRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict[str, Any]:+ response = session.get(url, headers=headers, timeout=60)++ # Northpass references rate limits but doesn't publicly quantify them; back off on 429 and+ # transient 5xx rather than failing the sync.+ if response.status_code == 429 or response.status_code >= 500:+ raise NorthpassRetryableError(f"Northpass API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ # A parent resource deleted mid fan-out 404s; the caller decides whether to skip or raise.+ log = logger.warning if response.status_code == 404 else logger.error+ log(f"Northpass API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()+++def _flatten_item(item: dict[str, Any], extra: Optional[dict[str, Any]] = None) -> dict[str, Any]:+ """Promote a JSON:API resource's `attributes` to the root, keeping `id`/`type`/`relationships`.++ The per-item `links` block is dropped (it's only self/action hyperlinks). `extra` injects+ fan-out parent identifiers so child rows always carry their parent id even when the API omits+ it from `attributes`.+ """+ row = dict(item)+ attributes = row.pop("attributes", None)+ row.pop("links", None)+ if isinstance(attributes, dict):+ row.update(attributes)+ if extra:+ row.update(extra)+ return row+++def _iter_pages(+ session: requests.Session,+ start_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield `(items, next_url)` for each JSON:API page, following `links.next`."""+ url = start_url+ while True:+ # Refuse to send the credentialed request anywhere but Northpass's host — the first URL is+ # built by us, but every subsequent one comes from the (untrusted) response body.+ if not _is_northpass_url(url):+ logger.warning(f"Northpass: refusing to fetch off-host pagination URL: {url}")+ return+ data = _fetch_page(session, url, headers, logger)+ items = data.get("data", [])+ next_url = data.get("links", {}).get("next")+ yield items, next_url+ if not next_url:+ return+ url = next_url+++def _iter_parent_ids(+ session: requests.Session, parent_path: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[str]:+ """Page through a parent collection and yield each resource id (for fan-out endpoints)."""+ for items, _ in _iter_pages(session, _build_url(parent_path, {"limit": PAGE_SIZE}), headers, logger):+ for item in items:+ yield item["id"]+++def _get_top_level_rows(+ session: requests.Session,+ config: NorthpassEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ resume_url = resume.next_url if resume is not None else None+ start_url = resume_url or _build_url(config.path, {"limit": PAGE_SIZE})+ if resume_url:+ logger.debug(f"Northpass: resuming {config.name} from {start_url}")++ for items, next_url in _iter_pages(session, start_url, headers, logger):+ if items:+ yield [_flatten_item(item) for item in items]+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes on the primary key.+ if next_url:+ resumable_source_manager.save_state(NorthpassResumeConfig(next_url=next_url))+++def _get_fan_out_rows(+ session: requests.Session,+ config: NorthpassEndpointConfig,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ # Guard (and narrow the Optional fan-out fields to str) so `parent_id_field` can be used as a+ # dict key below. A `raise` rather than `assert` so it survives `python -O`.+ if config.fan_out_parent is None or config.parent_id_field is None:+ raise ValueError(f"_get_fan_out_rows called with non-fan-out config: {config.name}")+ parent_config = NORTHPASS_ENDPOINTS[config.fan_out_parent]++ parent_ids = list(_iter_parent_ids(session, parent_config.path, headers, logger))++ # Resolve the saved parent bookmark to the slice of parents still to process. If the bookmarked+ # parent no longer exists (deleted between runs), start over — merge dedupes re-pulled rows.+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = parent_ids+ resume_url: str | None = None+ if resume is not None and resume.parent_id is not None and resume.parent_id in parent_ids:+ remaining = parent_ids[parent_ids.index(resume.parent_id) :]+ resume_url = resume.next_url+ logger.debug(f"Northpass: resuming {config.name} from parent={resume.parent_id}, url={resume_url}")++ for index, parent_id in enumerate(remaining):+ start_url = resume_url or _build_url(config.path.replace("{parent_id}", parent_id), {"limit": PAGE_SIZE})+ resume_url = None # only the resumed-into parent uses the saved URL; the rest start fresh++ try:+ for items, next_url in _iter_pages(session, start_url, headers, logger):+ if items:+ yield [_flatten_item(item, extra={config.parent_id_field: parent_id}) for item in items]+ if next_url:+ resumable_source_manager.save_state(NorthpassResumeConfig(next_url=next_url, parent_id=parent_id))+ except requests.HTTPError as exc:+ # A parent deleted between enumeration and this fetch 404s. Skip it rather than failing+ # the whole sync — the enrollments are genuinely gone. Any other HTTP error re-raises.+ if exc.response is not None and exc.response.status_code == 404:+ logger.warning(f"Northpass: {config.fan_out_parent} {parent_id} not found, skipping")+ else:+ raise++ # Advance the bookmark to the next parent so a crash between parents resumes correctly.+ if index + 1 < len(remaining):+ resumable_source_manager.save_state(NorthpassResumeConfig(next_url=None, parent_id=remaining[index + 1]))+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = NORTHPASS_ENDPOINTS[endpoint]+ headers = _headers(api_key)+ # One session reused across every page (and, for fan-out, every parent) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. `redact_values` scrubs the API key+ # from logged URLs and captured HTTP samples; `allow_redirects=False` stops a 30x from+ # forwarding the credentialed X-Api-Key header off-host.+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)++ if config.fan_out_parent is not None:+ yield from _get_fan_out_rows(session, config, headers, logger, resumable_source_manager)+ else:+ yield from _get_top_level_rows(session, config, headers, logger, resumable_source_manager)+++def northpass_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],+) -> SourceResponse:+ config = NORTHPASS_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="month" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )+++def validate_credentials(api_key: str) -> tuple[bool, int | None]:+ """Probe a cheap list endpoint to confirm the API key is genuine.++ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error.+ """+ url = _build_url("/courses", {"limit": 1})+ try:+ session = make_tracked_session(redact_values=(api_key,), allow_redirects=False)+ response = session.get(url, headers=_headers(api_key), timeout=10)+ except Exception:+ return False, None+ return response.status_code == 200, response.status_codediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.pynew file mode 100644index 000000000000..83418986c365--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/settings.py@@ -0,0 +1,87 @@+from dataclasses import dataclass, field+from typing import Optional++from products.warehouse_sources.backend.types import IncrementalField++# Northpass exposes no server-side timestamp filter (list endpoints only accept page/limit/q and a+# fixed default sort), so every endpoint is full refresh only — there is no reliable incremental+# cursor. See `northpass_lms.py` for the pagination transport.+++@dataclass+class NorthpassEndpointConfig:+ name: str+ # JSON:API collection path relative to the API base. Fan-out children use a `{parent_id}`+ # placeholder resolved per parent resource.+ path: str+ # Stable creation-time field used for datetime partitioning. Never `updated_at` — it moves and+ # would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ # For fan-out endpoints: the parent endpoint name to iterate for `{parent_id}`, and the column+ # name under which the parent id is injected into each child row (also part of the primary key).+ fan_out_parent: Optional[str] = None+ parent_id_field: Optional[str] = None+ # Human-readable note surfaced in the schema picker / docs.+ description: Optional[str] = None+++NORTHPASS_ENDPOINTS: dict[str, NorthpassEndpointConfig] = {+ "people": NorthpassEndpointConfig(+ name="people",+ path="/people",+ partition_key="created_at",+ ),+ "courses": NorthpassEndpointConfig(+ name="courses",+ path="/courses",+ partition_key="created_at",+ ),+ "learning_paths": NorthpassEndpointConfig(+ name="learning_paths",+ path="/learning-paths",+ partition_key="created_at",+ ),+ "categories": NorthpassEndpointConfig(+ name="categories",+ path="/categories",+ partition_key="created_at",+ ),+ "groups": NorthpassEndpointConfig(+ name="groups",+ path="/groups",+ partition_key="created_at",+ ),+ "quizzes": NorthpassEndpointConfig(+ name="quizzes",+ path="/quizzes",+ partition_key="created_at",+ ),+ # Enrollments have no top-level list endpoint — they're only reachable per course / learning+ # path, so these fan out over the parent resource. The parent id is injected into each row and+ # forms part of the primary key (the enrollment id is only documented as unique per parent).+ "course_enrollments": NorthpassEndpointConfig(+ name="course_enrollments",+ path="/courses/{parent_id}/enrollments",+ partition_key="enrolled_at",+ primary_keys=["course_id", "id"],+ fan_out_parent="courses",+ parent_id_field="course_id",+ description="Enrollments for every course. Fans out one request per course. Full refresh only.",+ ),+ "learning_path_enrollments": NorthpassEndpointConfig(+ name="learning_path_enrollments",+ path="/learning-paths/{parent_id}/enrollments",+ partition_key="enrolled_at",+ primary_keys=["learning_path_id", "id"],+ fan_out_parent="learning_paths",+ parent_id_field="learning_path_id",+ description="Enrollments for every learning path. Fans out one request per learning path. Full refresh only.",+ ),+}++ENDPOINTS = tuple(NORTHPASS_ENDPOINTS.keys())++# Northpass documents no server-side timestamp filter, so no endpoint advertises incremental fields.+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: [] for name in NORTHPASS_ENDPOINTS}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.pyindex 93338021aa58..f59102db13f7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/source.py@@ -1,19 +1,45 @@-from typing import cast+from typing import Optional, castfrom 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 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.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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NorthpassLMSSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.northpass_lms import (+ NorthpassResumeConfig,+ northpass_source,+ validate_credentials as validate_northpass_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ NORTHPASS_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class NorthpassLMSSource(SimpleSource[NorthpassLMSSourceConfig]):+class NorthpassLMSSource(ResumableSource[NorthpassLMSSourceConfig, NorthpassResumeConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # surface in public docs.+ lists_tables_without_credentials = True+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.NORTHPASSLMS@@ -24,7 +50,92 @@ class NorthpassLMSSource(SimpleSource[NorthpassLMSSourceConfig]):name=SchemaExternalDataSourceType.NORTHPASS_LMS,category=DataWarehouseSourceCategory.HR___RECRUITING,label="Northpass LMS",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your Northpass API key to sync your Northpass (Gainsight Customer Education) learning data into the PostHog Data warehouse.++You can create an API key in your Northpass admin panel under **Apps → API Access**.""",iconPath="/static/services/northpass_lms.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/northpass-lms",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # An invalid or revoked API key surfaces as an HTTPError when `_fetch_page` calls+ # `raise_for_status()`. Retrying can never satisfy a credential problem, so stop the sync.+ "401 Client Error: Unauthorized for url: https://api.northpass.com": "Your Northpass API key is invalid or has been revoked. Create a new key in your Northpass admin panel under Apps → API Access, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.northpass.com": "Your Northpass API key does not have permission to access this data. Check the key's permissions in your Northpass admin panel, then reconnect.",+ }++ def get_schemas(+ self,+ config: NorthpassLMSSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ # Northpass documents no server-side timestamp filter, so every endpoint is full refresh only.+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = NORTHPASS_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ detected_primary_keys=endpoint_config.primary_keys,+ should_sync_default=endpoint_config.should_sync_default,+ description=endpoint_config.description,+ )++ 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_credentials(+ self, config: NorthpassLMSSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status_code = validate_northpass_credentials(config.api_key)+ if ok:+ return True, None++ if status_code in (401, 403):+ return False, "Invalid Northpass API key"+ return False, "Could not connect to Northpass. Please check your API key and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[NorthpassResumeConfig]:+ return ResumableSourceManager[NorthpassResumeConfig](inputs, NorthpassResumeConfig)++ def source_for_pipeline(+ self,+ config: NorthpassLMSSourceConfig,+ resumable_source_manager: ResumableSourceManager[NorthpassResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return northpass_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.pynew file mode 100644index 000000000000..d3098db8ecf7--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms.py@@ -0,0 +1,270 @@+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms import northpass_lms+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.northpass_lms import (+ NorthpassResumeConfig,+ _build_url,+ _flatten_item,+ _is_northpass_url,+ get_rows,+ northpass_source,+)+++class TestBuildUrl:+ @parameterized.expand(+ [+ ("no_params", {}, "https://api.northpass.com/v2/courses"),+ ("encodes_params", {"limit": 100}, "https://api.northpass.com/v2/courses?limit=100"),+ ]+ )+ def test_build_url(self, _name, params, expected):+ assert _build_url("/courses", params) == expected+++class TestFlattenItem:+ def test_promotes_attributes_and_drops_links(self):+ item = {+ "id": "c1",+ "type": "courses",+ "attributes": {"name": "Intro", "created_at": "2024-10-08T08:37:18Z"},+ "links": {"self": "https://api.northpass.com/v2/courses/c1"},+ "relationships": {"categories": {"data": []}},+ }+ row = _flatten_item(item)++ assert row["id"] == "c1"+ assert row["type"] == "courses"+ assert row["name"] == "Intro"+ assert row["created_at"] == "2024-10-08T08:37:18Z"+ assert "links" not in row+ assert "attributes" not in row+ assert row["relationships"] == {"categories": {"data": []}}++ def test_injects_extra_parent_id(self):+ item = {"id": "e1", "type": "course_enrollments", "attributes": {"progress": 30}}+ row = _flatten_item(item, extra={"course_id": "c1"})++ assert row["course_id"] == "c1"+ assert row["progress"] == 30++ def test_tolerates_missing_attributes(self):+ row = _flatten_item({"id": "x", "type": "quizzes"})+ assert row == {"id": "x", "type": "quizzes"}+++class _FakeResumableManager:+ def __init__(self, state: NorthpassResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[NorthpassResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> NorthpassResumeConfig | None:+ return self._state++ def save_state(self, data: NorthpassResumeConfig) -> None:+ self.saved.append(data)+++def _patch_fetch(monkeypatch: Any, pages: dict[str, Any]) -> list[str]:+ fetched: list[str] = []++ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ fetched.append(url)+ result = pages[url]+ if isinstance(result, Exception):+ raise result+ return result++ monkeypatch.setattr(northpass_lms, "_fetch_page", fake_fetch)+ monkeypatch.setattr(northpass_lms, "make_tracked_session", lambda *a, **k: MagicMock())+ return fetched+++def _collect(manager: _FakeResumableManager, endpoint: str) -> list[dict]:+ rows: list[dict] = []+ for batch in get_rows(+ api_key="key",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(batch)+ return rows+++class TestTopLevelPagination:+ def test_paginates_until_next_link_missing(self, monkeypatch: Any):+ pages = {+ "https://api.northpass.com/v2/courses?limit=100": {+ "data": [{"id": "1", "attributes": {"name": "a"}}, {"id": "2", "attributes": {"name": "b"}}],+ "links": {"next": "https://api.northpass.com/v2/courses?page=2&limit=100"},+ },+ "https://api.northpass.com/v2/courses?page=2&limit=100": {+ "data": [{"id": "3", "attributes": {"name": "c"}}],+ "links": {},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), "courses")++ assert [r["id"] for r in rows] == ["1", "2", "3"]+ assert [r["name"] for r in rows] == ["a", "b", "c"]+ assert fetched == list(pages)++ def test_saves_resume_state_only_while_pages_remain(self, monkeypatch: Any):+ pages = {+ "https://api.northpass.com/v2/courses?limit=100": {+ "data": [{"id": "1"}],+ "links": {"next": "https://api.northpass.com/v2/courses?page=2&limit=100"},+ },+ "https://api.northpass.com/v2/courses?page=2&limit=100": {"data": [{"id": "2"}], "links": {}},+ }+ _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager()+ _collect(manager, "courses")++ # Saved after yielding page 1 (more remains), never after the last page.+ assert manager.saved == [+ NorthpassResumeConfig(next_url="https://api.northpass.com/v2/courses?page=2&limit=100")+ ]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any):+ pages = {+ "https://api.northpass.com/v2/courses?page=2&limit=100": {"data": [{"id": "2"}], "links": {}},+ }+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(+ NorthpassResumeConfig(next_url="https://api.northpass.com/v2/courses?page=2&limit=100")+ )+ rows = _collect(manager, "courses")++ assert [r["id"] for r in rows] == ["2"]+ # The first page is skipped entirely — resume starts at the saved URL.+ assert fetched == ["https://api.northpass.com/v2/courses?page=2&limit=100"]++ def test_refuses_to_follow_offhost_next_link(self, monkeypatch: Any):+ # A hostile upstream points `links.next` off-host; the credentialed request must not be sent.+ pages = {+ "https://api.northpass.com/v2/courses?limit=100": {+ "data": [{"id": "1"}],+ "links": {"next": "https://evil.example.com/steal?limit=100"},+ },+ }+ fetched = _patch_fetch(monkeypatch, pages)+ rows = _collect(_FakeResumableManager(), "courses")++ assert [r["id"] for r in rows] == ["1"]+ # Pagination stops at the Northpass host; the off-host URL is never fetched.+ assert fetched == ["https://api.northpass.com/v2/courses?limit=100"]+++class TestIsNorthpassUrl:+ @parameterized.expand(+ [+ ("valid_https_host", "https://api.northpass.com/v2/courses?page=2", True),+ ("attacker_host", "https://evil.example.com/v2/courses", False),+ ("internal_metadata", "http://169.254.169.254/latest/meta-data/", False),+ ("http_scheme_rejected", "http://api.northpass.com/v2/courses", False),+ ("subdomain_spoof_rejected", "https://api.northpass.com.evil.com/v2/courses", False),+ ]+ )+ def test_is_northpass_url(self, _name, url, expected):+ assert _is_northpass_url(url) is expected+++class TestFanOut:+ def _parent_and_children(self) -> dict[str, Any]:+ return {+ # Parent enumeration (two courses).+ "https://api.northpass.com/v2/courses?limit=100": {+ "data": [{"id": "c1"}, {"id": "c2"}],+ "links": {},+ },+ "https://api.northpass.com/v2/courses/c1/enrollments?limit=100": {+ "data": [{"id": "e1", "attributes": {"progress": 30}}],+ "links": {},+ },+ "https://api.northpass.com/v2/courses/c2/enrollments?limit=100": {+ "data": [{"id": "e2", "attributes": {"progress": 60}}],+ "links": {},+ },+ }++ def test_injects_parent_id_into_every_child_row(self, monkeypatch: Any):+ _patch_fetch(monkeypatch, self._parent_and_children())+ rows = _collect(_FakeResumableManager(), "course_enrollments")++ by_id = {r["id"]: r for r in rows}+ assert by_id["e1"]["course_id"] == "c1"+ assert by_id["e2"]["course_id"] == "c2"+ # The injected parent id is what keeps the [course_id, id] primary key unique table-wide.+ assert by_id["e1"]["progress"] == 30++ def test_advances_parent_bookmark_between_parents(self, monkeypatch: Any):+ _patch_fetch(monkeypatch, self._parent_and_children())+ manager = _FakeResumableManager()+ _collect(manager, "course_enrollments")++ # After finishing c1, the bookmark advances to c2 so a crash resumes at the next parent.+ assert NorthpassResumeConfig(next_url=None, parent_id="c2") in manager.saved++ def test_resumes_from_parent_bookmark_skipping_earlier_parents(self, monkeypatch: Any):+ pages = self._parent_and_children()+ fetched = _patch_fetch(monkeypatch, pages)+ manager = _FakeResumableManager(NorthpassResumeConfig(next_url=None, parent_id="c2"))+ rows = _collect(manager, "course_enrollments")++ assert [r["id"] for r in rows] == ["e2"]+ # c1's enrollments must not be re-fetched when resuming into c2.+ assert "https://api.northpass.com/v2/courses/c1/enrollments?limit=100" not in fetched++ def test_skips_parent_that_404s_mid_fanout(self, monkeypatch: Any):+ pages = self._parent_and_children()+ pages["https://api.northpass.com/v2/courses/c1/enrollments?limit=100"] = requests.HTTPError(+ response=MagicMock(status_code=404)+ )+ _patch_fetch(monkeypatch, pages)++ rows = _collect(_FakeResumableManager(), "course_enrollments")++ # c1 vanished mid-sync; its 404 is swallowed and c2 still syncs.+ assert [r["id"] for r in rows] == ["e2"]++ def test_reraises_non_404_child_error(self, monkeypatch: Any):+ pages = self._parent_and_children()+ pages["https://api.northpass.com/v2/courses/c1/enrollments?limit=100"] = requests.HTTPError(+ response=MagicMock(status_code=500)+ )+ _patch_fetch(monkeypatch, pages)++ with pytest.raises(requests.HTTPError):+ _collect(_FakeResumableManager(), "course_enrollments")+++class TestNorthpassSource:+ @parameterized.expand(+ [+ ("people", ["id"], "created_at"),+ ("courses", ["id"], "created_at"),+ ("course_enrollments", ["course_id", "id"], "enrolled_at"),+ ("learning_path_enrollments", ["learning_path_id", "id"], "enrolled_at"),+ ]+ )+ def test_source_response_carries_endpoint_keys_and_partitioning(self, endpoint, primary_keys, partition_key):+ response = northpass_source(+ api_key="key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()+ )+ assert response.name == endpoint+ assert response.primary_keys == primary_keys+ assert response.partition_keys == [partition_key]+ assert response.partition_mode == "datetime"+ assert response.partition_format == "month"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.pynew file mode 100644index 000000000000..246b24a22576--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/northpass_lms/tests/test_northpass_lms_source.py@@ -0,0 +1,146 @@+from unittest import mock++from parameterized import parameterized++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import NorthpassLMSSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.northpass_lms import (+ NorthpassResumeConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.settings import (+ ENDPOINTS,+ NORTHPASS_ENDPOINTS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.source import NorthpassLMSSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestNorthpassLMSSource:+ def setup_method(self):+ self.source = NorthpassLMSSource()+ self.team_id = 123+ self.config = NorthpassLMSSourceConfig(api_key="key")++ def test_source_type(self):+ assert self.source.source_type == ExternalDataSourceType.NORTHPASSLMS++ def test_get_source_config(self):+ config = self.source.get_source_config++ assert config.name.value == "NorthpassLMS"+ assert config.label == "Northpass LMS"+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # A finished source ships visible — the scaffold's unreleasedSource flag must be gone.+ assert config.unreleasedSource is None+ assert config.iconPath == "/static/services/northpass_lms.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/northpass-lms"++ def test_api_key_field_is_secret_password(self):+ config = self.source.get_source_config+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.secret is True+ assert api_key_field.required is True++ @parameterized.expand(+ [+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.northpass.com/v2/people?limit=100"),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.northpass.com/v2/courses?limit=100"),+ ]+ )+ def test_non_retryable_errors_match_auth_failures(self, _name, observed_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable_errors)++ @parameterized.expand(+ [+ ("throttle", "429 Client Error: Too Many Requests for url: https://api.northpass.com/v2/people"),+ ("server", "500 Server Error: Internal Server Error for url: https://api.northpass.com/v2/people"),+ ("timeout", "HTTPSConnectionPool(host='api.northpass.com', port=443): Read timed out."),+ ]+ )+ def test_non_retryable_errors_do_not_match_transient(self, _name, other_error):+ non_retryable_errors = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable_errors)++ def test_get_schemas_are_all_full_refresh(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ assert set(schemas) == set(ENDPOINTS)+ # Northpass documents no server-side timestamp filter, so nothing may advertise incremental.+ for schema in schemas.values():+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_expose_endpoint_primary_keys(self):+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}++ # Fan-out children must carry the parent id in their key so rows stay unique table-wide.+ assert schemas["people"].detected_primary_keys == ["id"]+ assert schemas["course_enrollments"].detected_primary_keys == ["course_id", "id"]+ assert schemas["learning_path_enrollments"].detected_primary_keys == ["learning_path_id", "id"]++ def test_get_schemas_filtered_by_names(self):+ schemas = self.source.get_schemas(self.config, self.team_id, names=["courses"])+ assert len(schemas) == 1+ assert schemas[0].name == "courses"++ def test_get_schemas_filtered_unknown_name_returns_empty(self):+ assert self.source.get_schemas(self.config, self.team_id, names=["nope"]) == []++ def test_lists_tables_without_credentials_publishes_catalog(self):+ # Static endpoint catalog (no I/O) — the public docs table list should render.+ assert self.source.lists_tables_without_credentials is True+ documented = self.source.get_documented_tables()+ assert {table["name"] for table in documented} == set(ENDPOINTS)++ def test_canonical_descriptions_cover_every_endpoint(self):+ canonical = self.source.get_canonical_descriptions()+ assert set(canonical) == set(NORTHPASS_ENDPOINTS)++ @parameterized.expand(+ [+ ("valid", (True, 200), True, None),+ ("unauthorized", (False, 401), False, "Invalid Northpass API key"),+ ("forbidden", (False, 403), False, "Invalid Northpass API key"),+ (+ "transport_error",+ (False, None),+ False,+ "Could not connect to Northpass. Please check your API key and try again.",+ ),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.source.validate_northpass_credentials"+ )+ def test_validate_credentials(self, _name, mock_return, expected_valid, expected_message, mock_validate):+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("key")++ def test_get_resumable_source_manager_bound_to_resume_config(self):+ manager = self.source.get_resumable_source_manager(mock.MagicMock())+ assert manager._data_class is NorthpassResumeConfig++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.northpass_lms.source.northpass_source"+ )+ def test_source_for_pipeline_plumbs_arguments(self, mock_northpass_source):+ inputs = mock.MagicMock()+ inputs.schema_name = "courses"+ manager = mock.MagicMock()++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_northpass_source.assert_called_once()+ kwargs = mock_northpass_source.call_args.kwargs+ assert kwargs["api_key"] == "key"+ assert kwargs["endpoint"] == "courses"+ assert kwargs["resumable_source_manager"] is manager