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(warehouse-sources): add knowbe4 account and risk score history tables (#113343)

Tom Owers395a8b1a5e9f
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index 9750ee18c007..d33605d369b9 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -731,7 +731,6 @@
1 products/warehouse_sources/backend/temporal/data_imports/sources/klaus/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/klaviyo/klaviyo.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/knock/knock.py
-1 products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kommo/kommo.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/kong_konnect.py
1 products/warehouse_sources/backend/temporal/data_imports/sources/kong_konnect/settings.py
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index f2d07c6ac32b..ec9922593b7a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -4820,10 +4820,10 @@ Today (8): `group_members`, `groups`, `phishing_campaigns`, `phishing_security_t
Diffed against: <https://developer.knowbe4.com/elvis-swagger.yml>
-- [ ] `/v1/users/{user_id}/risk_score_history` — per-user Risk Score over time — KnowBe4's headline metric, and the whole point of syncing users (high)
-- [ ] `/v1/account/risk_score_history` — org-level Risk Score trend, the top-line number every KnowBe4 report opens with (high)
-- [ ] `/v1/groups/{group_id}/risk_score_history` — Risk Score trend per group, the standard department-level breakdown (medium)
-- [ ] `/v1/account` — account-level summary (current risk score, subscription tier, seat counts) providing denominators for coverage metrics (medium)
+- [x] `/v1/users/{user_id}/risk_score_history` — per-user Risk Score over time — KnowBe4's headline metric, and the whole point of syncing users (high)
+- [x] `/v1/account/risk_score_history` — org-level Risk Score trend, the top-line number every KnowBe4 report opens with (high)
+- [x] `/v1/groups/{group_id}/risk_score_history` — Risk Score trend per group, the standard department-level breakdown (medium)
+- [x] `/v1/account` — account-level summary (current risk score, subscription tier, seat counts) providing denominators for coverage metrics (medium)
- [ ] `/v1/training/policies and /v1/training/policies/{policy_id}` — policy acknowledgement records — the compliance-attestation half of the training program, entirely absent today (medium)
- [ ] `/v1/phishing/campaigns/{campaign_id}/security_tests` — explicit campaign-to-test join; today the link must be inferred from phishing_security_tests (low)
- [ ] `/v1/training/store_purchases` — lookup resolving the ModStore content IDs referenced by training campaigns (low)
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.py
index 78f2932df67f..32ee1eec2c7d 100644
--- 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.py
@@ -153,4 +153,44 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"policy_acknowledged": "Whether the course-attached URL policy was acknowledged, if applicable.",
},
},
+ "account": {
+ "description": "The KnowBe4 account itself, one row: subscription level, seat count, admins, and current organization risk score.",
+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Account/paths/~1v1~1account/get",
+ "columns": {
+ "name": "Organization's name, or its domain if the name is unavailable.",
+ "type": "Whether the account is paid, trial, or free.",
+ "domains": "Array of the allowed domains on the account.",
+ "admins": "Array of the account's admins with their id, first name, last name, and email.",
+ "subscription_level": "The account's subscription level (paid subscriptions only).",
+ "subscription_end_date": "The account's subscription end date (paid subscriptions only).",
+ "number_of_seats": "Number of seats available on the account (paid subscriptions only).",
+ "current_risk_score": "Organization's current risk score.",
+ },
+ },
+ "account_risk_score_history": {
+ "description": "The organization's risk score over time, one row per recorded date.",
+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Account/paths/~1v1~1account~1risk_score_history/get",
+ "columns": {
+ "risk_score": "Organization risk score on this date.",
+ "date": "Date the risk score was recorded.",
+ },
+ },
+ "group_risk_score_history": {
+ "description": "Each group's risk score over time, one row per group per recorded date.",
+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Groups/paths/~1v1~1groups~1%7Bgroup_id%7D~1risk_score_history/get",
+ "columns": {
+ "group_id": "ID of the group the risk score belongs to.",
+ "risk_score": "Group risk score on this date.",
+ "date": "Date the risk score was recorded.",
+ },
+ },
+ "user_risk_score_history": {
+ "description": "Each user's risk score over time, one row per user per recorded date.",
+ "docs_url": "https://developer.knowbe4.com/rest/reporting#tag/Users/paths/~1v1~1users~1%7Buser_id%7D~1risk_score_history/get",
+ "columns": {
+ "user_id": "ID of the user the risk score belongs to.",
+ "risk_score": "User risk score on this date.",
+ "date": "Date the risk score was recorded.",
+ },
+ },
}
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.py
index 93178d27a934..692dc4e712ed 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/knowbe4.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/knowbe4.py
@@ -12,7 +12,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
build_dependent_resource,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
+ BasePaginator,
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (
ClientConfig,
@@ -49,12 +51,17 @@ def _list_paginator() -> PageNumberPaginator:
return PageNumberPaginator(base_page=1, page_param="page", stop_after_empty_page=True)
+def _paginator(config: KnowBe4EndpointConfig) -> BasePaginator:
+ return _list_paginator() if config.paginated else SinglePagePaginator()
+
+
def get_resource(config: KnowBe4EndpointConfig) -> EndpointResource:
+ page_params: dict[str, Any] = {"per_page": config.page_size} if config.paginated else {}
endpoint_config: Endpoint = {
"path": config.path,
- "params": {"per_page": config.page_size, **config.extra_params},
+ "params": {**page_params, **config.extra_params},
"data_selector": config.data_selector,
- "paginator": _list_paginator(),
+ "paginator": _paginator(config),
}
return {
"name": config.name,
@@ -101,13 +108,13 @@ def knowbe4_source(
job_id=job_id,
db_incremental_field_last_value=None,
should_use_incremental_field=False,
- page_size_param="per_page",
+ page_size_param="per_page" if config.paginated else None,
parent_endpoint_extra={
"paginator": _list_paginator(),
"data_selector": KNOWBE4_ENDPOINTS[config.fanout.parent_name].data_selector,
},
child_endpoint_extra={
- "paginator": _list_paginator(),
+ "paginator": _paginator(config),
"data_selector": config.data_selector,
},
child_params_extra=config.extra_params or None,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py
index aefba1e9f798..a1dd6f627599 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/knowbe4/settings.py
@@ -21,7 +21,7 @@ DEFAULT_REGION = "us"
PAGE_SIZE = 500
-@dataclass
+@dataclass(frozen=True)
class KnowBe4EndpointConfig:
name: str
path: str
@@ -37,6 +37,9 @@ class KnowBe4EndpointConfig:
incremental_fields: list[IncrementalField] = field(default_factory=list)
default_incremental_field: str | None = None
page_size: int = PAGE_SIZE
+ # False for endpoints that return one object or a capped, unpaginated array. Sending page
+ # params to those would repeat the same rows on every page and never reach an empty page.
+ paginated: bool = True
KNOWBE4_ENDPOINTS: dict[str, KnowBe4EndpointConfig] = {
@@ -110,6 +113,52 @@ KNOWBE4_ENDPOINTS: dict[str, KnowBe4EndpointConfig] = {
"include_employee_number": "true",
},
),
+ "account": KnowBe4EndpointConfig(
+ name="account",
+ path="/v1/account",
+ # A single object per token. The account has no id field, and `name` falls back to the
+ # account's domain when no organization name is set.
+ primary_key="name",
+ paginated=False,
+ ),
+ "account_risk_score_history": KnowBe4EndpointConfig(
+ name="account_risk_score_history",
+ path="/v1/account/risk_score_history",
+ primary_key="date",
+ # Without `full=true` only the last six months are returned.
+ extra_params={"full": "true"},
+ ),
+ "group_risk_score_history": KnowBe4EndpointConfig(
+ name="group_risk_score_history",
+ path="/v1/groups/{group_id}/risk_score_history",
+ primary_key=["group_id", "date"],
+ extra_params={"full": "true"},
+ fanout=DependentEndpointConfig(
+ parent_name="groups",
+ resolve_param="group_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "group_id"},
+ ),
+ ),
+ "user_risk_score_history": KnowBe4EndpointConfig(
+ name="user_risk_score_history",
+ path="/v1/users/{user_id}/risk_score_history",
+ primary_key=["user_id", "date"],
+ extra_params={"full": "true"},
+ # KnowBe4 documents this endpoint as excluded from pagination, returning up to 1000
+ # records in one response.
+ paginated=False,
+ fanout=DependentEndpointConfig(
+ parent_name="users",
+ resolve_param="user_id",
+ resolve_field="id",
+ include_from_parent=["id"],
+ parent_field_renames={"id": "user_id"},
+ # The child takes no page-size param, so the parent's one is passed here instead.
+ parent_params={"per_page": PAGE_SIZE},
+ ),
+ ),
}
ENDPOINTS = tuple(KNOWBE4_ENDPOINTS)
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.py
index a3adafa53a18..1195af4300c2 100644
--- 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.py
@@ -8,6 +8,7 @@ from parameterized import parameterized
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (
PageNumberPaginator,
+ SinglePagePaginator,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.knowbe4.knowbe4 import (
build_base_url,
@@ -103,6 +104,19 @@ class TestKnowBe4Transport:
assert paginator.page == 1
assert paginator.page_param == "page"
+ def test_get_resource_account_is_single_unpaginated_request(self) -> None:
+ # `/v1/account` returns one object; a page paginator would refetch it forever because
+ # the response never becomes an empty array.
+ resource = cast(dict[str, Any], get_resource(KNOWBE4_ENDPOINTS["account"]))
+ assert resource["endpoint"]["params"] == {}
+ assert isinstance(resource["endpoint"]["paginator"], SinglePagePaginator)
+
+ def test_get_resource_account_risk_score_history_requests_full_history(self) -> None:
+ # Without full=true KnowBe4 returns only the last six months.
+ resource = cast(dict[str, Any], get_resource(KNOWBE4_ENDPOINTS["account_risk_score_history"]))
+ assert resource["endpoint"]["params"] == {"per_page": 500, "full": "true"}
+ assert isinstance(resource["endpoint"]["paginator"], PageNumberPaginator)
+
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"]))
@@ -124,23 +138,50 @@ class TestKnowBe4Transport:
assert response.primary_keys == ["id"]
assert response.sort_mode == "asc"
+ @parameterized.expand(
+ [
+ (
+ "group_members",
+ "groups",
+ {"id": "user_1", "email": "[email protected]", "_groups_id": "grp_1"},
+ {"id": "user_1", "email": "[email protected]", "group_id": "grp_1"},
+ ["group_id", "id"],
+ ),
+ (
+ "group_risk_score_history",
+ "groups",
+ {"risk_score": 37.3, "date": "2021-02-07", "_groups_id": "grp_1"},
+ {"risk_score": 37.3, "date": "2021-02-07", "group_id": "grp_1"},
+ ["group_id", "date"],
+ ),
+ (
+ "user_risk_score_history",
+ "users",
+ {"risk_score": 37.3, "date": "2021-02-07", "_users_id": "user_1"},
+ {"risk_score": 37.3, "date": "2021-02-07", "user_id": "user_1"},
+ ["user_id", "date"],
+ ),
+ ]
+ )
@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:
+ def test_knowbe4_source_fanout_injects_and_renames_parent_id(
+ self, endpoint, parent_name, raw_child_row, expected_row, expected_primary_keys, mock_rest_api_resources
+ ) -> None:
+ parent_id = expected_row[expected_primary_keys[0]]
mock_rest_api_resources.return_value = [
- _FakeDltResource("groups", [{"id": "grp_1"}]),
- _FakeDltResource("group_members", [{"id": "user_1", "email": "[email protected]", "_groups_id": "grp_1"}]),
+ _FakeDltResource(parent_name, [{"id": parent_id}]),
+ _FakeDltResource(endpoint, [raw_child_row]),
]
- response = knowbe4_source(api_key="tok", region="us", endpoint="group_members", team_id=1, job_id="job-1")
+ response = knowbe4_source(api_key="tok", region="us", endpoint=endpoint, 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"]
+ # The parent id is renamed so it can't collide with a child `id`, and it anchors the key
+ # because the child rows from every parent land in one table.
+ assert rows == [expected_row]
+ assert response.primary_keys == expected_primary_keys
@patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
@@ -175,3 +216,37 @@ class TestKnowBe4Transport:
assert isinstance(kwargs["child_endpoint_extra"]["paginator"], PageNumberPaginator)
assert kwargs["parent_endpoint_extra"]["data_selector"] == "$"
assert kwargs["child_endpoint_extra"]["data_selector"] == "$"
+
+ @parameterized.expand(
+ [
+ ("group_members", 500, 500, PageNumberPaginator, {}),
+ ("group_risk_score_history", 500, 500, PageNumberPaginator, {"full": "true"}),
+ # Documented as unpaginated (up to 1000 records), so no per_page that could truncate it.
+ ("user_risk_score_history", 500, None, SinglePagePaginator, {"full": "true"}),
+ ]
+ )
+ @patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"
+ )
+ def test_knowbe4_source_fanout_request_shaping(
+ self,
+ endpoint,
+ expected_parent_per_page,
+ expected_child_per_page,
+ expected_child_paginator,
+ expected_child_extra_params,
+ mock_rest_api_resources,
+ ) -> None:
+ mock_rest_api_resources.side_effect = lambda config, *args, **kwargs: [
+ _FakeDltResource(resource["name"], []) for resource in config["resources"]
+ ]
+
+ knowbe4_source(api_key="tok", region="us", endpoint=endpoint, team_id=1, job_id="job-1")
+
+ parent, child = mock_rest_api_resources.call_args.args[0]["resources"]
+ assert parent["endpoint"]["params"]["per_page"] == expected_parent_per_page
+ assert isinstance(parent["endpoint"]["paginator"], PageNumberPaginator)
+ assert child["endpoint"]["params"].get("per_page") == expected_child_per_page
+ assert isinstance(child["endpoint"]["paginator"], expected_child_paginator)
+ for key, value in expected_child_extra_params.items():
+ assert child["endpoint"]["params"][key] == value