Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): add 4 missing tables to the Grafana source (#120098)

Tom Owers6341328391f5
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 c3aad6fcbe5f..cc5dbb9f8d26 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
@@ -5524,10 +5524,10 @@ Diffed against: <https://raw.githubusercontent.com/grafana/grafana/main/public/o
- [x] `org/users (and orgs/{org_id}/users)` — org membership plus role, the other half of the identity model we already sync (high) — already synced as `users` (`/api/org/users`); `orgs/{org_id}/users` only repeats it per org for server admins
- [x] `orgs` — lookup resolving the org_id carried on dashboards, users, teams and datasources (high)
- [x] `dashboards/uid/{uid}/versions` — dashboard change history - who changed what and when, the main governance question (medium)
-- [ ] `library-elements` — reusable panels referenced by dashboards; needed to resolve panel definitions that are not inline (medium)
+- [x] `library-elements` — reusable panels referenced by dashboards; needed to resolve panel definitions that are not inline (medium)
- [ ] `query-history` — records of explored queries, the usage-analytics table for Explore adoption (medium)
-- [ ] `access-control/roles and access-control/{resource}/{resourceID}` — RBAC role definitions and resource permissions, resolving who can see which dashboards/folders (medium)
-- [ ] `folders/{folder_uid}/permissions and dashboards/uid/{uid}/permissions` — per-object permission grants for access auditing (low)
+- [x] `access-control/roles and access-control/{resource}/{resourceID}` — RBAC role definitions and resource permissions, resolving who can see which dashboards/folders (medium) — synced as `roles`, plus `dashboard_permissions` and `folder_permissions` for the dashboards and folders resources
+- [x] `folders/{folder_uid}/permissions and dashboards/uid/{uid}/permissions` — per-object permission grants for access auditing (low) — both are deprecated; synced as `dashboard_permissions` and `folder_permissions` from their `access-control/{resource}/{resourceID}` replacement
- [ ] `annotations/tags` — lookup of annotation tags for grouping the annotations we already sync (low)
- [ ] `playlists and playlists/{uid}/items` — playlist definitions and the dashboards inside them (low)
- [ ] `datasources/correlations` — correlation definitions linking datasources, useful for lineage (low)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py
index db2e4c4c2b83..7812981a62a4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/canonical_descriptions.py
@@ -173,4 +173,83 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"data": "Additional structured data attached to the annotation.",
},
},
+ "library_elements": {
+ "description": "Library panels: reusable panels that dashboards reference instead of defining inline.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/library_element/",
+ "columns": {
+ "id": "Internal numeric identifier of the library element.",
+ "uid": "Unique identifier of the library element.",
+ "orgId": "ID of the organization the library element belongs to.",
+ "folderUid": "Unique identifier of the folder that contains the library element.",
+ "name": "Name of the library element.",
+ "kind": "Kind of library element (1 = library panel).",
+ "type": "Panel type of the library element, for example timeseries or stat.",
+ "description": "Description of the library element.",
+ "model": "Full panel JSON model of the library element.",
+ "version": "Version number of the library element.",
+ "meta": "Folder, connected dashboard count, and created and updated timestamps and users.",
+ },
+ },
+ "dashboard_permissions": {
+ "description": "Access grants on each dashboard (one row per grant per dashboard), including grants inherited from folders.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/access_control/",
+ "columns": {
+ "dashboardUid": "Unique identifier of the dashboard the grant applies to.",
+ "subject": "Who holds the grant: user:<userId>, team:<teamId>, or role:<basic role>. Derived by PostHog from the grant's user, team, or role.",
+ "id": "Internal identifier of the permission. Grafana returns 0 when it serves permissions from unified storage.",
+ "roleName": "Name of the managed role that carries the grant.",
+ "isManaged": "Whether the grant is managed through the permissions UI or API.",
+ "isInherited": "Whether the grant is inherited from a parent folder.",
+ "isServiceAccount": "Whether the grantee user is a service account.",
+ "userId": "Internal numeric identifier of the user that holds the grant.",
+ "userUid": "Unique identifier of the user that holds the grant.",
+ "userLogin": "Login handle of the user that holds the grant.",
+ "teamId": "Internal numeric identifier of the team that holds the grant.",
+ "teamUid": "Unique identifier of the team that holds the grant.",
+ "team": "Name of the team that holds the grant.",
+ "builtInRole": "Basic role that holds the grant (Viewer, Editor, or Admin).",
+ "actions": "Actions the grant allows.",
+ "permission": "Permission level of the grant (View, Edit, or Admin).",
+ },
+ },
+ "folder_permissions": {
+ "description": "Access grants on each folder (one row per grant per folder).",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/access_control/",
+ "columns": {
+ "folderUid": "Unique identifier of the folder the grant applies to.",
+ "subject": "Who holds the grant: user:<userId>, team:<teamId>, or role:<basic role>. Derived by PostHog from the grant's user, team, or role.",
+ "id": "Internal identifier of the permission. Grafana returns 0 when it serves permissions from unified storage.",
+ "roleName": "Name of the managed role that carries the grant.",
+ "isManaged": "Whether the grant is managed through the permissions UI or API.",
+ "isInherited": "Whether the grant is inherited from a parent folder.",
+ "isServiceAccount": "Whether the grantee user is a service account.",
+ "userId": "Internal numeric identifier of the user that holds the grant.",
+ "userUid": "Unique identifier of the user that holds the grant.",
+ "userLogin": "Login handle of the user that holds the grant.",
+ "teamId": "Internal numeric identifier of the team that holds the grant.",
+ "teamUid": "Unique identifier of the team that holds the grant.",
+ "team": "Name of the team that holds the grant.",
+ "builtInRole": "Basic role that holds the grant (Viewer, Editor, or Admin).",
+ "actions": "Actions the grant allows.",
+ "permission": "Permission level of the grant (View, Edit, or Admin).",
+ },
+ },
+ "roles": {
+ "description": "Role-based access control roles in the organization, with the permissions each role grants. Grafana Enterprise and Grafana Cloud only.",
+ "docs_url": "https://grafana.com/docs/grafana/latest/developers/http_api/access_control/",
+ "columns": {
+ "uid": "Unique identifier of the role.",
+ "name": "Name of the role, for example fixed:dashboards:reader or a custom role name.",
+ "displayName": "Display name of the role.",
+ "description": "Description of the role.",
+ "group": "Group the role is listed under in the UI.",
+ "version": "Version number of the role.",
+ "global": "Whether the role is available in every organization.",
+ "hidden": "Whether the role is hidden from the role picker.",
+ "delegatable": "Whether the authenticated identity can assign the role.",
+ "permissions": "Actions and scopes the role grants.",
+ "created": "Timestamp when the role was created.",
+ "updated": "Timestamp when the role was last updated.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
index b37b4cb365ab..8e94f0b7473b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/grafana.py
@@ -22,7 +22,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import (
ANNOTATIONS_LIMIT,
DASHBOARD_VERSIONS_PAGE_SIZE,
- DEFAULT_PAGE_SIZE,
GRAFANA_ENDPOINTS,
GrafanaEndpointConfig,
)
@@ -276,17 +275,44 @@ def _extract_items(data: Any, data_key: str | None) -> list[dict[str, Any]]:
Most list endpoints return a bare JSON array; the search-style endpoints
(``/api/teams/search``, ``/api/serviceaccounts/search``) wrap it, e.g.
- ``{"teams": [...], "totalCount": N}``.
+ ``{"teams": [...], "totalCount": N}``, and ``/api/library-elements`` nests it one level deeper
+ (``{"result": {"elements": [...]}}``, addressed as ``result.elements``).
"""
if data_key is not None:
- if isinstance(data, dict) and isinstance(data.get(data_key), list):
- return [item for item in data[data_key] if isinstance(item, dict)]
+ for key in data_key.split("."):
+ data = data.get(key) if isinstance(data, dict) else None
+ if isinstance(data, list):
+ return [item for item in data if isinstance(item, dict)]
return []
if isinstance(data, list):
return [item for item in data if isinstance(item, dict)]
return []
+def _permission_subject(row: dict[str, Any]) -> str:
+ if row.get("userId"):
+ return f"user:{row['userId']}"
+ if row.get("teamId"):
+ return f"team:{row['teamId']}"
+ if row.get("builtInRole"):
+ return f"role:{row['builtInRole']}"
+ return f"role:{row.get('roleName') or 'unknown'}"
+
+
+def _shape_resource_permissions(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ """Add the `subject` key column and drop rows that repeat a key within one resource.
+
+ A subject can repeat when Grafana appends its implicit Admin grant next to a managed one, or
+ when the same grant is inherited from more than one ancestor folder.
+ """
+ shaped: dict[tuple[str, bool, Any], dict[str, Any]] = {}
+ for row in rows:
+ subject = _permission_subject(row)
+ key = (subject, bool(row.get("isInherited")), row.get("permission"))
+ shaped.setdefault(key, {**row, "subject": subject, "isInherited": key[1]})
+ return list(shaped.values())
+
+
def _permission_error_from_response(response: requests.Response) -> str:
"""Build a short scope message from a Grafana 403 body.
@@ -458,7 +484,11 @@ def _probe_params(config: GrafanaEndpointConfig) -> dict[str, Any]:
def _probe(
- session: requests.Session, url: str, headers: dict[str, str], read_body: bool = False
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ read_body: bool = False,
+ not_found_reason: str | None = None,
) -> tuple[str | None, Any]:
"""Return (reason the credentials can't reach `url`, parsed body when requested and reachable)."""
# stream=True so a hostile host can't buffer an unbounded probe body; bodies are only read
@@ -468,6 +498,8 @@ def _probe(
return "Your Grafana credentials are invalid or expired.", None
if response.status_code == 403:
return _permission_error_from_response(response), None
+ if response.status_code == 404 and not_found_reason is not None:
+ return not_found_reason, None
if read_body and response.status_code == 200:
try:
return None, _read_json_bounded(response)
@@ -499,7 +531,10 @@ def get_endpoint_permissions(
try:
if config.fan_out is None:
results[endpoint], _ = _probe(
- session, f"{base_url}{config.path}?{urlencode(_probe_params(config))}", headers
+ session,
+ f"{base_url}{config.path}?{urlencode(_probe_params(config))}",
+ headers,
+ not_found_reason=config.not_found_reason,
)
continue
# A child needs its own permission (e.g. `dashboards:write` for versions), so probe it
@@ -539,14 +574,14 @@ def _get_paged_rows(
pages_this_run = 0
deadline = time.monotonic() + MAX_WALK_SECONDS
while True:
- params = {**config.params, config.page_size_param: DEFAULT_PAGE_SIZE, "page": page}
+ params = {**config.params, config.page_size_param: config.page_size, "page": page}
data = fetch(f"{base_url}{config.path}?{urlencode(params)}")
items = _extract_items(data, config.data_key)
if items:
yield items
- if len(items) < DEFAULT_PAGE_SIZE:
+ if len(items) < config.page_size:
break
page += 1
@@ -677,6 +712,8 @@ def _get_child_rows(
if config.pagination != "continue_token":
items = _extract_items(data, config.data_key)
+ if config.resource_permissions:
+ items = _shape_resource_permissions(items)
has_more = False
elif isinstance(data, list):
# Grafana releases before unified storage return a bare array and page by `start` offset.
@@ -716,7 +753,7 @@ def _get_fan_out_rows(
# after each parent lets the next sync continue from there.
budget = _WalkBudget(max_requests=MAX_PAGES_PER_RUN, deadline=time.monotonic() + MAX_WALK_SECONDS)
while not budget.exhausted:
- params = {**parent.params, parent.page_size_param: DEFAULT_PAGE_SIZE, "page": page}
+ params = {**parent.params, parent.page_size_param: parent.page_size, "page": page}
budget.spend()
parents = _extract_items(fetch(f"{base_url}{parent.path}?{urlencode(params)}"), parent.data_key)
@@ -736,7 +773,7 @@ def _get_fan_out_rows(
resumable_source_manager.safe_point()
if cut_short:
break
- if len(parents) < DEFAULT_PAGE_SIZE:
+ if len(parents) < parent.page_size:
return
page += 1
start_index = 0
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
index 3acdcfc53b0e..d3499b1d7a36 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/settings.py
@@ -16,6 +16,10 @@ ANNOTATIONS_LIMIT = 1000
# response well under MAX_RESPONSE_BYTES even for large dashboards.
DASHBOARD_VERSIONS_PAGE_SIZE = 50
+# Each library element carries its full panel JSON in `model`, so pages stay at Grafana's default
+# `perPage` to keep a response well under MAX_RESPONSE_BYTES.
+LIBRARY_ELEMENTS_PAGE_SIZE = 100
+
PaginationStyle = Literal["page", "time_window", "continue_token", "none"]
@@ -39,15 +43,20 @@ class GrafanaEndpointConfig:
# "none": one request returns the whole collection.
pagination: PaginationStyle = "none"
page_size_param: str = "limit"
+ page_size: int = DEFAULT_PAGE_SIZE
# Number of the first page for "page" pagination; `/api/orgs` counts pages from 0.
first_page: int = 1
# Key holding the rows when the response is wrapped (e.g. {"teams": [...], "totalCount": N});
- # None when the endpoint returns a bare JSON array.
+ # dotted for nested wrappers ("result.elements"). None when the endpoint returns a bare JSON array.
data_key: str | None = None
params: dict[str, str] = field(default_factory=dict)
primary_keys: list[str] = field(default_factory=lambda: ["id"])
incremental_fields: list[IncrementalField] = field(default_factory=list)
fan_out: GrafanaFanOutConfig | None = None
+ # Rows are access-control resource permissions, keyed by the derived `subject` column.
+ resource_permissions: bool = False
+ # Reason reported by the table picker when the endpoint returns 404, e.g. an Enterprise-only API.
+ not_found_reason: str | None = None
GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
@@ -87,6 +96,40 @@ GRAFANA_ENDPOINTS: dict[str, GrafanaEndpointConfig] = {
fan_out=GrafanaFanOutConfig(parent="teams", parent_field="id", child_field="teamId"),
primary_keys=["teamId", "userId"],
),
+ "library_elements": GrafanaEndpointConfig(
+ name="library_elements",
+ path="/api/library-elements",
+ pagination="page",
+ page_size_param="perPage",
+ page_size=LIBRARY_ELEMENTS_PAGE_SIZE,
+ data_key="result.elements",
+ primary_keys=["uid"],
+ ),
+ # Grafana's per-dashboard and per-folder permission endpoints are deprecated in favor of the
+ # access-control resource permission API. Its `id` is 0 when Grafana serves permissions from
+ # unified storage, and `userId` / `teamId` / `builtInRole` are omitted when empty, so rows are
+ # keyed by a derived `subject` instead.
+ "dashboard_permissions": GrafanaEndpointConfig(
+ name="dashboard_permissions",
+ path="/api/access-control/dashboards/{parent_id}",
+ fan_out=GrafanaFanOutConfig(parent="dashboards", parent_field="uid", child_field="dashboardUid"),
+ resource_permissions=True,
+ primary_keys=["dashboardUid", "subject", "isInherited", "permission"],
+ ),
+ "folder_permissions": GrafanaEndpointConfig(
+ name="folder_permissions",
+ path="/api/access-control/folders/{parent_id}",
+ fan_out=GrafanaFanOutConfig(parent="folders", parent_field="uid", child_field="folderUid"),
+ resource_permissions=True,
+ primary_keys=["folderUid", "subject", "isInherited", "permission"],
+ ),
+ # Role-based access control is a Grafana Enterprise and Grafana Cloud feature; OSS returns 404.
+ "roles": GrafanaEndpointConfig(
+ name="roles",
+ path="/api/access-control/roles",
+ primary_keys=["uid"],
+ not_found_reason="Roles are only available on Grafana Enterprise and Grafana Cloud.",
+ ),
"users": GrafanaEndpointConfig(
name="users",
path="/api/org/users",
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
index cd15ce2aa2d4..e5ff48396883 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/source.py
@@ -59,7 +59,7 @@ class GrafanaSource(ResumableSource[GrafanaSourceConfig, GrafanaResumeConfig]):
releaseStatus=ReleaseStatus.ALPHA,
caption="""Enter your Grafana instance URL and credentials to pull your Grafana metadata (dashboards, folders, alert rules, annotations, and more) into the PostHog Data warehouse.
-Create a service account token under **Administration > Users and access > Service accounts** in your Grafana instance. A Viewer role covers most tables; users, teams, team members, data sources, service accounts, and alert rules need extra read permissions (`users:read`, `teams:read`, `teams.permissions:read`, `datasources:read`, `serviceaccounts:read`, `alert.provisioning:read`). Grafana only shows dashboard versions to accounts that can edit the dashboard (`dashboards:write`), such as the Editor role.
+Create a service account token under **Administration > Users and access > Service accounts** in your Grafana instance. A Viewer role covers most tables; users, teams, team members, data sources, service accounts, alert rules, dashboard permissions, and folder permissions need extra read permissions (`users:read`, `teams:read`, `teams.permissions:read`, `datasources:read`, `serviceaccounts:read`, `alert.provisioning:read`, `dashboards.permissions:read`, `folders.permissions:read`). Grafana only shows dashboard versions to accounts that can edit the dashboard (`dashboards:write`), such as the Editor role. The roles table needs `roles:read` and is only available on Grafana Enterprise and Grafana Cloud.
Self-hosted Grafana OSS can alternatively authenticate with a username and password. Grafana Cloud only supports service account tokens. The organizations table lists every organization on the instance, so it needs a Grafana server admin username and password.""",
iconPath="/static/services/grafana.png",
@@ -186,6 +186,14 @@ Self-hosted Grafana OSS can alternatively authenticate with a username and passw
return "Dashboard metadata from the search API; does not include panel definitions"
if endpoint == "dashboard_versions":
return "Saved versions of every dashboard. Needs permission to edit dashboards"
+ if endpoint in ("dashboard_permissions", "folder_permissions"):
+ return (
+ "Users, teams, and basic roles granted access, one row per grant. `subject` identifies who holds it"
+ )
+ if endpoint == "roles":
+ return (
+ "Access control roles and their permissions. Only available on Grafana Enterprise and Grafana Cloud"
+ )
if endpoint == "orgs":
return "Every organization on the instance. Needs a Grafana server admin username and password"
return None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py
index f47424279875..71394d974a88 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/grafana/tests/test_grafana.py
@@ -20,7 +20,6 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.gr
ANNOTATIONS_LIMIT,
BASIC_AUTH,
DASHBOARD_VERSIONS_PAGE_SIZE,
- DEFAULT_PAGE_SIZE,
MAX_RESPONSE_BYTES,
TOKEN_AUTH,
GrafanaAuth,
@@ -35,6 +34,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.gr
normalize_host,
validate_credentials,
)
+from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.settings import (
+ DEFAULT_PAGE_SIZE,
+ LIBRARY_ELEMENTS_PAGE_SIZE,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.grafana.source import GrafanaSource
@@ -145,6 +148,9 @@ class TestExtractItems:
(None, None, []),
("nonsense", None, []),
({"teams": "nonsense"}, "teams", []),
+ ({"result": {"elements": [{"uid": "p1"}], "totalCount": 1}}, "result.elements", [{"uid": "p1"}]),
+ ({"result": None}, "result.elements", []),
+ ({"result": [{"uid": "p1"}]}, "result.elements", []),
],
)
def test_extract_items(self, data, data_key, expected):
@@ -287,6 +293,20 @@ class TestGetEndpointPermissions:
assert results["dashboard_versions"] is not None and "dashboards:write" in results["dashboard_versions"]
assert all("{" not in request.path for request in network.requests_log)
+ @pytest.mark.parametrize(
+ "endpoint, path, expected_reason",
+ [
+ # An Enterprise-only API is missing on OSS, so the table picker says why it can't sync.
+ ("roles", "/api/access-control/roles", "Roles are only available on Grafana Enterprise and Grafana Cloud."),
+ # Other tables keep treating a 404 as reachable rather than as a missing scope.
+ ("alert_rules", "/api/v1/provisioning/alert-rules", None),
+ ],
+ )
+ def test_not_found_reason(self, endpoint, path, expected_reason):
+ with scripted_network(route({path: [ScriptedResponse(status=404, body=b"not found")]})):
+ results = get_endpoint_permissions("https://x.grafana.net", _token_auth(), None, 1, [endpoint])
+ assert results == {endpoint: expected_reason}
+
def test_network_blip_is_not_a_missing_scope(self):
with scripted_network(always(ConnectionResetError("boom"))) as network:
results = get_endpoint_permissions("https://x.grafana.net", _token_auth(), None, 1, ["dashboards"])
@@ -303,6 +323,20 @@ class TestPagedRows:
assert result.params("page") == ["3"]
assert result.rows == [{"uid": "d1"}]
+ def test_library_elements_walk_nested_pages_at_their_own_page_size(self):
+ full_page = [{"uid": f"p{i}"} for i in range(LIBRARY_ELEMENTS_PAGE_SIZE)]
+ result = _driver().run(
+ "library_elements",
+ [
+ ScriptedResponse(json={"result": {"elements": full_page, "page": 1}}),
+ ScriptedResponse(json={"result": {"elements": [{"uid": "last"}], "page": 2}}),
+ ],
+ )
+ assert result.raised is None
+ assert result.params("page") == ["1", "2"]
+ assert result.params("perPage") == [str(LIBRARY_ELEMENTS_PAGE_SIZE)] * 2
+ assert len(result.rows) == LIBRARY_ELEMENTS_PAGE_SIZE + 1
+
def test_unpaginated_endpoint_single_request(self):
result = _driver().run("datasources", [ScriptedResponse(json=[{"uid": "ds1"}, {"uid": "ds2"}])])
assert result.raised is None
@@ -357,6 +391,41 @@ class TestFanOutRows:
assert result.raised is None
assert result.items == [[{"uid": "d2", "version": 1}]]
+ @pytest.mark.parametrize(
+ "endpoint, parent_path, child_path, parent_key",
+ [
+ ("dashboard_permissions", "/api/search", "/api/access-control/dashboards/r1", "dashboardUid"),
+ ("folder_permissions", "/api/folders", "/api/access-control/folders/r1", "folderUid"),
+ ],
+ )
+ def test_resource_permissions_keyed_by_subject(self, endpoint, parent_path, child_path, parent_key):
+ grants = [
+ {"id": 0, "userId": 7, "userLogin": "jo", "isInherited": False, "permission": "Edit"},
+ {"id": 0, "userId": 7, "userLogin": "jo", "isInherited": True, "permission": "Edit"},
+ {"id": 0, "teamId": 3, "team": "ops", "isInherited": True, "permission": "View"},
+ {"id": 12, "builtInRole": "Admin", "isInherited": False, "permission": "Admin"},
+ # Grafana appends an implicit Admin grant when access control enforcement is off.
+ {"builtInRole": "Admin", "isInherited": False, "permission": "Admin"},
+ {"id": 0, "roleName": "managed:custom", "permission": "View"},
+ ]
+ result = _driver().run(
+ endpoint,
+ route(
+ {
+ parent_path: [ScriptedResponse(json=[{"uid": "r1"}])],
+ child_path: [ScriptedResponse(json=grants)],
+ }
+ ),
+ )
+ assert result.raised is None
+ assert [(row[parent_key], row["subject"], row["isInherited"], row["permission"]) for row in result.rows] == [
+ ("r1", "user:7", False, "Edit"),
+ ("r1", "user:7", True, "Edit"),
+ ("r1", "team:3", True, "View"),
+ ("r1", "role:Admin", False, "Admin"),
+ ("r1", "role:managed:custom", False, "View"),
+ ]
+
def test_resumes_from_saved_parent_index(self):
result = _driver().run(
"team_members",