: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): add KnowBe4 source (#73196)
Tom Owers083f262b0841
diff --git a/frontend/public/services/knowbe4.png b/frontend/public/services/knowbe4.pngindex 8b3861655107..3ceb37669f33 100644Binary files a/frontend/public/services/knowbe4.png and b/frontend/public/services/knowbe4.png differdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 971c4ffe0c2c..0cb7284a7183 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -314,6 +314,7 @@ the row lists both.| klaus | HTTP | requests | ✅ || klaviyo | HTTP | requests | ✅ || knock | HTTP | requests + `rest_source.RESTClient` | ✅ |+| knowbe4 | HTTP | requests + `rest_source.RESTClient` | ✅ || koyeb | HTTP | requests | ✅ || kong_konnect | HTTP | requests | ✅ || kubecost | HTTP | requests | ✅ |@@ -1035,7 +1036,6 @@ doesn't conflict with concurrent PRs.- kisi- kissmetrics- klarna-- knowbe4- kommo- komodor- koyebdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knowbe4.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knowbe4.pyindex 6c2f1aff2ef2..df99f28b2f10 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knowbe4.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/knowbe4.py@@ -1,9 +1,12 @@# This file is automatically generated from `SourceRegistry.get_all_sources()`# Do not edit manually - run `pnpm generate:source-configs` to regenerate.+from typing import Literal+from products.warehouse_sources.backend.temporal.data_imports.sources.common import config@config.configclass Knowbe4SourceConfig(config.Config):- pass+ api_key: str+ region: Literal["us", "eu", "ca", "uk", "de"] = config.value(default="us")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/canonical_descriptions.pynew file mode 100644index 000000000000..78f2932df67f--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/canonical_descriptions.py@@ -0,0 +1,156 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++# Sourced from KnowBe4's Reporting API docs (https://developer.knowbe4.com/rest/reporting). Columns+# not covered here fall back to LLM enrichment, so partial coverage is fine; keys match the+# endpoint/schema names returned by `get_schemas`.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "users": {+ "description": "Every user in the KnowBe4 account, one row per user, including their current phishing risk score.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Users/paths/~1v1~1users/get",+ "columns": {+ "id": "User ID.",+ "employee_number": "Employee number.",+ "first_name": "First name.",+ "last_name": "Last name.",+ "job_title": "Job title.",+ "email": "Email address.",+ "phish_prone_percentage": "Phish-prone percentage.",+ "phone_number": "Phone number.",+ "location": "Location.",+ "division": "Division.",+ "manager_name": "Manager's name.",+ "manager_email": "Manager's email.",+ "groups": "Array of group IDs (active or archived) the user is a member of.",+ "current_risk_score": "The user's current risk score.",+ "joined_on": "Date the user was added to the KnowBe4 account.",+ "last_sign_in": "Date the user last signed in to their KnowBe4 account.",+ "status": "Status of the user (active or archived).",+ "organization": "Organization.",+ "department": "Department.",+ "employee_start_date": "Employee start date.",+ "archived_at": "Date the user was archived, if applicable.",+ },+ },+ "groups": {+ "description": "Every group configured in the KnowBe4 account, one row per group.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Groups/paths/~1v1~1groups/get",+ "columns": {+ "id": "Group ID.",+ "name": "Group name.",+ "group_type": "Group type (console_group, smart_group, or provisioning_managed_group).",+ "member_count": "Number of members in the group.",+ "current_risk_score": "The group's current risk score.",+ "status": "Status of the group (active or archived).",+ },+ },+ "group_members": {+ "description": "Membership rows linking each group to its member users.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Users/paths/~1v1~1groups~1%7Bgroup_id%7D~1members/get",+ "columns": {+ "group_id": "ID of the group this membership row belongs to.",+ "id": "User ID of the member.",+ "email": "Member's email address.",+ "first_name": "Member's first name.",+ "last_name": "Member's last name.",+ "status": "Status of the member (active or archived).",+ },+ },+ "phishing_campaigns": {+ "description": "Phishing campaigns configured in the account, including aggregate results across all of the campaign's security tests.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Phishing/paths/~1v1~1phishing~1campaigns/get",+ "columns": {+ "campaign_id": "Unique ID of the phishing campaign.",+ "name": "Name of the phishing campaign.",+ "groups": "Array of groups targeted by the campaign.",+ "last_phish_prone_percentage": "Last phish-prone percentage recorded on the campaign.",+ "last_run": "Date and time of the last phishing security test in the campaign.",+ "status": "Status of the campaign.",+ "frequency": "How often the phishing campaign is configured to run.",+ "create_date": "Date and time the campaign was created.",+ "psts_count": "Number of phishing security tests in the campaign.",+ "psts": "Array of phishing security tests belonging to the campaign.",+ },+ },+ "phishing_security_tests": {+ "description": "Individual phishing security tests (PSTs), including delivery and interaction result counts.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Phishing/paths/~1v1~1phishing~1security_tests/get",+ "columns": {+ "campaign_id": "Unique ID of the phishing campaign the test belongs to.",+ "pst_id": "Unique ID of the phishing security test.",+ "status": "Status of the phishing security test.",+ "name": "Name of the phishing security test.",+ "phish_prone_percentage": "Phish-prone percentage on the test, in decimal form.",+ "started_at": "Date and time the phishing security test started.",+ "duration": "Duration of the phishing security test in calendar days.",+ "scheduled_count": "Number of users scheduled to receive phishing emails.",+ "delivered_count": "Number of users who received phishing emails.",+ "opened_count": "Number of users who opened the email.",+ "clicked_count": "Number of users who clicked.",+ "replied_count": "Number of users who replied.",+ "attachment_open_count": "Number of users who opened an attachment.",+ "data_entered_count": "Number of users who entered data on a landing page.",+ "qr_code_scanned_count": "Number of users who scanned a QR code.",+ "reported_count": "Number of users who reported the email using the Phish Alert Button.",+ "bounced_count": "Number of users whose phishing email bounced.",+ },+ },+ "phishing_security_test_recipients": {+ "description": "Per-recipient results for a phishing security test, one row per user targeted by the test.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Phishing/paths/~1v1~1phishing~1security_tests~1%7Bpst_id%7D~1recipients/get",+ "columns": {+ "recipient_id": "Unique ID of the recipient (user) within the phishing security test.",+ "pst_id": "Unique ID of the phishing security test this result belongs to.",+ "user": "Recipient user details (id, name, email).",+ "template": "The phishing template the recipient received.",+ "scheduled_at": "Date and time the user was scheduled to receive the phishing security test.",+ "delivered_at": "Date and time the user received the phishing security test.",+ "opened_at": "Date and time the user opened the phishing security test.",+ "clicked_at": "Date and time the user clicked.",+ "replied_at": "Date and time the user replied.",+ "attachment_opened_at": "Date and time the user opened an attachment.",+ "data_entered_at": "Date and time the user entered data on a landing page.",+ "qr_code_scanned": "Date and time the user scanned a QR code.",+ "reported_at": "Date and time the user reported the email using the Phish Alert Button.",+ "bounced_at": "Date and time the phishing email designated for this user bounced.",+ "ip": "User's IP address.",+ "ip_location": "User's geolocation.",+ "browser": "User's browser.",+ "os": "User's operating system.",+ },+ },+ "training_campaigns": {+ "description": "Training campaigns configured in the account, including assigned content and completion status.",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Training/paths/~1v1~1training~1campaigns/get",+ "columns": {+ "campaign_id": "Campaign ID.",+ "name": "Campaign name.",+ "groups": "Array of groups targeted by the campaign.",+ "status": "Campaign status (Created, Enrolling, In Progress, Completed, Cancelled).",+ "content": "Array of Store Purchases and uploaded policies included in the campaign.",+ "duration_type": "Duration type (Specific End Date, Relative End Date, No End Date).",+ "start_date": "Start date/time.",+ "end_date": "End date/time.",+ "auto_enroll": "Whether users added to the targeted groups are automatically enrolled.",+ "completion_percentage": "Percentage of completed enrollments (-1 if too large to calculate).",+ },+ },+ "training_enrollments": {+ "description": "Individual user enrollments in training campaign content (modules or uploaded policies).",+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Training/paths/~1v1~1training~1enrollments/get",+ "columns": {+ "enrollment_id": "Enrollment ID.",+ "content_type": "Whether the enrollment is for a Store Purchase or an Uploaded Policy.",+ "module_name": "Name of the module or title of the uploaded policy.",+ "user": "Enrolled user's id, name, and email.",+ "campaign_name": "Name of the training campaign the enrollment belongs to.",+ "enrollment_date": "Enrollment date.",+ "start_date": "Assignment start date.",+ "completion_date": "Assignment completion date.",+ "status": "Completion status (Not Started, In Progress, Completed, Passed, Past Due).",+ "time_spent": "Time spent on the assignment, in seconds.",+ "policy_acknowledged": "Whether the course-attached URL policy was acknowledged, if applicable.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/knowbe4.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/knowbe4.pynew file mode 100644index 000000000000..5db7abe64c9c--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/knowbe4.py@@ -0,0 +1,153 @@+from collections.abc import Iterable+from typing import Any, cast++from requests.exceptions import RequestException++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+ EndpointResource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.settings import (+ KNOWBE4_ENDPOINTS,+ KNOWBE4_REGION_HOSTS,+ KnowBe4EndpointConfig,+)+++def build_base_url(region: str) -> str:+ """Resolve the region-scoped Reporting API host. Raises `ValueError` for an unknown region."""+ host = KNOWBE4_REGION_HOSTS.get(region.lower().strip())+ if host is None:+ raise ValueError(f"Unknown KnowBe4 region {region!r}. Must be one of {sorted(KNOWBE4_REGION_HOSTS)}.")+ return host+++def _client_config(base_url: str, api_key: str) -> ClientConfig:+ return {+ "base_url": base_url,+ "auth": {"type": "bearer", "token": api_key},+ "headers": {"Accept": "application/json"},+ }+++def _list_paginator() -> PageNumberPaginator:+ # KnowBe4 pages start at 1 and terminate on an empty array — no total-count field is+ # documented, so we can't stop a page early via `total_path`.+ return PageNumberPaginator(base_page=1, page_param="page", stop_after_empty_page=True)+++def get_resource(config: KnowBe4EndpointConfig) -> EndpointResource:+ endpoint_config: Endpoint = {+ "path": config.path,+ "params": {"per_page": config.page_size, **config.extra_params},+ "data_selector": config.data_selector,+ "paginator": _list_paginator(),+ }+ return {+ "name": config.name,+ "table_name": config.name,+ "write_disposition": "replace",+ "endpoint": endpoint_config,+ "table_format": "delta",+ }+++def _make_source_response(config: KnowBe4EndpointConfig, items_fn: Any) -> SourceResponse:+ primary_keys = config.primary_key if isinstance(config.primary_key, list) else [config.primary_key]+ return SourceResponse(+ name=config.name,+ items=items_fn,+ primary_keys=primary_keys,+ # Full refresh only — KnowBe4 exposes no server-side updated-since cursor on any+ # list endpoint, so pages are requested and consumed in their stable ascending order.+ sort_mode="asc",+ )+++def knowbe4_source(+ api_key: str,+ region: str,+ endpoint: str,+ team_id: int,+ job_id: str,+) -> SourceResponse:+ config = KNOWBE4_ENDPOINTS[endpoint]+ base_url = build_base_url(region)+ client_config = _client_config(base_url, api_key)++ if config.fanout is not None:+ dependent_resource = cast(+ Iterable[Any],+ build_dependent_resource(+ endpoint_configs=KNOWBE4_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ should_use_incremental_field=False,+ page_size_param="per_page",+ parent_endpoint_extra={+ "paginator": _list_paginator(),+ "data_selector": KNOWBE4_ENDPOINTS[config.fanout.parent_name].data_selector,+ },+ child_endpoint_extra={+ "paginator": _list_paginator(),+ "data_selector": config.data_selector,+ },+ child_params_extra=config.extra_params or None,+ ),+ )+ return _make_source_response(config, lambda: dependent_resource)++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {"write_disposition": "replace"},+ "resources": [get_resource(config)],+ }+ resource = rest_api_resource(rest_config, team_id, job_id, None)+ return _make_source_response(config, lambda: resource)+++def validate_credentials(api_key: str, region: str, schema_name: str | None = None) -> tuple[bool, str | None]:+ """Probe the token against `/v1/account` — the cheapest authenticated call, and one every+ KnowBe4 Reporting API token can reach regardless of subscription tier."""+ try:+ base_url = build_base_url(region)+ except ValueError as exc:+ return False, str(exc)++ try:+ response = make_tracked_session(redact_values=(api_key,)).get(+ f"{base_url}/v1/account",+ headers={"Authorization": f"Bearer {api_key}", "Accept": "application/json"},+ timeout=10,+ )+ except RequestException as exc:+ return False, f"Could not reach the KnowBe4 API: {exc}"++ if response.status_code == 401:+ return False, "Invalid KnowBe4 API key. Please check your key and try again."+ if response.status_code == 403:+ if schema_name is not None:+ return False, "Your KnowBe4 API key does not have permission to read this table."+ return True, None+ if response.status_code != 200:+ return False, f"KnowBe4 API returned an unexpected status ({response.status_code})."++ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.pynew file mode 100644index 000000000000..aefba1e9f798--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py@@ -0,0 +1,119 @@+from dataclasses import dataclass, field+from typing import Any++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField++# KnowBe4's Reporting API is regional: the account's console determines which host the+# account-scoped Bearer token is valid against.+KNOWBE4_REGION_HOSTS: dict[str, str] = {+ "us": "https://us.api.knowbe4.com",+ "eu": "https://eu.api.knowbe4.com",+ "ca": "https://ca.api.knowbe4.com",+ "uk": "https://uk.api.knowbe4.com",+ "de": "https://de.api.knowbe4.com",+}+DEFAULT_REGION = "us"++# Documented hard maximum for `per_page` across every list endpoint.+PAGE_SIZE = 500+++@dataclass+class KnowBe4EndpointConfig:+ name: str+ path: str+ primary_key: str | list[str]+ # jsonpath selector into the response body. Every KnowBe4 list endpoint returns a bare+ # JSON array (no `{"data": [...]}` wrapper), so "$" (the whole body) is used everywhere.+ data_selector: str = "$"+ fanout: DependentEndpointConfig | None = None+ # Static query params beyond page/per_page (e.g. flags that avoid a truncated response).+ extra_params: dict[str, Any] = field(default_factory=dict)+ # KnowBe4 has no documented updated-since filter on any list endpoint, so every stream is+ # full-refresh; these stay empty but satisfy the fan-out helper's endpoint protocol.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ default_incremental_field: str | None = None+ page_size: int = PAGE_SIZE+++KNOWBE4_ENDPOINTS: dict[str, KnowBe4EndpointConfig] = {+ "users": KnowBe4EndpointConfig(+ name="users",+ path="/v1/users",+ primary_key="id",+ ),+ "groups": KnowBe4EndpointConfig(+ name="groups",+ path="/v1/groups",+ primary_key="id",+ ),+ "group_members": KnowBe4EndpointConfig(+ name="group_members",+ path="/v1/groups/{group_id}/members",+ # A user can belong to multiple groups, and this stream aggregates every group's+ # members, so the parent group id is required to keep the key unique table-wide.+ primary_key=["group_id", "id"],+ fanout=DependentEndpointConfig(+ parent_name="groups",+ resolve_param="group_id",+ resolve_field="id",+ include_from_parent=["id"],+ # The parent's "id" field is renamed to "group_id" so it doesn't collide with the+ # member row's own "id" (the user's id).+ parent_field_renames={"id": "group_id"},+ ),+ ),+ "phishing_campaigns": KnowBe4EndpointConfig(+ name="phishing_campaigns",+ path="/v1/phishing/campaigns",+ primary_key="campaign_id",+ ),+ "phishing_security_tests": KnowBe4EndpointConfig(+ name="phishing_security_tests",+ path="/v1/phishing/security_tests",+ primary_key="pst_id",+ ),+ "phishing_security_test_recipients": KnowBe4EndpointConfig(+ name="phishing_security_test_recipients",+ path="/v1/phishing/security_tests/{pst_id}/recipients",+ # Each recipient row already carries its own `pst_id` field from the API, so no parent+ # field injection is needed — but the parent id still anchors the composite key, since+ # a recipient's id is only documented as unique within a single security test.+ primary_key=["pst_id", "recipient_id"],+ fanout=DependentEndpointConfig(+ parent_name="phishing_security_tests",+ resolve_param="pst_id",+ resolve_field="pst_id",+ include_from_parent=[],+ ),+ ),+ "training_campaigns": KnowBe4EndpointConfig(+ name="training_campaigns",+ path="/v1/training/campaigns",+ primary_key="campaign_id",+ # Without this, KnowBe4 caps the response at 10 campaigns (see the endpoint's+ # documented `exclude_percentages` behavior) — set unconditionally to get every campaign.+ extra_params={"exclude_percentages": "true"},+ ),+ "training_enrollments": KnowBe4EndpointConfig(+ name="training_enrollments",+ path="/v1/training/enrollments",+ primary_key="enrollment_id",+ # Enriches every enrollment row with its campaign/store-purchase/employee-number ids,+ # which otherwise aren't included by default.+ extra_params={+ "include_campaign_id": "true",+ "include_store_purchase_id": "true",+ "include_employee_number": "true",+ },+ ),+}++ENDPOINTS = tuple(KNOWBE4_ENDPOINTS)++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in KNOWBE4_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/source.pyindex ead25554d163..d675583d8a47 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/source.py@@ -1,32 +1,152 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+ SourceFieldSelectConfigOption,)+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, SimpleSource+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.schema import (+ SourceSchema,+ build_endpoint_schemas,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.knowbe4 import (Knowbe4SourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4 import (+ knowbe4_source,+ validate_credentials as validate_knowbe4_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.registerclass Knowbe4Source(SimpleSource[Knowbe4SourceConfig]):+ # `get_schemas` iterates a static endpoint catalog with no I/O, so the table list is safe to+ # render in public docs without credentials.+ lists_tables_without_credentials = True+ api_docs_url = "https://developer.knowbe4.com/rest/reporting"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.KNOWBE4+ @property+ def connection_host_fields(self) -> list[str]:+ # `region` selects which regional host the stored API key is sent to; retargeting it+ # must re-require the key (KnowBe4 keys are only valid against the region they were+ # generated in anyway).+ return ["region"]++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ message = (+ "Your KnowBe4 API key is invalid or expired. Generate a new key in Account Settings > API and reconnect."+ )+ return {+ "401 Client Error: Unauthorized": message,+ "Invalid KnowBe4 API key": message,+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: Knowbe4SourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)++ def validate_credentials(+ self,+ config: Knowbe4SourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_knowbe4_credentials(+ api_key=config.api_key,+ region=config.region,+ schema_name=schema_name,+ )++ def source_for_pipeline(self, config: Knowbe4SourceConfig, inputs: SourceInputs) -> SourceResponse:+ return knowbe4_source(+ api_key=config.api_key,+ region=config.region,+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ )+@propertydef get_source_config(self) -> SourceConfig:return SourceConfig(name=SchemaExternalDataSourceType.KNOWBE4,category=DataWarehouseSourceCategory.HR___RECRUITING,label="KnowBe4",+ keywords=["security awareness training", "phishing simulation"],+ caption=(+ "Enter your KnowBe4 Reporting API key to pull your security awareness training and "+ "phishing simulation data into the PostHog Data warehouse.\n\n"+ "Generate a key as an account admin under **Account Settings > API**. Reporting API "+ "keys are account-wide (no scopes to grant) but are only valid against the region "+ "your console runs on.\n\n"+ "Pick the **region** matching the URL you sign in to."+ ),+ docsUrl="https://posthog.com/docs/cdp/sources/knowbe4",iconPath="/static/services/knowbe4.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ releaseStatus=ReleaseStatus.ALPHA,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldSelectConfig(+ name="region",+ label="Region",+ required=True,+ defaultValue="us",+ options=[+ SourceFieldSelectConfigOption(label="US (us.api.knowbe4.com)", value="us"),+ SourceFieldSelectConfigOption(label="EU (eu.api.knowbe4.com)", value="eu"),+ SourceFieldSelectConfigOption(label="CA (ca.api.knowbe4.com)", value="ca"),+ SourceFieldSelectConfigOption(label="UK (uk.api.knowbe4.com)", value="uk"),+ SourceFieldSelectConfigOption(label="DE (de.api.knowbe4.com)", value="de"),+ ],+ ),+ ],+ ),)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4.pynew file mode 100644index 000000000000..a3adafa53a18--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4.py@@ -0,0 +1,177 @@+from typing import Any, cast++import pytest+from unittest.mock import Mock, patch++import requests+from parameterized import parameterized++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ PageNumberPaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4 import (+ build_base_url,+ get_resource,+ knowbe4_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.settings import KNOWBE4_ENDPOINTS+++class _FakeDltResource:+ def __init__(self, name: str, rows: list[dict]) -> None:+ self.name = name+ self._rows = rows++ def add_map(self, mapper):+ self._rows = [mapper(dict(row)) for row in self._rows]+ return self++ def __iter__(self):+ return iter(self._rows)+++class TestKnowBe4Transport:+ @parameterized.expand(+ [+ ("us", "us", "https://us.api.knowbe4.com"),+ ("eu", "eu", "https://eu.api.knowbe4.com"),+ ("ca", "ca", "https://ca.api.knowbe4.com"),+ ("uk", "uk", "https://uk.api.knowbe4.com"),+ ("de", "de", "https://de.api.knowbe4.com"),+ ("case_insensitive", "US", "https://us.api.knowbe4.com"),+ ("whitespace_trimmed", " us ", "https://us.api.knowbe4.com"),+ ]+ )+ def test_build_base_url(self, _name, region, expected) -> None:+ assert build_base_url(region) == expected++ def test_build_base_url_rejects_unknown_region(self) -> None:+ with pytest.raises(ValueError):+ build_base_url("apac")++ @parameterized.expand(+ [+ ("unauthorized", 401, None, False),+ ("forbidden_at_create", 403, None, True),+ ("forbidden_for_schema", 403, "users", False),+ ("ok", 200, None, True),+ ("unexpected", 500, None, False),+ ]+ )+ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4.make_tracked_session")+ def test_validate_credentials_status_mapping(+ self, _name, status_code, schema_name, expected_ok, mock_session+ ) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=status_code)++ is_valid, _message = validate_credentials(api_key="tok", region="us", schema_name=schema_name)++ assert is_valid is expected_ok++ def test_validate_credentials_rejects_bad_region_before_request(self) -> None:+ is_valid, message = validate_credentials(api_key="tok", region="apac")+ assert is_valid is False+ assert message is not None++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4.make_tracked_session")+ def test_validate_credentials_probes_account_with_bearer(self, mock_session) -> None:+ mock_session.return_value.get.return_value = Mock(status_code=200)++ validate_credentials(api_key="tok", region="us")++ call = mock_session.return_value.get.call_args+ assert call.args[0] == "https://us.api.knowbe4.com/v1/account"+ assert call.kwargs["headers"]["Authorization"] == "Bearer tok"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4.make_tracked_session")+ def test_validate_credentials_handles_request_exception(self, mock_session) -> None:+ mock_session.return_value.get.side_effect = requests.exceptions.RequestException("boom")+ is_valid, message = validate_credentials(api_key="tok", region="us")+ assert is_valid is False+ assert message is not None and "boom" in message++ def test_get_resource_users_bare_array_page_paginated(self) -> None:+ resource = cast(dict[str, Any], get_resource(KNOWBE4_ENDPOINTS["users"]))+ assert resource["name"] == "users"+ assert resource["write_disposition"] == "replace"+ assert resource["endpoint"]["path"] == "/v1/users"+ assert resource["endpoint"]["data_selector"] == "$"+ assert resource["endpoint"]["params"]["per_page"] == 500+ paginator = resource["endpoint"]["paginator"]+ assert isinstance(paginator, PageNumberPaginator)+ assert paginator.page == 1+ assert paginator.page_param == "page"++ def test_get_resource_training_campaigns_carries_exclude_percentages(self) -> None:+ # Without exclude_percentages=true, KnowBe4 caps the response at 10 campaigns.+ resource = cast(dict[str, Any], get_resource(KNOWBE4_ENDPOINTS["training_campaigns"]))+ assert resource["endpoint"]["params"]["exclude_percentages"] == "true"++ def test_get_resource_training_enrollments_requests_enrichment_flags(self) -> None:+ resource = cast(dict[str, Any], get_resource(KNOWBE4_ENDPOINTS["training_enrollments"]))+ params = resource["endpoint"]["params"]+ assert params["include_campaign_id"] == "true"+ assert params["include_store_purchase_id"] == "true"+ assert params["include_employee_number"] == "true"++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4.rest_api_resource")+ def test_knowbe4_source_users_top_level(self, mock_rest_api_resource) -> None:+ mock_rest_api_resource.return_value = Mock()+ response = knowbe4_source(api_key="tok", region="us", endpoint="users", team_id=1, job_id="job-1")++ assert response.name == "users"+ assert response.primary_keys == ["id"]+ assert response.sort_mode == "asc"++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_knowbe4_source_group_members_fanout_injects_and_renames_parent_id(self, mock_rest_api_resources) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("groups", [{"id": "grp_1"}]),+ _FakeDltResource("group_members", [{"id": "user_1", "email": "[email protected]", "_groups_id": "grp_1"}]),+ ]++ response = knowbe4_source(api_key="tok", region="us", endpoint="group_members", team_id=1, job_id="job-1")++ rows = list(cast(Any, response.items()))+ # The parent group id is injected and renamed to `group_id` to avoid colliding with the+ # member's own `id` field.+ assert rows == [{"id": "user_1", "email": "[email protected]", "group_id": "grp_1"}]+ # A user can belong to multiple groups, so the parent group id is required in the key.+ assert response.primary_keys == ["group_id", "id"]++ @patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_knowbe4_source_phishing_recipients_fanout_keeps_own_pst_id(self, mock_rest_api_resources) -> None:+ # Each recipient row already carries its own `pst_id` from the API, so no parent field+ # injection is configured for this fan-out.+ mock_rest_api_resources.return_value = [+ _FakeDltResource("phishing_security_tests", [{"pst_id": 1}]),+ _FakeDltResource("phishing_security_test_recipients", [{"recipient_id": 55, "pst_id": 1, "os": "MacOSX"}]),+ ]++ response = knowbe4_source(+ api_key="tok", region="us", endpoint="phishing_security_test_recipients", team_id=1, job_id="job-1"+ )++ rows = list(cast(Any, response.items()))+ assert rows == [{"recipient_id": 55, "pst_id": 1, "os": "MacOSX"}]+ # `recipient_id` is only documented unique within a single test, so the parent pst_id+ # anchors the composite key.+ assert response.primary_keys == ["pst_id", "recipient_id"]++ @patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4.build_dependent_resource")+ def test_knowbe4_source_fanout_uses_per_page_and_page_paginator(self, mock_build_dependent_resource) -> None:+ mock_build_dependent_resource.return_value = iter([])++ knowbe4_source(api_key="tok", region="us", endpoint="group_members", team_id=1, job_id="job-1")++ kwargs = mock_build_dependent_resource.call_args.kwargs+ assert kwargs["page_size_param"] == "per_page"+ assert isinstance(kwargs["parent_endpoint_extra"]["paginator"], PageNumberPaginator)+ assert isinstance(kwargs["child_endpoint_extra"]["paginator"], PageNumberPaginator)+ assert kwargs["parent_endpoint_extra"]["data_selector"] == "$"+ assert kwargs["child_endpoint_extra"]["data_selector"] == "$"diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4_source.pynew file mode 100644index 000000000000..09d1f89a12e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/tests/test_knowbe4_source.py@@ -0,0 +1,135 @@+import pytest+from unittest import mock++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+ SourceFieldSelectConfig,+)++from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.knowbe4 import (+ Knowbe4SourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.source import Knowbe4Source+from products.warehouse_sources.backend.types import ExternalDataSourceType+++class TestKnowBe4Source:+ def setup_method(self) -> None:+ self.source = Knowbe4Source()+ self.team_id = 123+ self.config = Knowbe4SourceConfig(api_key="tok", region="us")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.KNOWBE4++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config+ assert config.name.value == "Knowbe4"+ assert config.category == DataWarehouseSourceCategory.HR___RECRUITING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/knowbe4"++ def test_source_is_released_not_hidden(self) -> None:+ # A finished source must be visible: `unreleasedSource` hides it from every user.+ assert not self.source.get_source_config.unreleasedSource++ def test_source_config_fields(self) -> None:+ config = self.source.get_source_config+ input_fields = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]+ select_fields = [f.name for f in config.fields if isinstance(f, SourceFieldSelectConfig)]+ assert input_fields == ["api_key"]+ assert select_fields == ["region"]++ def test_api_key_field_is_secret_password(self) -> None:+ config = self.source.get_source_config+ field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.secret is True+ assert field.required is True++ def test_region_options(self) -> None:+ config = self.source.get_source_config+ region = next(f for f in config.fields if isinstance(f, SourceFieldSelectConfig) and f.name == "region")+ assert {o.value for o in region.options} == {"us", "eu", "ca", "uk", "de"}+ assert region.defaultValue == "us"++ def test_get_schemas_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_get_schemas_are_all_full_refresh(self) -> None:+ # KnowBe4 exposes no server-side updated-since cursor on any list endpoint, so no+ # stream is incremental.+ for schema in self.source.get_schemas(self.config, self.team_id):+ assert schema.supports_incremental is False+ assert schema.supports_append is False+ assert schema.incremental_fields == []++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["users"])+ assert [s.name for s in schemas] == ["users"]++ def test_lists_tables_without_credentials(self) -> None:+ # Static endpoint catalog with no I/O — powers the public docs table list.+ assert self.source.lists_tables_without_credentials is True++ def test_connection_host_fields_cover_token_destination(self) -> None:+ # Dropping `region` would let an editor retarget the stored API key at a different+ # regional host without re-entering it (the update serializer keys off this list).+ assert self.source.connection_host_fields == ["region"]++ def test_api_docs_url_is_https(self) -> None:+ assert self.source.api_docs_url is not None+ assert self.source.api_docs_url.startswith("https://")++ @pytest.mark.parametrize(+ "observed_error",+ [+ "401 Client Error: Unauthorized for url: https://us.api.knowbe4.com/v1/users",+ "Invalid KnowBe4 API key. Please check your key and try again.",+ ],+ )+ def test_non_retryable_errors_match_auth_failures(self, observed_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ def test_non_retryable_errors_ignore_transient(self) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in "503 Server Error for url: https://us.api.knowbe4.com/v1/users" for key in non_retryable)++ def test_canonical_descriptions_cover_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ assert set(descriptions.keys()) == set(ENDPOINTS)++ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.source.validate_knowbe4_credentials"+ )+ def test_validate_credentials_plumbs_arguments(self, mock_validate: mock.MagicMock) -> None:+ mock_validate.return_value = (True, None)+ result = self.source.validate_credentials(self.config, self.team_id, schema_name="users")++ assert result == (True, None)+ kwargs = mock_validate.call_args.kwargs+ assert kwargs["api_key"] == "tok"+ assert kwargs["region"] == "us"+ assert kwargs["schema_name"] == "users"++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.source.knowbe4_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_knowbe4_source: mock.MagicMock) -> None:+ inputs = mock.MagicMock()+ inputs.schema_name = "group_members"+ inputs.team_id = self.team_id+ inputs.job_id = "job-1"++ self.source.source_for_pipeline(self.config, inputs)++ kwargs = mock_knowbe4_source.call_args.kwargs+ assert kwargs["api_key"] == "tok"+ assert kwargs["region"] == "us"+ assert kwargs["endpoint"] == "group_members"+ assert kwargs["team_id"] == self.team_id+ assert kwargs["job_id"] == "job-1"