You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by wu...@apache.org on 2026/09/28 12:43:33 UTC
(skywalking-horizon-ui) branch main updated: feat(rbac): limit a verb to layers and service groups, and close the Platform monitoring layers to roles without cluster:read (#178)
This is an automated email from the ASF dual-hosted git repository.
wu-sheng pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/skywalking-horizon-ui.git
The following commit(s) were added to refs/heads/main by this push:
new 1286ff8b feat(rbac): limit a verb to layers and service groups, and close the Platform monitoring layers to roles without cluster:read (#178)
1286ff8b is described below
commit 1286ff8bb2e769a338095553ecf790319566c72e
Author: 吴晟 Wu Sheng <wu...@foxmail.com>
AuthorDate: Mon Sep 28 20:43:27 2026 +0800
feat(rbac): limit a verb to layers and service groups, and close the Platform monitoring layers to roles without cluster:read (#178)
A permission can name the layer it applies to and, optionally, the OAP
service groups in it: `metrics:read@GENERAL[payments]`. A role built from
such grants sees only the layers and group entries its grants reach, and
every request the BFF answers is checked against the services it reads:
pages, typed URLs, API calls, and the reads the AI assistant and MCP tools
make for the role. Reads across every service keep only the rows of
services the role may read. A permission without `@` means what it always
has, and the built-in roles are unchanged.
The Platform monitoring layers were listed only for `cluster:read` but the
server never enforced it; they are now refused to a role without it, by
page, by URL, through another layer's API path, in the landing columns,
in the 3D map and through the AI assistant, unless granted by layer.
Also: draft previews need `layer-template:write`; layer-wide totals run
only declared expressions; an MQE with no service needs `inspect:read`;
service names are resolved as OAP files them (`_blank`, both ids, exact
spelling) and `baseline` reads need every namesake readable; an OAP that
cannot say who owns a service answers 503. A stored layer template that
spells its entity terms as `aliases` no longer opens to a blank page.
A local demo environment with services in two groups of one layer lives
under .claude/skills/local-boot/rbac-demo.
---
.claude/skills/local-boot/SKILL.md | 26 ++
.../skills/local-boot/rbac-demo/docker-compose.yml | 133 ++++++++
.claude/skills/local-boot/rbac-demo/down.sh | 23 ++
.../rbac-demo/otel-collector-config.yaml | 44 +++
.claude/skills/local-boot/rbac-demo/roles.json | 1 +
.claude/skills/local-boot/rbac-demo/up.sh | 85 +++++
.claude/skills/local-boot/rbac-demo/users.json | 1 +
.gitignore | 1 +
apps/bff/CLAUDE.md | 37 ++-
apps/bff/src/ai/chat-assistant/route.ts | 4 +
apps/bff/src/ai/lib/tool-context.ts | 6 +
apps/bff/src/ai/lib/tools/access.ts | 116 +++++++
apps/bff/src/ai/lib/tools/context/tools.test.ts | 24 ++
apps/bff/src/ai/lib/tools/context/tools.ts | 16 +-
apps/bff/src/ai/lib/tools/kubernetes/tools.ts | 13 +-
apps/bff/src/ai/lib/tools/metric-catalog/tools.ts | 21 +-
apps/bff/src/ai/lib/tools/telemetry/tools.ts | 7 +-
apps/bff/src/ai/lib/tools/triggers/tools.test.ts | 46 +++
apps/bff/src/ai/lib/tools/triggers/tools.ts | 32 +-
.../src/ai/lib/tools/visualization/tools.test.ts | 117 +++++++
apps/bff/src/ai/lib/tools/visualization/tools.ts | 119 ++++---
apps/bff/src/ai/mcp/capture.ts | 5 +
apps/bff/src/ai/mcp/route.ts | 3 +
apps/bff/src/ai/mcp/tools.ts | 3 +
apps/bff/src/http/query/alarms-baseline.test.ts | 125 ++++++++
apps/bff/src/http/query/alarms.ts | 35 +-
apps/bff/src/http/query/browser-errors.ts | 9 +
apps/bff/src/http/query/continuous-profiling.ts | 6 +-
apps/bff/src/http/query/dashboard.ts | 31 +-
apps/bff/src/http/query/deployment.ts | 2 +-
apps/bff/src/http/query/ebpf.ts | 24 +-
apps/bff/src/http/query/endpoint-dependency.ts | 2 +-
apps/bff/src/http/query/evaluation-record.ts | 22 +-
apps/bff/src/http/query/events.ts | 18 +-
apps/bff/src/http/query/infra-3d-metrics.ts | 3 +-
apps/bff/src/http/query/instance-topology.ts | 2 +-
apps/bff/src/http/query/landing.ts | 49 ++-
apps/bff/src/http/query/log.ts | 16 +-
.../src/http/query/map-service-identity.test.ts | 6 +-
apps/bff/src/http/query/menu-access.test.ts | 193 +++++++++++
apps/bff/src/http/query/menu.ts | 54 +++-
apps/bff/src/http/query/mqe-exec-access.test.ts | 76 +++++
apps/bff/src/http/query/mqe-exec.ts | 10 +
apps/bff/src/http/query/services.ts | 5 +-
apps/bff/src/http/query/topology.ts | 11 +-
apps/bff/src/http/query/trace.ts | 3 +-
apps/bff/src/http/user.ts | 3 +
apps/bff/src/logic/dashboard/mqe.ts | 7 +-
apps/bff/src/logic/layers/operate-layers.test.ts | 69 ++++
apps/bff/src/logic/layers/operate-layers.ts | 95 ++++++
apps/bff/src/logic/layers/preview-traces.test.ts | 5 +
apps/bff/src/logic/layers/preview.ts | 3 +-
apps/bff/src/logic/oap/deployment.test.ts | 78 +++++
apps/bff/src/logic/oap/deployment.ts | 43 ++-
apps/bff/src/logic/oap/endpoint-dependency.test.ts | 53 +++
apps/bff/src/logic/oap/endpoint-dependency.ts | 21 +-
apps/bff/src/logic/oap/instance-topology.ts | 5 +-
apps/bff/src/logic/oap/profiling.ts | 10 +-
apps/bff/src/logic/oap/service-topology.ts | 6 +-
apps/bff/src/logic/oap/topology-mqe.test.ts | 36 +++
apps/bff/src/logic/oap/topology-mqe.ts | 9 +-
.../logic/overview/declared-expressions.test.ts | 61 ++++
apps/bff/src/logic/overview/effective.ts | 27 ++
.../src/logic/services/service-identity.test.ts | 42 +++
apps/bff/src/logic/services/service-identity.ts | 208 ++++++++++++
.../src/logic/services/service-layer-catalog.ts | 5 +-
apps/bff/src/oauth/scopes.ts | 5 +-
apps/bff/src/rbac/builtin-roles-access.test.ts | 85 +++++
apps/bff/src/rbac/layer-access.ts | 159 +++++++++
apps/bff/src/rbac/layer-grants.test.ts | 161 ++++++++++
apps/bff/src/rbac/policy.ts | 15 +-
apps/bff/src/rbac/request-access.test.ts | 209 ++++++++++++
apps/bff/src/rbac/request-access.ts | 301 +++++++++++++++++
apps/bff/src/rbac/route-policy.test.ts | 11 +-
apps/bff/src/rbac/route-policy.ts | 60 +++-
apps/bff/src/rbac/route-scope.ts | 328 +++++++++++++++++++
apps/bff/src/rbac/scope-gate.test.ts | 355 +++++++++++++++++++++
apps/bff/src/rbac/scope-gate.ts | 238 ++++++++++++++
apps/bff/src/rbac/verb-enforcement.test.ts | 5 +-
apps/bff/src/rbac/verbs.ts | 129 +++++++-
apps/bff/src/server.ts | 30 +-
apps/ui/src/api/client.ts | 15 +-
apps/ui/src/api/permissionDenied.test.ts | 53 +++
apps/ui/src/api/permissionDenied.ts | 97 ++++++
apps/ui/src/api/queryClient.ts | 4 +
apps/ui/src/features/admin/roles/RolesView.test.ts | 45 ++-
apps/ui/src/features/admin/roles/RolesView.vue | 119 +++++--
apps/ui/src/features/alarms/AlarmFilterRow.vue | 26 +-
apps/ui/src/features/alarms/AlarmsView.test.ts | 5 +
apps/ui/src/features/alarms/AlarmsView.vue | 9 +-
apps/ui/src/i18n/locales/de.json | 20 +-
apps/ui/src/i18n/locales/en.json | 20 +-
apps/ui/src/i18n/locales/es.json | 20 +-
apps/ui/src/i18n/locales/fr.json | 20 +-
apps/ui/src/i18n/locales/ja.json | 20 +-
apps/ui/src/i18n/locales/ko.json | 20 +-
apps/ui/src/i18n/locales/pt.json | 20 +-
apps/ui/src/i18n/locales/zh-CN.json | 20 +-
apps/ui/src/layer/LayerShell.vue | 42 ++-
.../LayerEvaluationRecordView.test.ts | 8 +-
.../LayerEvaluationRecordView.vue | 5 +-
apps/ui/src/layer/logs/useLayerLogs.ts | 3 +-
apps/ui/src/layer/serviceScope.test.ts | 4 +
apps/ui/src/layer/traceql/useTraceQL.ts | 3 +-
apps/ui/src/layer/traces/LayerTracesView.vue | 5 +-
apps/ui/src/layer/traces/useZipkinTraces.ts | 3 +-
apps/ui/src/layer/useLayerLanding.ts | 62 +++-
apps/ui/src/layer/useLayerServiceName.ts | 2 +-
apps/ui/src/layer/useLayerServices.ts | 2 +
.../render/layer-dashboard/LayerDashboardsView.vue | 2 +-
.../widgets/EvaluationRecordDetailPopout.test.ts | 2 +-
.../widgets/EvaluationRecordDetailPopout.vue | 2 +-
.../render/widgets/EvaluationRecordStreamPanel.vue | 2 +-
apps/ui/src/shell/AppSidebar.vue | 12 +-
apps/ui/src/shell/SidebarLayerChildren.vue | 5 +-
apps/ui/src/shell/router/index.ts | 5 +-
apps/ui/src/shell/useLayers.ts | 2 +
apps/ui/src/state/auth.test.ts | 97 +++++-
apps/ui/src/state/auth.ts | 82 +++--
apps/ui/src/state/verbGrammar.test.ts | 79 +++++
apps/ui/src/state/verbGrammar.ts | 118 +++++++
apps/ui/src/state/wildcardExempt.ts | 12 +-
docs/access-control/rbac.md | 65 +++-
docs/changelog/1.1.0.md | 14 +-
docs/customization/layer-templates.md | 2 +-
docs/setup/rbac.md | 2 +
packages/api-client/src/menu.ts | 4 +
127 files changed, 5374 insertions(+), 267 deletions(-)
diff --git a/.claude/skills/local-boot/SKILL.md b/.claude/skills/local-boot/SKILL.md
index 11e604b3..bb88ca79 100644
--- a/.claude/skills/local-boot/SKILL.md
+++ b/.claude/skills/local-boot/SKILL.md
@@ -353,6 +353,32 @@ HORIZON_SERVER_PORT=10081 BFF_PORT=10081 UI_DEV_PORT=10091 \
**Prod is single-port.** The BFF serves the built UI as static files, so
`UI_DEV_PORT` is meaningless outside Vite; only `HORIZON_SERVER_PORT` matters.
+## Boot the layer / group grant demo (two service groups in one layer)
+
+The public demo OAP has one service group per layer, so it cannot show a
+group-limited role beside a whole-layer one. `rbac-demo/` stands up a local
+OAP (BanyanDB, the e2e-pinned images) with `payments::checkout`,
+`payments::ledger` and `risk::scorer` in GENERAL, the OAP's own metrics in
+SO11Y_OAP (a Platform monitoring layer), and a BFF on **:10083** + Vite on
+**:10093** with one user per grant shape — password == username:
+
+| User | Grant | Sees |
+|---|---|---|
+| `viewer` | built-in | every layer but Platform monitoring; both GENERAL groups |
+| `maintainer` | built-in | every layer, Platform monitoring included |
+| `payments` | `…:read@GENERAL[payments]` | the payments entry of GENERAL only |
+| `risk` | `…:read@GENERAL[risk]` | the risk entry only; its map still names `payments::ledger` as a neighbour |
+| `general` | `…:read@GENERAL` | the whole layer, both entries |
+| `so11y` | `metrics:read@SO11Y_OAP` | that operate layer, without `cluster:read` |
+| `mixed` | metrics on payments, logs on risk, plain `alarms:read` | both entries, metrics on one side only |
+
+```bash
+.claude/skills/local-boot/rbac-demo/up.sh # compose up → BFF → Vite → split GENERAL by group
+.claude/skills/local-boot/rbac-demo/down.sh # stop both processes, compose down -v
+```
+
+`up.sh` ends by pushing GENERAL's bundled template with `splitByServiceGroup: true` to that OAP, the way the Layer dashboards admin would, so the sidebar shows one entry per group. The first metrics appear a minute or two after the load generator starts. Images come from `test/e2e/script/env`; export a variable first to override a pin (`SW_OTEL_COLLECTOR_IMAGE=…`).
+
## Boot against an LDAP directory (test)
Stand up a throwaway OpenLDAP, seed it from `ldap-seed.ldif`, then boot with
diff --git a/.claude/skills/local-boot/rbac-demo/docker-compose.yml b/.claude/skills/local-boot/rbac-demo/docker-compose.yml
new file mode 100644
index 00000000..70c330ec
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/docker-compose.yml
@@ -0,0 +1,133 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+# A throwaway OAP with services in TWO service groups of one layer, so layer
+# and group grants can be seen side by side. Images are the ones the e2e
+# fixture pins (test/e2e/script/env); `up.sh` exports them from that file.
+#
+# GENERAL payments::checkout -> payments::ledger <- risk::scorer
+# SO11Y_OAP the OAP itself, scraped by the collector (an operate layer)
+#
+# Host ports are offset so this runs beside the other local environments:
+# GraphQL 12820, admin 17138, agent gRPC 11810.
+
+services:
+ banyandb:
+ image: "ghcr.io/apache/skywalking-banyandb:${SW_BANYANDB_COMMIT}"
+ command: standalone --measure-metadata-cache-wait-duration 1m --stream-metadata-cache-wait-duration 1m
+ healthcheck:
+ test: ["CMD", "sh", "-c", "nc -nz 127.0.0.1 17912"]
+ interval: 5s
+ timeout: 60s
+ retries: 120
+
+ oap:
+ image: "ghcr.io/apache/skywalking/oap:${SW_OAP_COMMIT}"
+ ports:
+ - "12820:12800"
+ - "17138:17128"
+ - "11810:11800"
+ environment:
+ SW_HEALTH_CHECKER: default
+ SW_STORAGE_BANYANDB_TARGETS: banyandb:17912
+ SW_LOG_LAL_FILES: horizon-e2e
+ volumes:
+ - ../../../../test/e2e/script/docker-compose/lal.yaml:/skywalking/config/lal/horizon-e2e.yaml
+ healthcheck:
+ test: ["CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/11800"]
+ interval: 5s
+ timeout: 60s
+ retries: 120
+ start_period: 90s
+ depends_on:
+ banyandb:
+ condition: service_healthy
+
+ # Scrapes the OAP's own Prometheus endpoint into the OAP, which files it
+ # under SO11Y_OAP — a Platform monitoring layer for the demo.
+ otel-collector:
+ image: "${SW_OTEL_COLLECTOR_IMAGE}"
+ command: ["--config=/etc/otel-collector-config.yaml"]
+ volumes:
+ - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml:ro
+ depends_on:
+ oap:
+ condition: service_healthy
+
+ payments-ledger:
+ image: "horizon-e2e-demo-provider:${SW_E2E_SERVICE_COMMIT}"
+ pull_policy: never
+ environment:
+ SW_AGENT_COLLECTOR_BACKEND_SERVICES: oap:11800
+ SW_AGENT_NAME: "payments::ledger"
+ SW_AGENT_INSTANCE_NAME: ledger-1
+ SW_LOGGING_OUTPUT: CONSOLE
+ SW_METER_ACTIVE: 'true'
+ healthcheck:
+ test: ["CMD", "bash", "-c", "cat < /dev/null > /dev/tcp/127.0.0.1/9090"]
+ interval: 5s
+ timeout: 60s
+ retries: 120
+ depends_on:
+ oap:
+ condition: service_healthy
+
+ payments-checkout:
+ image: "horizon-e2e-demo-consumer:${SW_E2E_SERVICE_COMMIT}"
+ pull_policy: never
+ environment:
+ SW_AGENT_COLLECTOR_BACKEND_SERVICES: oap:11800
+ SW_AGENT_NAME: "payments::checkout"
+ SW_AGENT_INSTANCE_NAME: checkout-1
+ SW_LOGGING_OUTPUT: CONSOLE
+ SW_METER_ACTIVE: 'true'
+ PROVIDER_URL: http://payments-ledger:9090
+ depends_on:
+ payments-ledger:
+ condition: service_healthy
+
+ # Another group calling into payments: its topology shows payments::ledger
+ # as a neighbour, which a risk-only role sees but cannot open.
+ risk-scorer:
+ image: "horizon-e2e-demo-consumer:${SW_E2E_SERVICE_COMMIT}"
+ pull_policy: never
+ environment:
+ SW_AGENT_COLLECTOR_BACKEND_SERVICES: oap:11800
+ SW_AGENT_NAME: "risk::scorer"
+ SW_AGENT_INSTANCE_NAME: scorer-1
+ SW_LOGGING_OUTPUT: CONSOLE
+ SW_METER_ACTIVE: 'true'
+ PROVIDER_URL: http://payments-ledger:9090
+ depends_on:
+ payments-ledger:
+ condition: service_healthy
+
+ loadgen:
+ image: "alpine:3.22"
+ command:
+ - sh
+ - -c
+ - |
+ while true; do
+ for h in payments-checkout risk-scorer; do
+ wget -q -O /dev/null --post-data='{"id":"1","name":"demo"}' --header='Content-Type: application/json' "http://$$h:9092/users" || true
+ done
+ sleep 2
+ done
+ depends_on:
+ - payments-checkout
+ - risk-scorer
diff --git a/.claude/skills/local-boot/rbac-demo/down.sh b/.claude/skills/local-boot/rbac-demo/down.sh
new file mode 100755
index 00000000..59a3a3d8
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/down.sh
@@ -0,0 +1,23 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Tear the layer/group-grant demo down: the BFF, Vite and the compose stack.
+set -uo pipefail
+D="$(cd "$(dirname "$0")" && pwd)"
+LOGS="${TMPDIR:-/tmp}/horizon-rbac-demo"
+for p in bff vite; do [ -f "$LOGS/$p.pid" ] && pkill -P "$(cat "$LOGS/$p.pid")" 2>/dev/null; [ -f "$LOGS/$p.pid" ] && kill "$(cat "$LOGS/$p.pid")" 2>/dev/null; done
+docker compose -p horizon-rbac-demo -f "$D/docker-compose.yml" down -v
diff --git a/.claude/skills/local-boot/rbac-demo/otel-collector-config.yaml b/.claude/skills/local-boot/rbac-demo/otel-collector-config.yaml
new file mode 100644
index 00000000..9f485ae5
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/otel-collector-config.yaml
@@ -0,0 +1,44 @@
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+receivers:
+ prometheus:
+ config:
+ scrape_configs:
+ - job_name: skywalking-so11y
+ scrape_interval: 10s
+ static_configs:
+ - targets: ['oap:1234']
+ labels:
+ host_name: oap
+ service: oap-server
+
+processors:
+ batch:
+
+exporters:
+ otlp:
+ endpoint: oap:11800
+ tls:
+ insecure: true
+
+service:
+ pipelines:
+ metrics:
+ receivers: [prometheus]
+ processors: [batch]
+ exporters: [otlp]
diff --git a/.claude/skills/local-boot/rbac-demo/roles.json b/.claude/skills/local-boot/rbac-demo/roles.json
new file mode 100644
index 00000000..7d8d574c
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/roles.json
@@ -0,0 +1 @@
+{"payments-team": ["metrics:read@GENERAL[payments]", "traces:read@GENERAL[payments]", "logs:read@GENERAL[payments]", "topology:read@GENERAL[payments]", "alarms:read@GENERAL[payments]", "profile:read@GENERAL[payments]", "overview:read"], "risk-team": ["metrics:read@GENERAL[risk]", "traces:read@GENERAL[risk]", "logs:read@GENERAL[risk]", "topology:read@GENERAL[risk]", "alarms:read@GENERAL[risk]", "overview:read"], "general-team": ["metrics:read@GENERAL", "traces:read@GENERAL", "logs:read@GE [...]
diff --git a/.claude/skills/local-boot/rbac-demo/up.sh b/.claude/skills/local-boot/rbac-demo/up.sh
new file mode 100755
index 00000000..c7eb207e
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/up.sh
@@ -0,0 +1,85 @@
+#!/usr/bin/env bash
+#
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+#
+# Boot the layer/group-grant demo: a local OAP with services in two groups of
+# GENERAL (see docker-compose.yml), then a BFF on :10083 and Vite on :10093
+# with the roles in roles.json and the users in users.json (password ==
+# username). Ends by splitting GENERAL's sidebar entry by service group on
+# that OAP, so each group is its own entry.
+set -euo pipefail
+
+D="$(cd "$(dirname "$0")" && pwd)"
+REPO="$(git -C "$D" rev-parse --show-toplevel)"
+ENVF="$REPO/test/e2e/script/env"
+pin() { grep "^$1=" "$ENVF" | cut -d= -f2-; }
+# A value already exported in the shell wins over the e2e pin.
+export SW_OAP_COMMIT="${SW_OAP_COMMIT:-$(pin SW_OAP_COMMIT)}"
+export SW_BANYANDB_COMMIT="${SW_BANYANDB_COMMIT:-$(pin SW_BANYANDB_COMMIT)}"
+export SW_E2E_SERVICE_COMMIT="${SW_E2E_SERVICE_COMMIT:-$(pin SW_E2E_SERVICE_COMMIT)}"
+export SW_OTEL_COLLECTOR_IMAGE="${SW_OTEL_COLLECTOR_IMAGE:-$(pin SW_OTEL_COLLECTOR_IMAGE)}"
+
+BFF_PORT=${RBAC_DEMO_BFF_PORT:-10083}
+UI_PORT=${RBAC_DEMO_UI_PORT:-10093}
+LOGS="${TMPDIR:-/tmp}/horizon-rbac-demo"; mkdir -p "$LOGS"
+
+docker compose -p horizon-rbac-demo -f "$D/docker-compose.yml" up -d
+echo "waiting for the OAP…"
+until [ "$(docker inspect -f '{{.State.Health.Status}}' horizon-rbac-demo-oap-1 2>/dev/null)" = healthy ]; do sleep 3; done
+
+# The demo services need no -javaagent: the image presets JAVA_TOOL_OPTIONS.
+HORIZON_SERVER_PORT=$BFF_PORT HORIZON_CONFIG="$REPO/horizon.yaml" \
+HORIZON_OAP_QUERY_URL=http://127.0.0.1:12820 \
+HORIZON_OAP_ADMIN_URL=http://127.0.0.1:17138 \
+HORIZON_AUTH_LOCAL_USERS="$(cat "$D/users.json")" \
+HORIZON_RBAC_BUILTIN_ROLES=keep HORIZON_RBAC_ROLES="$(cat "$D/roles.json")" \
+ nohup pnpm --filter @skywalking-horizon-ui/bff run dev > "$LOGS/bff.log" 2>&1 &
+echo $! > "$LOGS/bff.pid"
+( cd "$REPO/apps/ui" && BFF_PORT=$BFF_PORT UI_DEV_PORT=$UI_PORT \
+ env -u http_proxy -u https_proxy -u all_proxy -u HTTP_PROXY -u HTTPS_PROXY -u ALL_PROXY \
+ nohup node_modules/.bin/vite --host 127.0.0.1 > "$LOGS/vite.log" 2>&1 & echo $! > "$LOGS/vite.pid" )
+
+echo "waiting for the BFF…"
+until curl -sf --noproxy '*' "http://127.0.0.1:$BFF_PORT/api/health" > /dev/null; do sleep 2; done
+
+# Split GENERAL's sidebar entry per service group on this OAP: push the
+# bundled template with the flag on, as the Layer dashboards admin would.
+JAR="$LOGS/admin.cookies"
+curl -sf --noproxy '*' -c "$JAR" -H 'content-type: application/json' \
+ -d '{"username":"admin","password":"admin"}' "http://127.0.0.1:$BFF_PORT/api/auth/login" > /dev/null
+python3 - "$REPO/apps/bff/src/bundled_templates/layers/general.json" <<'PY' > "$LOGS/general-split.json"
+import json, sys
+t = json.load(open(sys.argv[1])); t["splitByServiceGroup"] = True
+print(json.dumps({"name": "horizon.layer.GENERAL", "content": t}))
+PY
+curl -sf --noproxy '*' -b "$JAR" -H 'content-type: application/json' \
+ --data-binary "@$LOGS/general-split.json" "http://127.0.0.1:$BFF_PORT/api/admin/templates/save" > /dev/null
+
+cat <<MSG
+
+Open http://127.0.0.1:$UI_PORT — password is the username.
+
+ viewer every layer but Platform monitoring; both GENERAL groups
+ maintainer every layer, Platform monitoring included
+ payments the payments group of GENERAL only
+ risk the risk group of GENERAL only (its map still shows payments::ledger as a neighbour)
+ general the whole GENERAL layer, both groups
+ so11y the OAP self-observability layer only, without cluster:read
+ mixed metrics on payments, logs on risk, alarms everywhere
+
+Logs: $LOGS. Stop with: $D/down.sh
+MSG
diff --git a/.claude/skills/local-boot/rbac-demo/users.json b/.claude/skills/local-boot/rbac-demo/users.json
new file mode 100644
index 00000000..bb2d7263
--- /dev/null
+++ b/.claude/skills/local-boot/rbac-demo/users.json
@@ -0,0 +1 @@
+[{"username": "viewer", "passwordHash": "$argon2id$v=19$m=65536,t=3,p=4$Gp175hqr+EF2iZ7v1fndvw$w6w9hDI59/UA+CRARChDoGRlR1TkVt6kqzApa021K+0", "roles": ["viewer"]}, {"username": "maintainer", "passwordHash": "$argon2id$v=19$m=65536,t=3,p=4$w7ULwB3/jzH9FxVoHJ238A$y+qGoX6IPeOoGywLQCpfpAN5VJXcaevoWeJQhaybvQU", "roles": ["maintainer"]}, {"username": "operator", "passwordHash": "$argon2id$v=19$m=65536,t=3,p=4$nzoI4RqiobprtzX/mJqe5Q$FY2Hi7mKep0DPHoaE++r/KD++WLUwTgRUFLde87j2Wg", "roles": ["operat [...]
diff --git a/.gitignore b/.gitignore
index f64d0a67..51de72d4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -17,6 +17,7 @@ dist-ssr
!.claude/skills/local-boot/dev-users.json
!.claude/skills/local-boot/dev-ldap.json
!.claude/skills/local-boot/ldap-seed.ldif
+!.claude/skills/local-boot/rbac-demo/
# Editor
.idea
diff --git a/apps/bff/CLAUDE.md b/apps/bff/CLAUDE.md
index 0127875c..81027528 100644
--- a/apps/bff/CLAUDE.md
+++ b/apps/bff/CLAUDE.md
@@ -203,7 +203,11 @@ Two consequences worth stating, because both have been mistaken for bugs:
surface by asking. A column that carries its own `mqe` is a different
request: it names the expression to evaluate and is answered live. The
Overview is built that way, synthesising `w_0`, `w_1`… from its own widgets,
- which no layer template declares and never will.
+ which no layer template declares and never will. A SELF-AGGREGATING column
+ is the exception: it runs with no service in its entity, so it reads the
+ metric across every service, and it is evaluated only when a stored overview
+ (or the layer header) declares that exact expression — otherwise any caller
+ could read any metric of any layer through a layer it can open.
- **The hourly header cache holds only what the template declares.** Its
whitelist is the set of (MQE, entity) pairs under `layer-header.columns`,
matched on the EXPRESSION rather than the column's name — the name is the
@@ -279,6 +283,37 @@ Things worth remembering:
real conversation), so it runs under `performance.aiConversation.viewTimeoutMs`,
never `oap.timeoutMs`.
+## Which layer, which service: `ROUTE_SCOPE`
+
+A verb says WHAT a route reads; `rbac/route-scope.ts` says WHERE. A route whose
+verb can carry a layer (`LAYER_SCOPED_VERBS` — the per-service reads) must have
+an entry there, or registration throws, the same contract `ROUTE_POLICY` holds.
+The entry names the URL's `:key` and every request field that names a service or
+something a service owns (an instance / endpoint id is `<serviceId>_…`; a trace,
+async or pprof task id is `<createTime>_<serviceId>`). The gate checks each one
+before the handler runs; a roster the handler builds itself is filtered through
+`req.access`.
+
+Two rules that are easy to break:
+
+- **Check exactly the identity the handler QUERIES.** A picker sends a
+ service's id and its name; a handler that queries by the id has its id
+ listed, and the name beside it is an echo — checking it too would refuse a
+ caller whose name also belongs to a conjectured service they may not read.
+ A handler that queries by the name (process-relation metrics, events) has
+ the name listed.
+- **An empty selector reads every service.** OAP reads a missing `serviceId`
+ as "all services", not "this layer's services", so a layer-limited caller
+ must name one (`requireService`). Plain grants keep the cross-service read.
+
+The AI tools reach OAP without passing through these routes, and their figures
+replay from the captured payload, so each tool asks `ctx.access` itself before
+it reads and before it emits — see `ai/lib/tools/access.ts`. A tool that sends
+a service name or id to OAP as the model wrote it must refuse one OAP would not
+read as written (padding, control characters, a lone surrogate), as the gate
+does; a tool that looks the name up in the catalog and sends the row's id is
+safe already.
+
## Do not invent fields
The GraphQL query-protocol and the admin REST surface are **fixed** — owned by
diff --git a/apps/bff/src/ai/chat-assistant/route.ts b/apps/bff/src/ai/chat-assistant/route.ts
index 9e3460a1..273d9bf0 100644
--- a/apps/bff/src/ai/chat-assistant/route.ts
+++ b/apps/bff/src/ai/chat-assistant/route.ts
@@ -49,10 +49,12 @@ import { createGraphicCardBuffer } from '../lib/graphic-card-buffer.js';
import type { ToolContext } from '../lib/tool-context.js';
import type { StreamEvent } from '../lib/graphic-card.js';
import { SECURITY_HEADERS, API_CACHE_CONTROL } from '../../util/security-headers.js';
+import { buildRequestAccess, type AccessDeps } from '../../rbac/request-access.js';
export interface AiChatRouteDeps extends AuthDeps {
fetch?: FetchLike;
uiTemplateClient?: () => UITemplateClient;
+ access?: AccessDeps;
}
const chatBodySchema = z.object({
@@ -106,6 +108,7 @@ export function registerAiRoutes(app: FastifyInstance, deps: AiChatRouteDeps): v
}
const subject = req.session ?? { roles: [] };
+ const access = deps.access ? await buildRequestAccess(cfg, subject, deps.access) : undefined;
const offset = await getServerOffsetMinutes(deps.config, deps.fetch);
const nowMs = Date.now();
const endMs = parsed.data.endMs ?? nowMs;
@@ -185,6 +188,7 @@ export function registerAiRoutes(app: FastifyInstance, deps: AiChatRouteDeps): v
range: { startMs, endMs, step },
bulkSize: cfg.performance.bulk.dashboard.bulkSize,
hasVerb: (verb) => sessionHasVerb(cfg, subject, verb),
+ access,
emitFigure,
emitProposal,
emitProfiling,
diff --git a/apps/bff/src/ai/lib/tool-context.ts b/apps/bff/src/ai/lib/tool-context.ts
index db5c0ed0..5ff37c27 100644
--- a/apps/bff/src/ai/lib/tool-context.ts
+++ b/apps/bff/src/ai/lib/tool-context.ts
@@ -29,6 +29,7 @@ import type { FetchLike, UITemplateClient } from '@skywalking-horizon-ui/api-cli
import type { GraphqlOptions } from '../../client/graphql.js';
import type { ConfigSource } from '../../config/loader.js';
import type { Window } from '../../util/window.js';
+import type { RequestAccess } from '../../rbac/request-access.js';
import type {
ChatFigure,
DeploymentSpec,
@@ -64,6 +65,11 @@ export interface ToolContext {
/** Caller's roles — every tool checks its own read verb before touching OAP,
* so the agent inherits the caller's read scopes and never widens them. */
hasVerb(verb: string): boolean;
+ /** Which layers and services the caller may read. A tool that names a
+ * service asks this before it reads, and before it emits anything: its
+ * figures replay from the captured payload and never pass back through an
+ * HTTP route that could check them. Absent in unit tests — no restriction. */
+ access?: RequestAccess;
/** Queue/emit a figure. With a `group` label, consecutive figures sharing it
* are buffered and flushed as ONE tabbed figure block (the "figures 2–5,
* tab-based" UX); without a group, any pending group is flushed first and
diff --git a/apps/bff/src/ai/lib/tools/access.ts b/apps/bff/src/ai/lib/tools/access.ts
new file mode 100644
index 00000000..252cb12d
--- /dev/null
+++ b/apps/bff/src/ai/lib/tools/access.ts
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The tools' side of the layer grants: the same questions the HTTP scope gate
+ * asks, for tools that read OAP directly. A tool checks BEFORE it reads and
+ * before it emits a figure — a captured figure replays from its payload and
+ * never passes back through a route that could check it.
+ */
+
+import type { ToolContext } from '../tool-context.js';
+import { isExactIdentity, type ServiceRef } from '../../../rbac/request-access.js';
+
+/** The verb gate a tool opens with: held plainly, or on some layer. Which
+ * layer and which service is decided once the tool knows them. */
+export function holds(ctx: ToolContext, verb: string): boolean {
+ return ctx.access ? ctx.access.session.holds(verb) : ctx.hasVerb(verb);
+}
+
+/** The denial every tool answers with — the chat activity line marks a tool
+ * "denied" only when its output starts with `Permission denied:`. */
+export function denied(verb: string, what = ''): string {
+ return `Permission denied: the current user lacks ${verb}${what ? ` on ${what}` : ''}.`;
+}
+
+/** What a tool answers for a service name or id OAP would not read as
+ * written — see {@link isExactIdentity}. Null when it is exact. */
+export function inexact(value: string | undefined, what = 'the service', source = 'list_services'): string | null {
+ return value !== undefined && isExactIdentity(value) ? null : `Name ${what} exactly as ${source} returns it.`;
+}
+
+export type ReadDecision = 'allow' | 'deny' | 'unavailable';
+
+export async function decide(ctx: ToolContext, verb: string, ref: ServiceRef): Promise<ReadDecision> {
+ return ctx.access ? ctx.access.decide([verb], ref) : 'allow';
+}
+
+/** An OAP that could not say who owns a service is an outage, not a refusal —
+ * the model must not tell the operator they lack a permission they hold. */
+export function unverifiable(what: string): string {
+ return `OAP did not answer which layer ${what} belongs to, so it cannot be read right now. This is not a permission problem; try again shortly.`;
+}
+
+/** A caller holding `verb` plainly is told a name is unknown, as before layer
+ * grants existed; a layer-limited one gets one answer for "no such service"
+ * and "not yours", so a refusal does not confirm another team's service. */
+export function tellsUnknownApart(ctx: ToolContext, verb: string): boolean {
+ return !ctx.access || !ctx.access.layerLimited([verb]);
+}
+
+export function noReadableService(verb: string, layer: string, name: string): string {
+ return `Permission denied: layer ${layer.toUpperCase()} has no service "${name}" the current user may read with ${verb}. list_services shows the ones it can.`;
+}
+
+/** The roster row named `name`, when the caller may read it; otherwise what
+ * the tool answers — see {@link tellsUnknownApart}. */
+export async function readableRow<T extends { id: string; name: string }>(
+ ctx: ToolContext,
+ verb: string,
+ layer: string,
+ name: string,
+ rows: readonly T[],
+): Promise<{ row: T } | { answer: string }> {
+ const row = rows.find((s) => s.name === name);
+ if (!row) {
+ return {
+ answer: tellsUnknownApart(ctx, verb)
+ ? `Unknown service "${name}" in layer ${layer}. Use list_services first.`
+ : noReadableService(verb, layer, name),
+ };
+ }
+ const d = await decide(ctx, verb, { id: row.id });
+ if (d === 'allow') return { row };
+ return { answer: d === 'unavailable' ? unverifiable(`service ${name}`) : noReadableService(verb, layer, name) };
+}
+
+/** Null when the caller may read `ref`; otherwise what the tool answers. */
+export async function refusal(ctx: ToolContext, verb: string, ref: ServiceRef, what: string): Promise<string | null> {
+ const d = await decide(ctx, verb, ref);
+ return d === 'allow' ? null : d === 'unavailable' ? unverifiable(what) : denied(verb, what);
+}
+
+/** The graph block to draw for the caller — see `RequestAccess.graphConfig`. */
+export async function graphConfig<T>(ctx: ToolContext, verb: string, focusIds: readonly string[], cfg: T): Promise<T> {
+ return ctx.access ? ctx.access.graphConfig([verb], focusIds, cfg) : cfg;
+}
+
+/** Keep the rows of `layer` the caller may read with `verb`. */
+export function readableRows<T extends { group?: string | null }>(
+ ctx: ToolContext,
+ verb: string,
+ layer: string,
+ rows: T[],
+): T[] {
+ return ctx.access ? ctx.access.filterRoster([verb], layer, rows) : rows;
+}
+
+/** A whole-deployment read (a store with no service scoping, alarms with no
+ * entity): only for a caller who holds the verb with no layer limit. */
+export function readsEverything(ctx: ToolContext, verb: string): boolean {
+ return ctx.access ? ctx.access.plain(verb) : ctx.hasVerb(verb);
+}
diff --git a/apps/bff/src/ai/lib/tools/context/tools.test.ts b/apps/bff/src/ai/lib/tools/context/tools.test.ts
index 969ba9e1..e7853f57 100644
--- a/apps/bff/src/ai/lib/tools/context/tools.test.ts
+++ b/apps/bff/src/ai/lib/tools/context/tools.test.ts
@@ -34,6 +34,9 @@ vi.mock('../../../../logic/services/service-layer-catalog.js', () => ({
import { contextTools } from './tools.js';
import type { ToolContext } from '../../tool-context.js';
+import { RequestAccess } from '../../../../rbac/request-access.js';
+import { SessionAccess } from '../../../../rbac/layer-access.js';
+import type { ServiceIdentityResolver } from '../../../../logic/services/service-identity.js';
function tools(hasVerb = true) {
const ctx = { hasVerb: () => hasVerb, config: {}, fetch: undefined } as unknown as ToolContext;
@@ -69,3 +72,24 @@ describe('list_services', () => {
expect(String(await tools(false).listServices.invoke({}))).toMatch(/permission|metrics:read/i);
});
});
+
+describe('the roster tools answer with what the caller may read', () => {
+ const facts = { isOperate: (l: string) => l === 'K8S_SERVICE', canonical: (l: string) => l.toUpperCase() };
+ const limited = (grants: string[]) => {
+ const access = new RequestAccess(new SessionAccess(grants, undefined, facts), {} as ServiceIdentityResolver);
+ const ctx = { hasVerb: () => false, access, config: {}, fetch: undefined } as unknown as ToolContext;
+ const [listLayers, listServices] = contextTools(ctx);
+ return { listLayers, listServices };
+ };
+
+ it('keeps an operate layer from a plain viewer', async () => {
+ const t = limited(['metrics:read']);
+ expect(parse(await t.listServices.invoke({})).services.map((s: { layer: string }) => s.layer)).toEqual(['GENERAL', 'GENERAL']);
+ expect(parse(await t.listLayers.invoke({})).map((l: { layer: string }) => l.layer)).toEqual(['GENERAL']);
+ });
+
+ it('lists only the granted layer for a layer grant, and the operate one it names', async () => {
+ const t = limited(['metrics:read@K8S_SERVICE']);
+ expect(parse(await t.listServices.invoke({})).services.map((s: { name: string }) => s.name)).toEqual(['showcase::gateway.ns']);
+ });
+});
diff --git a/apps/bff/src/ai/lib/tools/context/tools.ts b/apps/bff/src/ai/lib/tools/context/tools.ts
index 30a6c8d9..7dc9cc80 100644
--- a/apps/bff/src/ai/lib/tools/context/tools.ts
+++ b/apps/bff/src/ai/lib/tools/context/tools.ts
@@ -29,6 +29,7 @@ import { serviceLayerCatalog } from '../../../../logic/services/service-layer-ca
import { resolveEffectiveLayer } from '../../../../logic/layers/effective.js';
import { getPreflight } from '../../../../logic/preflight/preflight.js';
import { toolPrompt } from '../../skills/loader.js';
+import { holds, readableRows } from '../access.js';
export function contextTools(ctx: ToolContext): StructuredToolInterface[] {
const catalog = () => serviceLayerCatalog({ config: ctx.config, fetch: ctx.fetch }).get();
@@ -36,12 +37,15 @@ export function contextTools(ctx: ToolContext): StructuredToolInterface[] {
const listLayers = tool(
async (): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const cat = await catalog();
+ // The layers the caller's sidebar shows, counted the way it counts them.
+ const layers = ctx.access ? cat.layers.filter((l) => ctx.access!.menuShows(l)) : cat.layers;
const rows = await Promise.all(
- cat.layers.map(async (layer) => {
+ layers.map(async (layer) => {
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
- return { layer, alias: eff.template?.alias, services: cat.byLayer.get(layer)?.length ?? 0 };
+ const services = readableRows(ctx, 'metrics:read', layer, cat.byLayer.get(layer) ?? []).length;
+ return { layer, alias: eff.template?.alias, services };
}),
);
return JSON.stringify(rows);
@@ -57,7 +61,7 @@ export function contextTools(ctx: ToolContext): StructuredToolInterface[] {
const svc = toolPrompt('context', 'list_services');
const listServices = tool(
async ({ layer, keyword }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const cat = await catalog();
const k = keyword?.toLowerCase();
// Each row is tagged with its layer. A service can belong to more than one
@@ -65,7 +69,7 @@ export function contextTools(ctx: ToolContext): StructuredToolInterface[] {
// so it appears once per layer — the agent still needs a layer to browse
// that service's metric catalog, so the layer rides with every row.
const collect = (l: string): Array<{ id: string; name: string; layer: string }> =>
- (cat.byLayer.get(l) ?? [])
+ readableRows(ctx, 'metrics:read', l, cat.byLayer.get(l) ?? [])
.filter((r) => !k || r.name.toLowerCase().includes(k))
.map((r) => ({ id: r.id, name: r.name, layer: l }));
const rows = layer ? collect(layer.toUpperCase()) : cat.layers.flatMap(collect);
@@ -89,7 +93,7 @@ export function contextTools(ctx: ToolContext): StructuredToolInterface[] {
// runs, behind its single-flight cache.
const health = tool(
async (): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const pre = await getPreflight(
ctx.config.current,
ctx.fetch ?? globalThis.fetch.bind(globalThis),
diff --git a/apps/bff/src/ai/lib/tools/kubernetes/tools.ts b/apps/bff/src/ai/lib/tools/kubernetes/tools.ts
index 5c538147..4d3e976c 100644
--- a/apps/bff/src/ai/lib/tools/kubernetes/tools.ts
+++ b/apps/bff/src/ai/lib/tools/kubernetes/tools.ts
@@ -45,6 +45,7 @@ import type { PodLogLine } from '../../graphic-card.js';
import { graphqlPost } from '../../../../client/graphql.js';
import { fmtSecond, getServerOffsetMinutes } from '../../../../util/window.js';
import { toolPrompt } from '../../skills/loader.js';
+import { holds, inexact, refusal } from '../access.js';
const DEFAULT_WINDOW_SEC = 120; // 2m trailing look-back for the agent's read
const MAX_WINDOW_SEC = 30 * 60; // 30m — same ceiling as the Pod Logs tab
@@ -125,7 +126,11 @@ export function kubernetesTools(ctx: ToolContext): StructuredToolInterface[] {
const listPrompt = toolPrompt('kubernetes', 'list_pod_containers');
const list = tool(
async ({ serviceInstanceId }): Promise<string> => {
- if (!ctx.hasVerb('logs:read')) return denied();
+ if (!holds(ctx, 'logs:read')) return denied();
+ const bad = inexact(serviceInstanceId, 'the instance id', 'kb_resolve_scope_drill');
+ if (bad) return bad;
+ const no = await refusal(ctx, 'logs:read', { childId: serviceInstanceId }, 'this pod');
+ if (no) return no;
const r = await queryContainers(serviceInstanceId);
if ('unavailable' in r) return ENABLE_HINT;
if ('error' in r) return `Could not list containers: ${r.error}`;
@@ -150,8 +155,12 @@ export function kubernetesTools(ctx: ToolContext): StructuredToolInterface[] {
const fetchPrompt = toolPrompt('kubernetes', 'fetch_pod_logs');
const fetchLogs = tool(
async (input): Promise<string> => {
- if (!ctx.hasVerb('logs:read')) return denied();
+ if (!holds(ctx, 'logs:read')) return denied();
const { serviceInstanceId } = input;
+ const bad = inexact(serviceInstanceId, 'the instance id', 'kb_resolve_scope_drill');
+ if (bad) return bad;
+ const no = await refusal(ctx, 'logs:read', { childId: serviceInstanceId }, 'this pod');
+ if (no) return no;
const windowSec = Math.min(
MAX_WINDOW_SEC,
input.windowSeconds && input.windowSeconds > 0 ? input.windowSeconds : DEFAULT_WINDOW_SEC,
diff --git a/apps/bff/src/ai/lib/tools/metric-catalog/tools.ts b/apps/bff/src/ai/lib/tools/metric-catalog/tools.ts
index 3c1b5923..e3cd57fa 100644
--- a/apps/bff/src/ai/lib/tools/metric-catalog/tools.ts
+++ b/apps/bff/src/ai/lib/tools/metric-catalog/tools.ts
@@ -32,6 +32,7 @@ import { serviceLayerCatalog } from '../../../../logic/services/service-layer-ca
import { getServiceHierarchy } from '../../../../logic/oap/hierarchy.js';
import { layerCapabilitiesResult } from '../../../../logic/layers/capabilities.js';
import { toolPrompt } from '../../skills/loader.js';
+import { denied as deniedOn, holds, inexact, refusal } from '../access.js';
import { getLayerCatalog } from './catalog.js';
import { explainEmptyCatalog } from './unreadable.js';
@@ -57,7 +58,7 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const cap0 = toolPrompt('metric-catalog', 'kb_layer_capabilities');
const capabilities = tool(
async ({ layer }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const { capabilities, reason } = await layerCapabilitiesResult(ctx.uiTemplateClient, layer);
if (!capabilities) return explainEmptyCatalog(reason, layer);
return JSON.stringify(capabilities);
@@ -72,7 +73,7 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const brw = toolPrompt('metric-catalog', 'kb_browse_catalog');
const browse = tool(
async ({ layer, scope }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const { entries, reason } = await getLayerCatalog(
{ config: ctx.config, uiTemplateClient: ctx.uiTemplateClient },
layer,
@@ -106,7 +107,11 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const drl = toolPrompt('metric-catalog', 'kb_resolve_scope_drill');
const drill = tool(
async ({ serviceId, toScope, keyword }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
+ const bad = inexact(serviceId, 'the service id');
+ if (bad) return bad;
+ const no = await refusal(ctx, 'metrics:read', { id: serviceId }, 'this service');
+ if (no) return no;
try {
if (toScope === 'instance') {
const data = await graphqlPost<{ instances: Array<{ id: string; name: string; language?: string | null }> }>(
@@ -148,7 +153,7 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const dsc = toolPrompt('metric-catalog', 'kb_describe_metric');
const describe = tool(
async ({ layer, scope, id }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const { entries, reason } = await getLayerCatalog(
{ config: ctx.config, uiTemplateClient: ctx.uiTemplateClient },
layer,
@@ -183,7 +188,7 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const srch = toolPrompt('metric-catalog', 'kb_search_metrics');
const search = tool(
async ({ keyword, scope }): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return denied();
+ if (!holds(ctx, 'metrics:read')) return denied();
const k = keyword.toLowerCase();
const sc = (scope ?? 'service') as DashboardScope;
const cat = await serviceLayerCatalog({ config: ctx.config, fetch: ctx.fetch }).get();
@@ -232,7 +237,11 @@ export function metricCatalogTools(ctx: ToolContext): StructuredToolInterface[]
const hier = toolPrompt('metric-catalog', 'kb_resolve_hierarchy');
const hierarchy = tool(
async ({ serviceId, layer }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return deniedOn('topology:read');
+ const bad = inexact(serviceId, 'the service id');
+ if (bad) return bad;
+ const no = await refusal(ctx, 'topology:read', { id: serviceId }, 'this service');
+ if (no) return no;
try {
const res = await getServiceHierarchy(ctx.config.current, serviceId, layer, ctx.fetch);
if (!res.reachable) return 'Hierarchy is unavailable (OAP unreachable).';
diff --git a/apps/bff/src/ai/lib/tools/telemetry/tools.ts b/apps/bff/src/ai/lib/tools/telemetry/tools.ts
index 55dd89c6..1a091427 100644
--- a/apps/bff/src/ai/lib/tools/telemetry/tools.ts
+++ b/apps/bff/src/ai/lib/tools/telemetry/tools.ts
@@ -30,6 +30,7 @@ import type { ToolContext } from '../../tool-context.js';
import { graphqlPost } from '../../../../client/graphql.js';
import { fmtSecond, getServerOffsetMinutes } from '../../../../util/window.js';
import { toolPrompt } from '../../skills/loader.js';
+import { denied, readsEverything } from '../access.js';
const ALARM_WINDOW_MS = 3 * 60 * 60_000; // under OAP's 4h alarm cap
@@ -55,9 +56,9 @@ export function telemetryTools(ctx: ToolContext): StructuredToolInterface[] {
const alarms = toolPrompt('telemetry', 'list_alarms');
const listAlarms = tool(
async ({ layer, keyword }): Promise<string> => {
- if (!ctx.hasVerb('alarms:read')) {
- return 'Permission denied: the current user lacks alarms:read.';
- }
+ // Alarms for every service in the window: a caller whose alarms:read is
+ // limited to some layers cannot be answered from this query.
+ if (!readsEverything(ctx, 'alarms:read')) return denied('alarms:read', 'every layer');
const offset = await getServerOffsetMinutes(ctx.config, ctx.fetch);
const endMs = ctx.range.endMs;
// Independent look-back — NOT clamped to the (often narrower, 60m-default)
diff --git a/apps/bff/src/ai/lib/tools/triggers/tools.test.ts b/apps/bff/src/ai/lib/tools/triggers/tools.test.ts
index 900f9fbd..c18c4ad0 100644
--- a/apps/bff/src/ai/lib/tools/triggers/tools.test.ts
+++ b/apps/bff/src/ai/lib/tools/triggers/tools.test.ts
@@ -37,6 +37,7 @@ vi.mock('../../../../logic/oap/profiling.js', () => ({
findInstanceWithProcesses: vi.fn(async () => ({ instance: { id: 'i-1', name: 'inst-1', language: 'java' }, checked: 1, total: 1, failed: 0 })),
analyzeProfiling: vi.fn(),
analyzeNetworkProfiling: vi.fn(),
+ profilingServiceId: vi.fn(async () => ({ id: 'svc-1' })),
MAX_PROCESS_PROBES: 60,
serviceCanEbpfProfile: vi.fn(async () => ({ could: true })),
}));
@@ -46,6 +47,9 @@ import { layerCapabilities } from '../../../../logic/layers/capabilities.js';
import { resolveEffectiveLayer } from '../../../../logic/layers/effective.js';
import { findInstanceWithProcesses, listServiceInstances, serviceCanEbpfProfile } from '../../../../logic/oap/profiling.js';
import type { ToolContext } from '../../tool-context.js';
+import { RequestAccess } from '../../../../rbac/request-access.js';
+import { SessionAccess } from '../../../../rbac/layer-access.js';
+import type { ServiceIdentityResolver } from '../../../../logic/services/service-identity.js';
function mockCtx(hasVerb: boolean) {
const emitProposal = vi.fn();
@@ -426,3 +430,45 @@ describe('analyze_profiling', () => {
expect(String(out)).not.toMatch(/Call analyze_profiling again with that event/);
});
});
+
+describe('analyze_profiling for a layer-limited caller', () => {
+ // A GENERAL service and a conjectured namesake in a layer the role is not granted.
+ const real = { id: 'svc-1', name: 'agent::frontend', normal: true, group: 'agent', layers: ['GENERAL'] };
+ const conjectured = { ...real, id: 'svc-1-conj', normal: false, layers: ['VIRTUAL_DATABASE'] };
+ const resolver = {
+ byId: async (id: string) => [real, conjectured].find((s) => s.id === id) ?? null,
+ byName: async () => [real, conjectured],
+ } as unknown as ServiceIdentityResolver;
+ const limited = () => {
+ const { ctx } = mockCtx(false);
+ const session = new SessionAccess(['profile:read@GENERAL[agent]'], undefined, {
+ isOperate: () => false,
+ canonical: (l: string) => l.toUpperCase(),
+ });
+ (ctx as { access?: RequestAccess }).access = new RequestAccess(session, resolver);
+ return ctx;
+ };
+
+ it('checks the service the name resolves to in the layer, and reads that one', async () => {
+ const { analyzeProfiling, profilingServiceId } = await import('../../../../logic/oap/profiling.js');
+ (analyzeProfiling as unknown as Mock).mockResolvedValueOnce({
+ profilingType: 'trace', taskId: null, trees: [], metricKey: 'count', tip: null, logs: [],
+ summary: { service: real.name, frameCount: 0 }, reachable: true,
+ });
+ const [, analyze] = triggerTools(limited());
+ const out = String(await analyze.invoke({ layer: 'general', service: real.name, profilingType: 'trace' }));
+ expect(out).not.toMatch(/^Permission denied/);
+ expect(analyzeProfiling).toHaveBeenLastCalledWith(expect.objectContaining({ serviceId: 'svc-1' }));
+
+ (profilingServiceId as unknown as Mock).mockResolvedValueOnce({ id: conjectured.id });
+ const refused = String(await analyze.invoke({ layer: 'virtual_database', service: real.name, profilingType: 'trace' }));
+ expect(refused).toMatch(/^Permission denied/);
+ });
+
+ it('refuses a name OAP would not read as written', async () => {
+ const [, analyze] = triggerTools(limited());
+ for (const service of ['', ' agent::frontend', '\u0000']) {
+ expect(String(await analyze.invoke({ layer: 'general', service, profilingType: 'trace' }))).toMatch(/exactly as list_services/);
+ }
+ });
+});
diff --git a/apps/bff/src/ai/lib/tools/triggers/tools.ts b/apps/bff/src/ai/lib/tools/triggers/tools.ts
index 125459cf..7a2550bd 100644
--- a/apps/bff/src/ai/lib/tools/triggers/tools.ts
+++ b/apps/bff/src/ai/lib/tools/triggers/tools.ts
@@ -36,12 +36,14 @@ import {
analyzeNetworkProfiling,
findInstanceWithProcesses,
listServiceInstances,
+ profilingServiceId,
serviceCanEbpfProfile,
} from '../../../../logic/oap/profiling.js';
import type { ProfilingAnalysis } from '../../../../logic/oap/profiling.js';
import { layerCapabilities } from '../../../../logic/layers/capabilities.js';
import { resolveEffectiveLayer } from '../../../../logic/layers/effective.js';
import { getServerOffsetMinutes } from '../../../../util/window.js';
+import { decide, holds, inexact, tellsUnknownApart, unverifiable } from '../access.js';
// Horizon-side template config, NOT an OAP capability: none of OAP's five
// profiling create paths takes a layer, so a missing type is a hint, not proof
@@ -136,8 +138,12 @@ export function triggerTools(ctx: ToolContext): StructuredToolInterface[] {
const t = toolPrompt('triggers', 'propose_profiling');
const propose = tool(
async ({ layer, serviceId, service, profilingType, durationMinutes, endpoint, event, targetType, instances, cause, rationale, expectation }): Promise<string> => {
- if (!ctx.hasVerb('profile:enable')) {
- return 'You lack permission to start profiling (profile:enable). Do not propose it; explain what a profiling task would reveal instead.';
+ const bad = inexact(serviceId, 'the service id');
+ if (bad) return bad;
+ const may = holds(ctx, 'profile:enable') ? await decide(ctx, 'profile:enable', { id: serviceId }) : 'deny';
+ if (may === 'unavailable') return unverifiable(service);
+ if (may === 'deny') {
+ return `Permission denied: the current user cannot start profiling on ${service} (profile:enable). Do not propose it; explain what a profiling task would reveal instead.`;
}
const layerKey = layer.toUpperCase();
// Readiness signals are ADVICE, never a veto: OAP's checkCreateRequest /
@@ -346,9 +352,24 @@ export function triggerTools(ctx: ToolContext): StructuredToolInterface[] {
async ({ layer, service, profilingType, taskId, event }): Promise<string> => {
// Same read verb the profiling routes require — the assistant never widens
// the caller's read scope (profile:enable does NOT imply profile:read).
- if (!ctx.hasVerb('profile:read')) {
- return 'Permission denied: the current user lacks profile:read. Do not analyze; say profiling results are not readable for this user.';
+ const bad = inexact(service);
+ if (bad) return bad;
+ const refused = `Permission denied: the current user cannot read profiling results for ${service} (profile:read). Do not analyze; say profiling results are not readable for this user.`;
+ if (!holds(ctx, 'profile:read')) return refused;
+ // The analysis reads the one service the name resolves to in this layer,
+ // so that is the identity to check — not every service of the name.
+ let serviceId: string;
+ try {
+ const found = await profilingServiceId(ctx.opts, layer, service);
+ // To a layer-limited caller an unknown service reads as a refusal.
+ if ('error' in found) return tellsUnknownApart(ctx, 'profile:read') ? found.error : refused;
+ serviceId = found.id;
+ } catch (err) {
+ return `Could not read the services of ${layer.toUpperCase()}: ${err instanceof Error ? err.message : String(err)}`;
}
+ const may = await decide(ctx, 'profile:read', { id: serviceId });
+ if (may === 'unavailable') return unverifiable(service);
+ if (may === 'deny') return refused;
// Network profiling has no flame — its result is a process-conversation
// graph. CAPTURE it and render a frozen block (never a live tab, which would
// drift). When no processes report — Rover/eBPF absent — say it out in text.
@@ -366,6 +387,7 @@ export function triggerTools(ctx: ToolContext): StructuredToolInterface[] {
rangeMs: { startMs: ctx.range.startMs, endMs: ctx.range.endMs },
offsetMinutes: await getServerOffsetMinutes(ctx.config, ctx.fetch),
taskId,
+ serviceId,
});
const topo = r.topology;
const windowLabel = `${r.queried.start} to ${r.queried.end}`;
@@ -397,7 +419,7 @@ export function triggerTools(ctx: ToolContext): StructuredToolInterface[] {
});
return `Captured the network process-conversation graph for ${service} (instance ${r.instanceName ?? 'unknown'}; ${scope}; times are OAP-server local): ${topo.nodes.length} process(es), ${topo.calls.length} conversation(s).`;
}
- const a = await analyzeProfiling({ opts: ctx.opts, profilingType, layerKey: layer, service, taskId, event });
+ const a = await analyzeProfiling({ opts: ctx.opts, profilingType, layerKey: layer, service, taskId, event, serviceId });
ctx.emitProfiling({
title: `Profiling — ${service} (${profilingType})`,
profilingType: a.profilingType,
diff --git a/apps/bff/src/ai/lib/tools/visualization/tools.test.ts b/apps/bff/src/ai/lib/tools/visualization/tools.test.ts
index 4beaee3f..207c5417 100644
--- a/apps/bff/src/ai/lib/tools/visualization/tools.test.ts
+++ b/apps/bff/src/ai/lib/tools/visualization/tools.test.ts
@@ -64,6 +64,9 @@ import { buildInstanceTopology } from '../../../../logic/oap/instance-topology.j
import { resolveEffectiveLayer } from '../../../../logic/layers/effective.js';
import type { ToolContext } from '../../tool-context.js';
import type { StructuredToolInterface } from '@langchain/core/tools';
+import { RequestAccess } from '../../../../rbac/request-access.js';
+import { SessionAccess } from '../../../../rbac/layer-access.js';
+import { ServiceLookupUnavailable, type ServiceIdentityResolver } from '../../../../logic/services/service-identity.js';
const runWidgetsMock = runWidgets as unknown as ReturnType<typeof vi.fn>;
const getHierarchy = getServiceHierarchy as unknown as ReturnType<typeof vi.fn>;
@@ -440,3 +443,117 @@ describe('a tool never claims the call drew something', () => {
expect(offenders).toEqual([]);
});
});
+
+describe('a layer-limited caller draws only services it may read', () => {
+ const songs = { id: 'svc-1', name: 'agent::songs', normal: true, group: 'agent', layers: ['GENERAL'] };
+ const resolver = {
+ byId: async (id: string) => (id === songs.id ? songs : null),
+ byName: async (name: string) => (name === songs.name ? [songs] : null),
+ } as unknown as ServiceIdentityResolver;
+ const facts = { isOperate: () => false, canonical: (l: string) => l.toUpperCase() };
+ const limitedCtx = (grants: string[]) => {
+ const m = mockCtx(false);
+ (m.ctx as { access?: RequestAccess }).access = new RequestAccess(new SessionAccess(grants, undefined, facts), resolver);
+ return m;
+ };
+
+ it('draws a service of its own group', async () => {
+ runWidgetsMock.mockResolvedValue({ widgets: [{ id: 'ai_fig', value: 1 }] });
+ const m = limitedCtx(['metrics:read@GENERAL[agent]']);
+ await byName(m.ctx).show_figure.invoke({ ...base, type: 'card', expressions: ['x'] });
+ expect(m.emitFigure).toHaveBeenCalledOnce();
+ });
+
+ it('refuses an empty or padded service name before reading anything', async () => {
+ const m = limitedCtx(['metrics:read@GENERAL[agent]']);
+ for (const service of ['', ' agent::songs', '\u0000', 'agent::songs\uDC00']) {
+ const out = String(await byName(m.ctx).show_figure.invoke({ ...base, service, type: 'card', expressions: ['x'] }));
+ expect(out).toMatch(/exactly as list_services returns it/);
+ }
+ expect(runWidgetsMock).not.toHaveBeenCalled();
+ });
+
+ it('refuses another group before reading or emitting anything', async () => {
+ const m = limitedCtx(['metrics:read@GENERAL[payments]']);
+ const out = String(await byName(m.ctx).show_figure.invoke({ ...base, type: 'card', expressions: ['x'] }));
+ expect(out).toMatch(/^Permission denied:/);
+ expect(runWidgetsMock).not.toHaveBeenCalled();
+ expect(m.emitFigure).not.toHaveBeenCalled();
+ });
+
+ it('reads a widget that shows only on a baseline through every service the name can mean', async () => {
+ const virtual = { ...songs, id: 'svc-1-conjectured', normal: false, layers: ['VIRTUAL_DATABASE'] };
+ const namesakes = {
+ byId: async (id: string) => (id === songs.id ? songs : null),
+ byName: async (name: string) => (name === songs.name ? [songs, virtual] : null),
+ } as unknown as ServiceIdentityResolver;
+ const m = mockCtx(false);
+ const grants = ['metrics:read@GENERAL[agent]'];
+ (m.ctx as { access?: RequestAccess }).access = new RequestAccess(new SessionAccess(grants, undefined, facts), namesakes);
+ const widget = (visibleWhen?: object) => ({
+ key: 'GENERAL',
+ dashboards: { service: [{ id: 'load', type: 'line', title: 'Load', expressions: ['service_cpm'], visibleWhen }] },
+ });
+ runWidgetsMock.mockResolvedValue({ widgets: [{ id: 'load', series: [{ data: [1, 2] }] }] });
+ const show = () => byName(m.ctx).show_widget.invoke({ layer: 'GENERAL', service: songs.name, widgetId: 'load' });
+
+ resolveEff.mockResolvedValue({ blocked: false, template: widget() });
+ expect(String(await show())).not.toMatch(/^Permission denied:/);
+ resolveEff.mockResolvedValue({
+ blocked: false,
+ template: widget({ kind: 'mqe', expression: 'baseline(service_cpm,value)', op: 'exists' }),
+ });
+ expect(String(await show())).toMatch(/^Permission denied:/);
+ expect(runWidgetsMock).toHaveBeenCalledOnce();
+ });
+
+ it('says OAP could not be asked, rather than that the caller lacks the permission', async () => {
+ const down = {
+ byId: async () => {
+ throw new ServiceLookupUnavailable(new Error('ETIMEDOUT'));
+ },
+ byName: async () => {
+ throw new ServiceLookupUnavailable(new Error('ETIMEDOUT'));
+ },
+ } as unknown as ServiceIdentityResolver;
+ const m = mockCtx(false);
+ const grants = ['metrics:read@GENERAL[agent]'];
+ (m.ctx as { access?: RequestAccess }).access = new RequestAccess(new SessionAccess(grants, undefined, facts), down);
+ const out = String(await byName(m.ctx).show_figure.invoke({ ...base, type: 'card', expressions: ['x'] }));
+ expect(out).toMatch(/not a permission problem/);
+ expect(runWidgetsMock).not.toHaveBeenCalled();
+ });
+
+ it('tells a plain role a name is unknown, as it always did', async () => {
+ const m = mockCtx(false);
+ (m.ctx as { access?: RequestAccess }).access = new RequestAccess(new SessionAccess(['logs:read'], undefined, facts), resolver);
+ const out = String(await byName(m.ctx).show_logs.invoke({ layer: 'GENERAL', service: 'agent::ghost' }));
+ expect(out).toMatch(/^Unknown service "agent::ghost"/);
+ });
+
+ it('answers alike for a service that does not exist and one of another group', async () => {
+ const gateway = { id: 'svc-2', name: 'agent::gateway', normal: true, group: 'other', layers: ['GENERAL'] };
+ const known = {
+ byId: async (id: string) => [songs, gateway].find((x) => x.id === id) ?? null,
+ byName: async (name: string) => [songs, gateway].filter((x) => x.name === name),
+ } as unknown as ServiceIdentityResolver;
+ const m = mockCtx(false);
+ const grants = ['logs:read@GENERAL[agent]', 'topology:read@GENERAL[agent]'];
+ (m.ctx as { access?: RequestAccess }).access = new RequestAccess(new SessionAccess(grants, undefined, facts), known);
+ const tools = byName(m.ctx);
+ const ghost = String(await tools.show_logs.invoke({ layer: 'GENERAL', service: 'agent::ghost' }));
+ const other = String(await tools.show_logs.invoke({ layer: 'GENERAL', service: 'agent::gateway' }));
+ expect(ghost).toMatch(/^Permission denied:/);
+ expect(ghost.replace('agent::ghost', 'X')).toBe(other.replace('agent::gateway', 'X'));
+ const two = String(await tools.show_topology.invoke({ layer: 'GENERAL', services: ['agent::songs', 'agent::ghost'] }));
+ const twoOther = String(await tools.show_topology.invoke({ layer: 'GENERAL', services: ['agent::songs', 'agent::gateway'] }));
+ expect(two.replace('agent::ghost', 'X')).toBe(twoOther.replace('agent::gateway', 'X'));
+ });
+
+ it('refuses a name the catalog does not know rather than querying it by name', async () => {
+ const m = limitedCtx(['metrics:read@GENERAL[agent]']);
+ const out = String(await byName(m.ctx).show_figure.invoke({ ...base, service: 'ghost', type: 'card', expressions: ['x'] }));
+ expect(out).toMatch(/^Permission denied:/);
+ expect(runWidgetsMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/bff/src/ai/lib/tools/visualization/tools.ts b/apps/bff/src/ai/lib/tools/visualization/tools.ts
index 8a0531c8..e91e7180 100644
--- a/apps/bff/src/ai/lib/tools/visualization/tools.ts
+++ b/apps/bff/src/ai/lib/tools/visualization/tools.ts
@@ -71,6 +71,8 @@ import { fetchLogs } from '../../../../http/query/log.js';
import { fetchBrowserErrors } from '../../../../http/query/browser-errors.js';
import { getServerOffsetMinutes, fmtSecond } from '../../../../util/window.js';
import { toolPrompt } from '../../skills/loader.js';
+import { decide, denied, graphConfig, holds, inexact, readableRow, refusal, tellsUnknownApart, unverifiable } from '../access.js';
+import { readsByNameOnly } from '../../../../rbac/request-access.js';
// Capture caps for the frozen triage lists — each is further clamped by the
// operator's `performance.limits.maxPageSize.*`.
@@ -268,16 +270,19 @@ function summarizeTopology(snap: TopologyResponse, focusId: string, service: str
return lines.join(' ') + edgeGapSummary(snap.calls, (id) => nodeById.get(id)?.name ?? id, gapDefs, 6);
}
+/** An endpoint id: `<serviceId>_<base64 name>`. */
+const ENDPOINT_ID = /^[A-Za-z0-9+/=]+\.[01]_./;
+
export function visualizationTools(ctx: ToolContext): StructuredToolInterface[] {
const catalog = () => serviceLayerCatalog({ config: ctx.config, fetch: ctx.fetch }).get();
async function render(type: DashboardWidgetType, input: RenderInput): Promise<string> {
- if (!ctx.hasVerb('metrics:read')) {
- return 'Permission denied: the current user lacks metrics:read.';
- }
+ if (!holds(ctx, 'metrics:read')) return denied('metrics:read');
// SkyWalking has no instance×endpoint scope: an Endpoint is measured across
// the whole service, a ServiceInstance across all its endpoints. Combining
// them returns empty — reject it so the model re-renders at one scope.
+ const bad = inexact(input.service);
+ if (bad) return bad;
if (input.instance && input.endpoint) {
return 'Invalid scope: SkyWalking has no instance×endpoint metric. An Endpoint is service-scoped (across all instances) and a ServiceInstance is service-scoped (across all endpoints) — they do not combine. Render at instance scope OR endpoint scope, not both.';
}
@@ -287,6 +292,10 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
// without it). Fall back to name-only if the catalog misses.
const cat = await catalog();
const row = (cat.byLayer.get(input.layer.toUpperCase()) ?? []).find((s) => s.name === input.service);
+ // A name the catalog does not know is still checked — as a name.
+ const byName = readsByNameOnly(input.expressions);
+ const no = await refusal(ctx, 'metrics:read', row && !byName ? { id: row.id } : { name: input.service }, `service ${input.service}`);
+ if (no) return no;
const scope: DashboardScope = input.instance ? 'instance' : input.endpoint ? 'endpoint' : 'service';
// Per-expression series labels: use the model's `labels` when given; else,
@@ -375,7 +384,9 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
endpoint?: string;
group?: string;
}): Promise<string> => {
- if (!ctx.hasVerb('metrics:read')) return 'Permission denied: the current user lacks metrics:read.';
+ if (!holds(ctx, 'metrics:read')) return denied('metrics:read');
+ const bad = inexact(service);
+ if (bad) return bad;
if (instance && endpoint) return 'Invalid scope: pass instance OR endpoint, not both.';
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
if (eff.blocked || !eff.template)
@@ -387,6 +398,12 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
if (widget.type === 'tab') return `"${widgetId}" is a tab container — pass one of its inner widget ids.`;
const cat = await catalog();
const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
+ const byName = readsByNameOnly([
+ ...(widget.expressions ?? []),
+ ...(widget.visibleWhen && 'expression' in widget.visibleWhen ? [widget.visibleWhen.expression] : []),
+ ]);
+ const no = await refusal(ctx, 'metrics:read', row && !byName ? { id: row.id } : { name: service }, `service ${service}`);
+ if (no) return no;
const { widgets } = await runWidgets(
[widget],
{
@@ -432,10 +449,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const hierarchyPrompt = toolPrompt('visualization', 'show_hierarchy');
const hierarchyTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'topology:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
const res = await getServiceHierarchy(ctx.config.current, row.id, layer, ctx.fetch);
// Order layers request-near → infra (level DESC), matching the topology
// overlay's top-to-bottom stack; unknown-level layers fall to the end.
@@ -491,7 +509,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const topologyPrompt = toolPrompt('visualization', 'show_topology');
const topologyTool = tool(
async ({ layer, service, services, depth, title }: { layer: string; service?: string; services?: string[]; depth?: number; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
const cat = await catalog();
// One name or several. The map seeds from a LIST of focus services at a
// BFS depth, so two services that call each other can be drawn in ONE
@@ -499,10 +517,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const wanted = (services?.length ? services : service ? [service] : []).map((n) => n.trim()).filter(Boolean);
if (!wanted.length) return 'Name at least one service, or use show_layer_topology for the whole layer.';
const inLayer = cat.byLayer.get(layer.toUpperCase()) ?? [];
- const rows = wanted.map((n) => inLayer.find((r) => r.name === n));
- const missing = wanted.filter((_, i) => !rows[i]);
- if (missing.length) {
- return `Unknown service(s) ${missing.map((m) => `"${m}"`).join(', ')} in layer ${layer}. Use list_services first.`;
+ const rows: typeof inLayer = [];
+ for (const n of wanted) {
+ const pick = await readableRow(ctx, 'topology:read', layer, n, inLayer);
+ if ('answer' in pick) return pick.answer;
+ rows.push(pick.row);
}
const row = rows[0]!;
// TWO hops by default, because this tool is for a SUBSET. One hop shows
@@ -549,7 +568,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
perf: ctx.config.current.performance,
window: ctx.window,
coldStage: false,
- cfg: topologyConfigFor(eff.template),
+ cfg: await graphConfig(ctx, 'topology:read', rows.map((r) => r!.id), topologyConfigFor(eff.template)),
layerKey: layer.toUpperCase(),
// Comma-joined ids: how the builder takes several seeds, and how the
// layer's own map page passes a roster selection.
@@ -610,7 +629,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const layerTopologyPrompt = toolPrompt('visualization', 'show_layer_topology');
const layerTopologyTool = tool(
async ({ layer, title }: { layer: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
+ // The whole-layer map seeds every service of the layer: a caller limited
+ // to some groups seeds only those.
+ const reach = ctx.access ? ctx.access.onLayer(['topology:read'], layer) : null;
+ if (ctx.access && !reach) return denied('topology:read', `layer ${layer.toUpperCase()}`);
const windowMinutes = Math.max(1, Math.round((ctx.range.endMs - ctx.range.startMs) / 60_000));
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
if (eff.blocked) {
@@ -621,12 +644,13 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
perf: ctx.config.current.performance,
window: ctx.window,
coldStage: false,
- cfg: topologyConfigFor(eff.template),
+ cfg: await graphConfig(ctx, 'topology:read', [], topologyConfigFor(eff.template)),
layerKey: layer.toUpperCase(),
// No seed ids: an empty serviceArg is what asks OAP for the whole layer,
// the same call the layer's own map page makes.
serviceArg: '',
depth: 1,
+ seedGroups: reach && !reach.whole ? reach.groups : undefined,
});
if (!snapshot.reachable) {
return `The ${layer.toUpperCase()} layer map is unreachable (${snapshot.error ?? 'no data'}).`;
@@ -684,10 +708,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const deploymentPrompt = toolPrompt('visualization', 'show_deployment');
const deploymentTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'topology:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
const windowMinutes = Math.max(1, Math.round((ctx.range.endMs - ctx.range.startMs) / 60_000));
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
if (eff.blocked) return `Deployment for ${service} is unavailable (template store unreachable).`;
@@ -698,7 +723,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
perf: ctx.config.current.performance,
window: ctx.window,
coldStage: false,
- cfg,
+ cfg: await graphConfig(ctx, 'topology:read', [row.id], cfg),
layerKey: layer.toUpperCase(),
serviceId: row.id,
});
@@ -742,13 +767,22 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const instanceTopologyPrompt = toolPrompt('visualization', 'show_instance_topology');
const instanceTopologyTool = tool(
async ({ layer, sourceService, destService, title }: { layer: string; sourceService: string; destService: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
const cat = await catalog();
const rows = cat.byLayer.get(layer.toUpperCase()) ?? [];
const client = rows.find((s) => s.name === sourceService);
- if (!client) return `Unknown source service "${sourceService}" in layer ${layer}. Use list_services first.`;
const server = rows.find((s) => s.name === destService);
- if (!server) return `Unknown dest service "${destService}" in layer ${layer}. Use list_services first.`;
+ const what = `services ${sourceService} and ${destService}`;
+ const opaque = `Permission denied: layer ${layer.toUpperCase()} has no call between ${what} the current user may read with topology:read. list_services shows the services it can.`;
+ if (!client || !server) {
+ if (!tellsUnknownApart(ctx, 'topology:read')) return opaque;
+ const [side, name] = !client ? ['source', sourceService] : ['dest', destService];
+ return `Unknown ${side} service "${name}" in layer ${layer}. Use list_services first.`;
+ }
+ // The instance map belongs to the call between the two services; the
+ // caller who reads either end may draw it.
+ const ends = [await decide(ctx, 'topology:read', { id: client.id }), await decide(ctx, 'topology:read', { id: server.id })];
+ if (!ends.includes('allow')) return ends.includes('unavailable') ? unverifiable(what) : opaque;
const windowMinutes = Math.max(1, Math.round((ctx.range.endMs - ctx.range.startMs) / 60_000));
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
if (eff.blocked) return `The instance map is unavailable (template store unreachable).`;
@@ -759,7 +793,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
perf: ctx.config.current.performance,
window: ctx.window,
coldStage: false,
- cfg,
+ cfg: await graphConfig(ctx, 'topology:read', [client.id, server.id], cfg),
layerKey: layer.toUpperCase(),
clientServiceId: client.id,
serverServiceId: server.id,
@@ -803,10 +837,16 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const endpointDependencyPrompt = toolPrompt('visualization', 'show_endpoint_dependency');
const endpointDependencyTool = tool(
async ({ layer, service, endpoint, title }: { layer: string; service: string; endpoint?: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('topology:read')) return 'Permission denied: the current user lacks topology:read.';
+ if (!holds(ctx, 'topology:read')) return denied('topology:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'topology:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
+ // The builder takes an endpoint id as it is, so an id must be one of
+ // THIS service's endpoints.
+ if (endpoint && ENDPOINT_ID.test(endpoint.trim()) && !endpoint.trim().startsWith(`${row.id}_`)) {
+ return denied('topology:read', `endpoint ${endpoint}, which is not an endpoint of ${service}`);
+ }
const windowMinutes = Math.max(1, Math.round((ctx.range.endMs - ctx.range.startMs) / 60_000));
const eff = await resolveEffectiveLayer(ctx.uiTemplateClient, layer);
if (eff.blocked) return `API dependency for ${service} is unavailable (template store unreachable).`;
@@ -818,7 +858,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
perf: ctx.config.current.performance,
window: ctx.window,
coldStage: false,
- cfg: endpointDependencyConfigFor(eff.template),
+ cfg: await graphConfig(ctx, 'topology:read', [row.id], endpointDependencyConfigFor(eff.template)),
layerKey: layer.toUpperCase(),
service: { id: row.id, name: row.name, normal: row.normal !== false },
endpointArg: endpoint ?? '',
@@ -868,10 +908,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const tracesPrompt = toolPrompt('visualization', 'show_traces');
const tracesTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('traces:read')) return 'Permission denied: the current user lacks traces:read.';
+ if (!holds(ctx, 'traces:read')) return denied('traces:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'traces:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
// Freeze the native list (frozen-always) so the block replays offline.
const windowMinutes = rangeWindowMinutes(ctx.range);
const offsetMinutes = await getServerOffsetMinutes(ctx.config, ctx.fetch);
@@ -937,7 +978,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const listZipkinServicesPrompt = toolPrompt('visualization', 'list_zipkin_services');
const listZipkinServicesTool = tool(
async ({ keyword }: { keyword?: string }): Promise<string> => {
- if (!ctx.hasVerb('traces:read')) return 'Permission denied: the current user lacks traces:read.';
+ if (!holds(ctx, 'traces:read')) return denied('traces:read');
const oap = ctx.config.current.oap;
let names: string[];
try {
@@ -970,7 +1011,7 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const zipkinTracesPrompt = toolPrompt('visualization', 'show_zipkin_traces');
const zipkinTracesTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('traces:read')) return 'Permission denied: the current user lacks traces:read.';
+ if (!holds(ctx, 'traces:read')) return denied('traces:read');
const oap = ctx.config.current.oap;
const zopts = { queryUrl: oap.zipkinUrl, timeoutMs: oap.timeoutMs, auth: oap.auth, fetch: ctx.fetch };
// Freeze the Zipkin list WITH spans so the waterfall replays offline.
@@ -1021,10 +1062,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const logsPrompt = toolPrompt('visualization', 'show_logs');
const logsTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('logs:read')) return 'Permission denied: the current user lacks logs:read.';
+ if (!holds(ctx, 'logs:read')) return denied('logs:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'logs:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
const maxLogs = Math.min(LIST_CAP, ctx.config.current.performance.limits.maxPageSize.logs);
// Logs query at SECOND step — format the window in SECOND (ctx.window is the
// chat's MINUTE-step string; mixing step + format throws verifyDateTimeString).
@@ -1067,10 +1109,11 @@ export function visualizationTools(ctx: ToolContext): StructuredToolInterface[]
const browserErrorsPrompt = toolPrompt('visualization', 'show_browser_logs');
const browserErrorsTool = tool(
async ({ layer, service, title }: { layer: string; service: string; title?: string }): Promise<string> => {
- if (!ctx.hasVerb('browser-errors:read')) return 'Permission denied: the current user lacks browser-errors:read.';
+ if (!holds(ctx, 'browser-errors:read')) return denied('browser-errors:read');
const cat = await catalog();
- const row = (cat.byLayer.get(layer.toUpperCase()) ?? []).find((s) => s.name === service);
- if (!row) return `Unknown service "${service}" in layer ${layer}. Use list_services first.`;
+ const pick = await readableRow(ctx, 'browser-errors:read', layer, service, cat.byLayer.get(layer.toUpperCase()) ?? []);
+ if ('answer' in pick) return pick.answer;
+ const { row } = pick;
const maxBrowser = Math.min(LIST_CAP, ctx.config.current.performance.limits.maxPageSize.browserLogs);
const beOffset = await getServerOffsetMinutes(ctx.config, ctx.fetch);
const beWindow = { start: fmtSecond(ctx.range.startMs, beOffset), end: fmtSecond(ctx.range.endMs, beOffset) };
diff --git a/apps/bff/src/ai/mcp/capture.ts b/apps/bff/src/ai/mcp/capture.ts
index 8cc47120..997c0ec8 100644
--- a/apps/bff/src/ai/mcp/capture.ts
+++ b/apps/bff/src/ai/mcp/capture.ts
@@ -30,6 +30,7 @@ import type { FetchLike, UITemplateClient } from '@skywalking-horizon-ui/api-cli
import type { ConfigSource } from '../../config/loader.js';
import { buildOapOpts } from '../../client/graphql.js';
import { sessionHasVerb, type VerbSubject } from '../../rbac/policy.js';
+import type { AccessDeps, RequestAccess } from '../../rbac/request-access.js';
import { defaultMinuteWindow, windowFromRange } from '../../util/window.js';
import { createGraphicCardBuffer } from '../lib/graphic-card-buffer.js';
import type { ToolContext } from '../lib/tool-context.js';
@@ -47,6 +48,9 @@ export interface CaptureDeps {
subject: VerbSubject;
/** OAP-server-local offset, resolved once by the caller (it needs a fetch). */
offsetMinutes: number;
+ access?: AccessDeps;
+ /** Built from `access` by the caller, which can await. */
+ requestAccess?: RequestAccess;
windowMinutes: number;
step: CaptureStep;
}
@@ -80,6 +84,7 @@ export function createCaptureContext(deps: CaptureDeps): CapturedRun {
range: { startMs, endMs, step: deps.step },
bulkSize: cfg.performance.bulk.dashboard.bulkSize,
hasVerb: (verb) => sessionHasVerb(cfg, deps.subject, verb),
+ access: deps.requestAccess,
...buffer,
// No activity line to paint: an MCP host shows its own tool-call status.
emitTool: () => {},
diff --git a/apps/bff/src/ai/mcp/route.ts b/apps/bff/src/ai/mcp/route.ts
index 16d907d8..605e8bec 100644
--- a/apps/bff/src/ai/mcp/route.ts
+++ b/apps/bff/src/ai/mcp/route.ts
@@ -35,11 +35,13 @@ import { requireAuth } from '../../user/middleware.js';
import { getServerOffsetMinutes } from '../../util/window.js';
import { SECURITY_HEADERS, API_CACHE_CONTROL } from '../../util/security-headers.js';
import { createMcpServer, surfaceFor } from './server.js';
+import type { AccessDeps } from '../../rbac/request-access.js';
export interface McpRouteDeps extends AuthDeps {
fetch?: FetchLike;
uiTemplateClient?: () => UITemplateClient;
version: string;
+ access?: AccessDeps;
}
/** JSON-RPC's own "you can't do that" shape — an MCP client parses this, where
@@ -172,6 +174,7 @@ export function registerMcpRoutes(app: FastifyInstance, deps: McpRouteDeps): voi
uiTemplateClient: deps.uiTemplateClient,
subject: req.session ?? { roles: [] },
offsetMinutes: needsTime ? await getServerOffsetMinutes(deps.config, deps.fetch) : 0,
+ access: deps.access,
},
surface,
deps.version,
diff --git a/apps/bff/src/ai/mcp/tools.ts b/apps/bff/src/ai/mcp/tools.ts
index fd0d6e0b..aedf420b 100644
--- a/apps/bff/src/ai/mcp/tools.ts
+++ b/apps/bff/src/ai/mcp/tools.ts
@@ -37,6 +37,7 @@ import { buildTools } from '../lib/registry.js';
import { rcaTools } from '../lib/tools/rca/tools.js';
import { createCaptureContext, type CaptureDeps, type CaptureStep } from './capture.js';
import { emitsCard } from '../lib/graphic-card.js';
+import { buildRequestAccess } from '../../rbac/request-access.js';
export interface McpToolDef {
name: string;
@@ -500,8 +501,10 @@ export async function callTool(
args: Record<string, unknown>,
): Promise<McpToolResult> {
const { windowMinutes, step, ...toolArgs } = args;
+ const requestAccess = deps.access ? await buildRequestAccess(deps.config.current, deps.subject, deps.access) : undefined;
const run = createCaptureContext({
...deps,
+ requestAccess,
// Enforce the bounds the schema ADVERTISES. A caller is a language model,
// which is exactly the kind of caller that sends a plausible-looking value
// outside the range it was given — and `> 0` accepted 1e15, which becomes a
diff --git a/apps/bff/src/http/query/alarms-baseline.test.ts b/apps/bff/src/http/query/alarms-baseline.test.ts
new file mode 100644
index 00000000..60c24a50
--- /dev/null
+++ b/apps/bff/src/http/query/alarms-baseline.test.ts
@@ -0,0 +1,125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * OAP evaluates an alarm rule's `baseline(...)` by the service NAME alone and
+ * keeps the values in the alarm's snapshot. A caller limited to some groups
+ * sees those values only when every service of that name is one it may read.
+ */
+
+import { describe, expect, it } from 'vitest';
+import Fastify from 'fastify';
+import cookie from '@fastify/cookie';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../../config/schema.js';
+import type { ConfigSource } from '../../config/loader.js';
+import { SessionStore } from '../../user/sessions.js';
+import { makeRouteAuthHook } from '../../rbac/route-policy.js';
+import { ServiceIdentityResolver, serviceIdOf } from '../../logic/services/service-identity.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from '../../logic/services/service-layer-catalog.js';
+import { _resetCapabilitiesCache } from '../../logic/oap/capabilities.js';
+import { registerAlarmsQueryRoutes } from './alarms.js';
+
+const NOW = 1_700_000_000_000;
+const NAME = 'payments::checkout';
+const real = { id: serviceIdOf(NAME, true), name: NAME, normal: true, group: 'payments' };
+const conjectured = { id: serviceIdOf(NAME, false), name: NAME, normal: false, group: 'payments' };
+
+const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } });
+
+let scope = 'Service';
+const fetch: FetchLike = async (_url, init) => {
+ const { query = '' } = JSON.parse(String(init?.body ?? '{}')) as { query?: string };
+ if (query.includes('__type')) return json({ data: { __type: { fields: [{ name: 'queryAlarms' }] } } });
+ if (query.includes('getTimeInfo')) return json({ data: { time: { timezone: '+0000' } } });
+ if (query.includes('queryAlarms')) {
+ const metric = { name: 'baseline', results: [{ metric: { labels: [] }, values: [{ id: '1', value: '42' }] }] };
+ return json({
+ data: {
+ queryAlarms: {
+ msgs: [
+ {
+ id: 'a-1', startTime: NOW - 60_000, recoveryTime: null, scope, name: scope === 'Service' ? NAME : `pod-1 of ${NAME}`,
+ message: 'above the predicted range', tags: [],
+ snapshot: { expression: 'service_resp_time > baseline(service_resp_time,upper)', metrics: [metric] },
+ },
+ ],
+ },
+ },
+ });
+ }
+ return json({ data: {} });
+};
+
+async function alarmsFor(withNamesake: boolean) {
+ _resetCapabilitiesCache();
+ const cfg = configSchema.parse({ rbac: { roles: { payments: ['alarms:read@GENERAL[payments]'] } } });
+ const config: ConfigSource = { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+ const snapshot: ServiceCatalog = {
+ layers: ['GENERAL', 'VIRTUAL_DATABASE'],
+ byLayer: new Map([
+ ['GENERAL', [real]],
+ ['VIRTUAL_DATABASE', withNamesake ? [conjectured] : []],
+ ]),
+ byName: new Map(),
+ };
+ const catalog = { get: async () => snapshot, allServices: async () => [] } as unknown as ServiceLayerCatalog;
+ const unknown: FetchLike = async () => json({ data: { service: null } });
+ const access = {
+ services: new ServiceIdentityResolver({ config, fetch: unknown, catalog }),
+ classify: async () => ({ isOperate: () => false }),
+ };
+ const sessions = new SessionStore({ ttlMinutes: 60 });
+ const app = Fastify();
+ await app.register(cookie);
+ app.addHook('onRoute', makeRouteAuthHook({ config, sessions, access }));
+ registerAlarmsQueryRoutes(app, { config, sessions, serviceLayer: catalog, fetch });
+ await app.ready();
+ const sid = sessions.create('pay', ['payments']).sid;
+ const res = await app.inject({
+ method: 'GET',
+ url: `/api/alarms?layer=GENERAL&service=${encodeURIComponent(NAME)}&normal=true&startTime=${NOW - 600_000}&endTime=${NOW}`,
+ headers: { cookie: `horizon_sid=${sid}` },
+ });
+ await app.close();
+ return { status: res.statusCode, body: res.json() as { msgs: Array<{ snapshot: { metrics: unknown[] } }> } };
+}
+
+describe('an alarm whose rule reads a baseline', () => {
+ it('keeps the snapshot values when no unreadable service shares the name', async () => {
+ const { status, body } = await alarmsFor(false);
+ expect(status).toBe(200);
+ expect(body.msgs[0]!.snapshot.metrics).toHaveLength(1);
+ });
+
+ it('withholds them from an instance alarm, whose lookup name is not a service\'s', async () => {
+ scope = 'ServiceInstance';
+ try {
+ const { body } = await alarmsFor(false);
+ expect(body.msgs[0]!.snapshot.metrics).toEqual([]);
+ } finally {
+ scope = 'Service';
+ }
+ });
+
+ it('withholds them when a namesake is outside the grant, and keeps the alarm', async () => {
+ const { status, body } = await alarmsFor(true);
+ expect(status).toBe(200);
+ expect(body.msgs).toHaveLength(1);
+ expect(body.msgs[0]!.snapshot.metrics).toEqual([]);
+ });
+});
diff --git a/apps/bff/src/http/query/alarms.ts b/apps/bff/src/http/query/alarms.ts
index 462d2d31..e6b62c00 100644
--- a/apps/bff/src/http/query/alarms.ts
+++ b/apps/bff/src/http/query/alarms.ts
@@ -71,6 +71,8 @@ import type {
ServiceCatalog,
ServiceLayerCatalog,
} from '../../logic/services/service-layer-catalog.js';
+import { readsByNameOnly } from '../../rbac/request-access.js';
+import { entityServiceName } from '../../logic/services/service-identity.js';
export interface AlarmsQueryRouteDeps extends AuthDeps {
/** Server-global service-by-layer index (shared with config/alarms.ts +
@@ -238,7 +240,7 @@ const COUNT_QUERY_ALARMS_QUERY = /* GraphQL */ `
`;
const LIST_SERVICES_QUERY = /* GraphQL */ `
query HorizonAlarmServices($layer: String!) {
- listServices(layer: $layer) { id name normal }
+ listServices(layer: $layer) { id name normal group }
}
`;
@@ -249,7 +251,7 @@ interface QueryAlarmsRaw {
queryAlarms?: { msgs?: AlarmMessage[] } | null;
}
interface ListServicesRaw {
- listServices: Array<{ id: string; name: string; normal: boolean | null }>;
+ listServices: Array<{ id: string; name: string; normal: boolean | null; group?: string | null }>;
}
/** Window cap for `/api/alarms` and `/api/alarms/count`. Defence-in-
@@ -352,6 +354,11 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
/* One page of raw alarm rows for a given paging pair. Handed to the shared
* over-fetch seam, which asks for one row more than the page displays so
* `truncated` is exact instead of a `length >= pageSize` guess. */
+ // The legacy query takes no service, so it cannot keep a layer-limited
+ // caller to their own services: it would answer with every alarm.
+ if (!caps.queryAlarms && req.access?.layerLimited(['alarms:read'])) {
+ return reply.code(403).send({ error: 'permission_denied', verb: 'alarms:read', reason: 'alarm_filter_unsupported' });
+ }
const fetchAlarms = async (paging: OapPaging): Promise<AlarmMessage[]> => {
if (caps.queryAlarms) {
/* New-mode condition. `entities` + `layer` ride server-side;
@@ -394,7 +401,25 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
});
}
- const tagged = tagWithLayer(page.rows, catalog);
+ let tagged = tagWithLayer(page.rows, catalog);
+ // A `baseline` in the rule was looked up by the alarm entity's NAME alone,
+ // and its values ride in the snapshot: a caller limited to some groups
+ // sees them only when every service of that name is readable. Only a
+ // Service alarm's name is a service's; the others are composite.
+ const byName = (m: AlarmMessage) => readsByNameOnly([m.snapshot?.expression ?? '']);
+ const access = req.access;
+ if (access?.layerLimited(['alarms:read']) && tagged.some(byName)) {
+ const readable = new Map<string, boolean>();
+ const keeps = async (m: AlarmMessage): Promise<boolean> => {
+ if (m.scope !== 'Service') return false;
+ const name = entityServiceName(m.name);
+ if (!readable.has(name)) readable.set(name, (await access.decide(['alarms:read'], { name })) === 'allow');
+ return readable.get(name)!;
+ };
+ const out: typeof tagged = [];
+ for (const m of tagged) out.push(byName(m) && !(await keeps(m)) ? { ...m, snapshot: { ...m.snapshot, metrics: [] } } : m);
+ tagged = out;
+ }
const body: AlarmsResponse = {
returned: tagged.length,
@@ -508,9 +533,11 @@ export function registerAlarmsQueryRoutes(app: FastifyInstance, deps: AlarmsQuer
const opts = buildOapOpts(deps.config.current, deps.fetch, signal);
try {
const got = await graphqlPost<ListServicesRaw>(opts, LIST_SERVICES_QUERY, { layer });
- const services = (got.listServices ?? [])
+ const listed = (got.listServices ?? [])
.filter((s) => typeof s?.name === 'string' && s.name.length > 0)
.sort((a, b) => a.name.localeCompare(b.name));
+ const access = req.access;
+ const services = access ? access.filterRoster(['alarms:read'], layer, listed) : listed;
return reply.send({ layer, services });
} catch (err) {
return reply.code(502).send({
diff --git a/apps/bff/src/http/query/browser-errors.ts b/apps/bff/src/http/query/browser-errors.ts
index 4f17121e..5c74b47d 100644
--- a/apps/bff/src/http/query/browser-errors.ts
+++ b/apps/bff/src/http/query/browser-errors.ts
@@ -267,6 +267,15 @@ export function registerBrowserErrorsRoute(app: FastifyInstance, deps: BrowserEr
} satisfies BrowserErrorsResponse);
}
const serviceId = scope.kind === 'service' ? scope.service.id : null;
+ // Only the browser receiver writes these rows, so they all belong to
+ // BROWSER services — filed under a name OAP may have shortened, which the
+ // row does not carry. A list across every service is therefore that
+ // layer's, read whole or not at all.
+ if (!serviceId && req.access && !req.access.onLayer(['browser-errors:read'], 'BROWSER')?.whole) {
+ return reply
+ .code(403)
+ .send({ error: 'permission_denied', verb: 'browser-errors:read', reason: 'layer_not_granted', layer: 'BROWSER' });
+ }
const res = await fetchBrowserErrors(
opts,
diff --git a/apps/bff/src/http/query/continuous-profiling.ts b/apps/bff/src/http/query/continuous-profiling.ts
index 1f7acdd0..9171d6c0 100644
--- a/apps/bff/src/http/query/continuous-profiling.ts
+++ b/apps/bff/src/http/query/continuous-profiling.ts
@@ -262,7 +262,11 @@ export function registerContinuousProfilingRoutes(
const opts = buildOapOpts(deps.config.current, deps.fetch);
try {
const snap = await catalog.get();
- const summary = await policySummaryForServices(opts, snap.byLayer.get(q.layer.toUpperCase()) ?? []);
+ const roster = snap.byLayer.get(q.layer.toUpperCase()) ?? [];
+ const readable = req.access
+ ? await req.access.keepReadable(['profile:read'], req.access.filterRoster(['profile:read'], q.layer, roster), (s) => ({ id: s.id }))
+ : roster;
+ const summary = await policySummaryForServices(opts, readable);
payload.services = summary.rows;
payload.checked = summary.checked;
payload.total = summary.total;
diff --git a/apps/bff/src/http/query/dashboard.ts b/apps/bff/src/http/query/dashboard.ts
index d10f7afb..e1715371 100644
--- a/apps/bff/src/http/query/dashboard.ts
+++ b/apps/bff/src/http/query/dashboard.ts
@@ -55,6 +55,8 @@ import { defaultWidgetsFor } from '../../logic/dashboard/defaults.js';
import { bodySchema, MAX_REQUEST_WIDGETS } from '../../logic/dashboard/schema.js';
import { flattenTabWidgets } from '../../logic/dashboard/gates.js';
import { runWidgets } from '../../logic/dashboard/run.js';
+import { readsByNameOnly, type ServiceRef } from '../../rbac/request-access.js';
+import { entityServiceName } from '../../logic/services/service-identity.js';
export interface DashboardRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -199,7 +201,8 @@ export function registerDashboardQueryRoute(app: FastifyInstance, deps: Dashboar
type PickRow = { id: string; name: string; normal: boolean | null; group?: string | null };
const pick = (all: PickRow[]): PickRow | undefined => {
if (serviceName) return all.find((s) => s.name === serviceName) ?? all.find((s) => s.id === serviceName);
- const inGroup = group === undefined ? all : all.filter((s) => (s.group ?? '') === group);
+ const readable = req.access ? req.access.filterRoster(['metrics:read'], layerKey, all) : all;
+ const inGroup = group === undefined ? readable : readable.filter((s) => (s.group ?? '') === group);
return inGroup[0];
};
let picked = pick((await serviceLayerCatalog(deps).get()).byLayer.get(layerKey.toUpperCase()) ?? []);
@@ -217,6 +220,11 @@ export function registerDashboardQueryRoute(app: FastifyInstance, deps: Dashboar
widgets: widgets.map((w) => ({ id: w.id, error: 'oap unreachable' })),
});
}
+ // To a caller limited to some groups, a named service that is not in
+ // the layer answers as one of another group does.
+ if (!picked && serviceName && req.access?.layerLimited(['metrics:read'])) {
+ return reply.code(403).send({ error: 'permission_denied', verb: 'metrics:read', reason: 'service_not_granted' });
+ }
if (!picked) {
return reply.send({
...baseResp,
@@ -227,6 +235,25 @@ export function registerDashboardQueryRoute(app: FastifyInstance, deps: Dashboar
});
}
}
+ // The caller must be able to read the service the widgets read — and,
+ // for `baseline`, every service its name can mean. Decided through the
+ // resolver, not the roster row: a roster kept through a failed refresh is
+ // display data, not current membership.
+ const expressions = widgets.flatMap((w) => [
+ ...(w.expressions ?? []),
+ ...(w.visibleWhen && 'expression' in w.visibleWhen ? [w.visibleWhen.expression] : []),
+ ]);
+ const refs: ServiceRef[] = [{ id: picked.id }, ...(readsByNameOnly(expressions) ? [{ name: entityServiceName(picked.name) }] : [])];
+ const access = req.access;
+ const decisions = access ? await Promise.all(refs.map((ref) => access.decide(['metrics:read'], ref))) : [];
+ for (const d of decisions) {
+ if (d === 'unavailable') {
+ return reply.code(503).send({ error: 'oap_unreachable', message: 'OAP did not answer who owns the service this request reads' });
+ }
+ if (d === 'deny') {
+ return reply.code(403).send({ error: 'permission_denied', verb: 'metrics:read', reason: 'service_not_granted' });
+ }
+ }
serviceName = picked.name;
serviceId = picked.id;
normal = picked.normal !== false;
@@ -277,7 +304,7 @@ export function registerDashboardQueryRoute(app: FastifyInstance, deps: Dashboar
const { widgets: results, reachable } = await runWidgets(
widgets,
{
- service: serviceName,
+ service: entityServiceName(serviceName),
serviceId: serviceId || undefined,
instance: selectedInstance,
endpoint: selectedEndpoint,
diff --git a/apps/bff/src/http/query/deployment.ts b/apps/bff/src/http/query/deployment.ts
index 20cf1f86..1c494478 100644
--- a/apps/bff/src/http/query/deployment.ts
+++ b/apps/bff/src/http/query/deployment.ts
@@ -132,7 +132,7 @@ export function registerDeploymentRoute(
perf: cfgCurrent.performance,
window,
coldStage: !!req.coldStage,
- cfg,
+ cfg: req.access ? await req.access.graphConfig(['topology:read'], [serviceId], cfg) : cfg,
layerKey,
serviceId,
});
diff --git a/apps/bff/src/http/query/ebpf.ts b/apps/bff/src/http/query/ebpf.ts
index ea43c900..2677298e 100644
--- a/apps/bff/src/http/query/ebpf.ts
+++ b/apps/bff/src/http/query/ebpf.ts
@@ -60,6 +60,7 @@ import { serviceScopeOf } from '../../logic/oap/service-scope.js';
import { processTopologyConfigFor, type ProcessTopologyConfig } from '../../logic/layers/loader.js';
import { parsePreviewProcessTopology } from '../../logic/layers/preview.js';
import { resolveEffectiveLayer } from '../../logic/layers/effective.js';
+import { entityServiceName, serviceIdOf } from '../../logic/services/service-identity.js';
export interface EBPFRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -331,11 +332,11 @@ function processRelationFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(expr)},\n` +
` entity: {` +
- ` serviceName: ${JSON.stringify(src.serviceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(src.serviceName))},` +
` normal: ${src.normal === false ? 'false' : 'true'},` +
` serviceInstanceName: ${JSON.stringify(src.serviceInstanceName)},` +
` processName: ${JSON.stringify(src.processName)},` +
- ` destServiceName: ${JSON.stringify(dst.serviceName)},` +
+ ` destServiceName: ${JSON.stringify(entityServiceName(dst.serviceName))},` +
` destNormal: ${dst.normal === false ? 'false' : 'true'},` +
` destServiceInstanceName: ${JSON.stringify(dst.serviceInstanceName)},` +
` destProcessName: ${JSON.stringify(dst.processName)} },\n` +
@@ -403,6 +404,17 @@ async function queryEbpfTasksBothTriggers(
return [...fixed, ...continuous].sort((a, b) => (b.taskStartTime ?? 0) - (a.taskStartTime ?? 0));
}
+/** A schedule id names no service; its process does. Keep the schedules
+ * whose process belongs to a service the caller may read. */
+async function readableSchedules<T extends { process?: { serviceId?: string | null } | null }>(
+ req: FastifyRequest,
+ schedules: T[],
+): Promise<T[]> {
+ const access = req.access;
+ if (!access) return schedules;
+ return access.keepReadable(['profile:read'], schedules, (s) => ({ id: s.process?.serviceId ?? '' }));
+}
+
export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): void {
const auth = requireAuth(deps);
@@ -507,7 +519,7 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
QUERY_EBPF_SCHEDULES,
{ taskId: params.taskId },
);
- payload.schedules = data.eBPFSchedules ?? [];
+ payload.schedules = await readableSchedules(req, data.eBPFSchedules ?? []);
return reply.send(payload);
} catch (err) {
return reply.send(softErr(payload, err));
@@ -782,6 +794,10 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
endMs = Date.now();
startMs = endMs - minutes * 60_000;
}
+ const focus = [src, dst]
+ .filter((e) => typeof e.serviceName === 'string')
+ .map((e) => serviceIdOf(e.serviceName, e.normal !== false));
+ const edgeMetrics = resolveEdgeMetrics(req.access ? await req.access.graphConfig(['profile:read'], focus, cfg) : cfg);
// Match the network-topology route's OAP-local formatting so the
// edge metrics window lines up with the rendered graph window.
const offset = await getServerOffsetMinutes(deps.config, deps.fetch);
@@ -790,7 +806,7 @@ export function registerEBPFRoutes(app: FastifyInstance, deps: EBPFRouteDeps): v
// Build one aliased execExpression per metric across both sides.
const aliasMap = new Map<string, { side?: 'client' | 'server'; metric: TopologyMetricDef }>();
const fragments: string[] = [];
- resolveEdgeMetrics(cfg).forEach((m, i) => {
+ edgeMetrics.forEach((m, i) => {
const alias = `m_${i}`;
aliasMap.set(alias, { ...(m.side ? { side: m.side } : {}), metric: m });
fragments.push(processRelationFragment(alias, m.mqe, src, dst, w, false));
diff --git a/apps/bff/src/http/query/endpoint-dependency.ts b/apps/bff/src/http/query/endpoint-dependency.ts
index e0a59a70..3667a5c7 100644
--- a/apps/bff/src/http/query/endpoint-dependency.ts
+++ b/apps/bff/src/http/query/endpoint-dependency.ts
@@ -143,7 +143,7 @@ export function registerEndpointDependencyRoute(
perf: cfgCurrent.performance,
window,
coldStage: !!req.coldStage,
- cfg: epCfg,
+ cfg: req.access ? await req.access.graphConfig(['topology:read'], [service.id], epCfg) : epCfg,
layerKey,
service,
endpointArg,
diff --git a/apps/bff/src/http/query/evaluation-record.ts b/apps/bff/src/http/query/evaluation-record.ts
index 4c08fdd2..fe868a4a 100644
--- a/apps/bff/src/http/query/evaluation-record.ts
+++ b/apps/bff/src/http/query/evaluation-record.ts
@@ -45,6 +45,7 @@ import { withColdStage } from '../../util/duration.js';
import { fmtSecond, getServerOffsetMinutes } from '../../util/window.js';
import { readPage, type PagedQuerySpec } from '../../logic/paging/read-page.js';
import { serviceLayerCatalog } from '../../logic/services/service-layer-catalog.js';
+import { ServiceLookupUnavailable } from '../../logic/services/service-identity.js';
export interface EvaluationRecordRouteDeps {
config: ConfigSource;
@@ -343,14 +344,25 @@ export function registerEvaluationRecordRoute(app: FastifyInstance, deps: Evalua
app.get(
'/api/evaluation-record/caller-services',
{ preHandler: auth },
- async (_req: FastifyRequest, reply: FastifyReply) => {
+ async (req: FastifyRequest, reply: FastifyReply) => {
const snapshot = await catalog.get();
+ const all = await catalog.allServices();
+ let readable = all;
+ if (req.access) {
+ try {
+ readable = await req.access.keepReadable(['logs:read'], all, (s) => ({ id: s.id }));
+ } catch (err) {
+ if (!(err instanceof ServiceLookupUnavailable)) throw err;
+ return reply.send({ reachable: false, services: [], error: err.message });
+ }
+ }
return reply.send({
reachable: snapshot.unreachable !== true,
- services: (await catalog.allServices()).map((service) => ({
- id: service.id, name: service.name, normal: service.normal,
- group: service.group, layer: service.layer,
- })),
+ services: readable
+ .map((service) => ({
+ id: service.id, name: service.name, normal: service.normal,
+ group: service.group, layer: service.layer,
+ })),
});
},
);
diff --git a/apps/bff/src/http/query/events.ts b/apps/bff/src/http/query/events.ts
index 48475a01..c8759992 100644
--- a/apps/bff/src/http/query/events.ts
+++ b/apps/bff/src/http/query/events.ts
@@ -48,6 +48,7 @@ import {
type PagedQuerySpec,
} from '../../logic/paging/read-page.js';
import { fmtSecond, getServerOffsetMinutes } from '../../util/window.js';
+import { ServiceLookupUnavailable } from '../../logic/services/service-identity.js';
export interface EventsRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -235,6 +236,11 @@ export function registerEventsRoute(app: FastifyInstance, deps: EventsRouteDeps)
const auth = requireAuth(deps);
app.post('/api/events', { preHandler: auth }, async (req: FastifyRequest, reply: FastifyReply) => {
const body = (req.body ?? {}) as EventsQueryRequest;
+ // The body's layer selects which events OAP reads, the way a URL's layer
+ // does elsewhere.
+ if (body.layer && req.access && !req.access.onLayer(['events:read'], body.layer)) {
+ return reply.code(403).send({ error: 'permission_denied', verb: 'events:read', reason: 'layer_not_granted', layer: body.layer });
+ }
const opts = buildOapOpts(deps.config.current, deps.fetch);
const offset = await getServerOffsetMinutes(deps.config, deps.fetch);
const window = resolveWindow(offset, body.windowMinutes, { startMs: body.startMs, endMs: body.endMs });
@@ -261,13 +267,23 @@ export function registerEventsRoute(app: FastifyInstance, deps: EventsRouteDeps)
false,
);
+ let events = res.events;
+ if (!body.service && req.access) {
+ try {
+ events = await req.access.keepReadable(['events:read'], res.events, (e) => ({ name: e.source?.service ?? '' }));
+ } catch (err) {
+ if (!(err instanceof ServiceLookupUnavailable)) throw err;
+ const empty = { generatedAt: Date.now(), query: body, pageNum, pageSize, hasNext: false, events: [] };
+ return reply.send({ ...empty, reachable: false, error: err.message } satisfies EventsResponse);
+ }
+ }
return reply.send({
generatedAt: Date.now(),
query: body,
pageNum,
pageSize,
hasNext: res.hasNext,
- events: res.events,
+ events,
reachable: res.reachable,
...(res.error ? { error: res.error } : {}),
} satisfies EventsResponse);
diff --git a/apps/bff/src/http/query/infra-3d-metrics.ts b/apps/bff/src/http/query/infra-3d-metrics.ts
index 18b84e00..2e282307 100644
--- a/apps/bff/src/http/query/infra-3d-metrics.ts
+++ b/apps/bff/src/http/query/infra-3d-metrics.ts
@@ -51,6 +51,7 @@ import {
windowFromRange,
type Window,
} from '../../util/window.js';
+import { entityServiceName } from '../../logic/services/service-identity.js';
export interface Infra3dMetricsDeps extends AuthDeps {
fetch?: FetchLike;
@@ -113,7 +114,7 @@ function buildFragment(
return (
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(s.mqe)},\n` +
- ` entity: { scope: Service, serviceName: ${JSON.stringify(s.name)}, normal: ${s.normal ? 'true' : 'false'} },\n` +
+ ` entity: { scope: Service, serviceName: ${JSON.stringify(entityServiceName(s.name))}, normal: ${s.normal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${cold} }\n` +
` ) { type error results { values { value } } }`
);
diff --git a/apps/bff/src/http/query/instance-topology.ts b/apps/bff/src/http/query/instance-topology.ts
index 1e8f89a1..1dc7005a 100644
--- a/apps/bff/src/http/query/instance-topology.ts
+++ b/apps/bff/src/http/query/instance-topology.ts
@@ -137,7 +137,7 @@ export function registerInstanceTopologyRoute(
perf: cfgCurrent.performance,
window,
coldStage: !!req.coldStage,
- cfg: instCfg,
+ cfg: req.access ? await req.access.graphConfig(['topology:read'], [clientServiceId, serverServiceId], instCfg) : instCfg,
layerKey,
clientServiceId,
serverServiceId,
diff --git a/apps/bff/src/http/query/landing.ts b/apps/bff/src/http/query/landing.ts
index 1d814524..ed23639d 100644
--- a/apps/bff/src/http/query/landing.ts
+++ b/apps/bff/src/http/query/landing.ts
@@ -57,12 +57,16 @@ import {
type ScanFn,
} from '../../logic/layers/header-kpi-cache.js';
import { expressionForServiceMetricSeries } from '../../util/mqe-catalog.js';
+import { overviewExpressionsForLayer } from '../../logic/overview/effective.js';
+import { sessionHasVerb } from '../../rbac/policy.js';
import {
defaultMinuteWindow,
getServerOffsetMinutes,
windowFromRange,
type Window,
} from '../../util/window.js';
+import { readsByNameOnly } from '../../rbac/request-access.js';
+import { entityServiceName } from '../../logic/services/service-identity.js';
export interface LandingRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -270,7 +274,7 @@ function buildMqeFragment(aliasName: string, m: MqeRequest, w: Window, coldStage
return (
`${aliasName}: execExpression(\n` +
` expression: ${JSON.stringify(m.expression)},\n` +
- ` entity: { scope: Service, serviceName: ${JSON.stringify(m.serviceName)}, normal: ${m.normal ? 'true' : 'false'} },\n` +
+ ` entity: { scope: Service, serviceName: ${JSON.stringify(entityServiceName(m.serviceName))}, normal: ${m.normal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
` ) { type error results { values { value } } }`
);
@@ -336,9 +340,10 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
// column of dashes.
//
// It is NOT an authorization boundary. Whether a caller may query metrics
- // at all is the RBAC query verb's decision; this is template analysis, and
- // the same request may carry any `mqe` it likes without passing through
- // here. So it runs only where there is something to check against — a
+ // at all is the RBAC query verb's decision; this is template analysis. A
+ // per-service column may carry any `mqe` it likes — it is evaluated per
+ // service the caller may read — and a self-aggregating one is bounded
+ // separately below. So this runs only where there is something to check against — a
// layer whose template could not be read refuses nothing, since refusing
// would cost real callers a working page during a template-store outage
// and withhold nothing from anyone.
@@ -408,6 +413,15 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
// only the first group asked for, and every other group would read its
// own services as absent for the rest of that hour.
layerRoster = services;
+ if (req.access) {
+ const access = req.access;
+ // The roster names a service in `value`; the blank-name rule reads `name`.
+ services = access.filterRoster(['metrics:read'], layerKey, services.map((s) => ({ ...s, name: s.value })));
+ // `baseline` is looked up by name, so every service of the name must be readable.
+ if (readsByNameOnly(cfg.columns.map((c) => c.mqe ?? ''))) {
+ services = await access.keepReadable(['metrics:read'], services, (s) => ({ name: entityServiceName(s.value) }));
+ }
+ }
// Optional `?group=` (split-by-service-group menu entry) — narrow
// the roster to that OAP Service.group before the top-N rollup.
const group = (req.query as { group?: string }).group;
@@ -473,8 +487,25 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
column: c,
expression: resolveMqe(c.metric, c.mqe, layerKey),
}));
+ // A self-aggregating column reads the metric across every service, so it
+ // runs only for a caller who reads the whole layer, and only when a
+ // stored overview declares it (or it names a declared header metric,
+ // checked above). A refused column is simply absent from `aggregates`.
+ const wholeLayer = !req.access || !req.access.layerLimited(['metrics:read']);
+ const overviewDeclared = wholeLayer
+ ? await overviewExpressionsForLayer(deps.uiTemplateClient, layerKey)
+ : new Set<string>();
+ for (const c of declared ?? []) if (c.mqe) overviewDeclared.add(c.mqe);
+ // An overview author previews a draft that no stored template holds yet.
+ const runsDrafts = !!req.session && sessionHasVerb(deps.config.current, req.session, 'overview-template:write');
const aggResolved = allResolved
- .filter((r) => r.column.selfAggregate === true && r.expression !== null)
+ .filter(
+ (r) =>
+ r.column.selfAggregate === true &&
+ r.expression !== null &&
+ wholeLayer &&
+ (!r.column.mqe || runsDrafts || overviewDeclared.has(r.column.mqe)),
+ )
.map((r) => ({
column: r.column,
expression: (r.expression as string).replace(/\{\{\s*topn\s*\}\}/g, String(overviewTopN)),
@@ -921,7 +952,13 @@ export function registerLandingRoute(app: FastifyInstance, deps: LandingRouteDep
// own reads, plus the scan behind whichever bucket answered the header.
// Charging only the live reads meant an hour whose scan lost a batch was
// reported as sound on every request but the one that filled it.
- const bucketBatches = kpiRead?.bucket?.batches ?? { total: 0, failed: 0 };
+ const scanned = kpiRead?.bucket?.batches ?? { total: 0, failed: 0 };
+ // The hour's scan spans every group of the layer, so a caller limited to
+ // some of them learns only whether it was partial, not its size.
+ const bucketBatches =
+ req.access?.layerLimited(['metrics:read']) && scanned.total > 0
+ ? { total: 1, failed: scanned.failed > 0 ? 1 : 0 }
+ : scanned;
const failedAll = requestAcct.failed + bucketBatches.failed;
const metricsPartial =
failedAll > 0
diff --git a/apps/bff/src/http/query/log.ts b/apps/bff/src/http/query/log.ts
index 94aa28a4..849ba389 100644
--- a/apps/bff/src/http/query/log.ts
+++ b/apps/bff/src/http/query/log.ts
@@ -51,6 +51,7 @@ import {
} from '../../logic/paging/read-page.js';
import { withColdStage } from '../../util/duration.js';
import { fmtSecond, getServerOffsetMinutes } from '../../util/window.js';
+import { ServiceLookupUnavailable } from '../../logic/services/service-identity.js';
export interface LogRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -296,6 +297,16 @@ export function registerLogRoute(app: FastifyInstance, deps: LogRouteDeps): void
paging,
!!req.coldStage,
);
+ // A read across every service keeps only the services this caller may
+ // read — for a plain grant that leaves out the Platform monitoring ones.
+ if (!serviceId && req.access) {
+ try {
+ res.logs = await req.access.keepReadable(['logs:read'], res.logs, (r) => ({ id: r.serviceId ?? '' }));
+ } catch (err) {
+ if (!(err instanceof ServiceLookupUnavailable)) throw err;
+ return reply.send({ ...res, logs: [], hasNext: false, reachable: false, error: err.message, query: body } satisfies LogsResponse);
+ }
+ }
// Echo the operator's query (the shared helper returns an empty
// echo since it's entity-agnostic).
return reply.send({ ...res, query: body } satisfies LogsResponse);
@@ -363,7 +374,10 @@ export function registerLogRoute(app: FastifyInstance, deps: LogRouteDeps): void
pageNum: 1,
pageSize: sampleSize,
});
- const rows = sample.rows;
+ const rows =
+ !serviceId && req.access
+ ? await req.access.keepReadable(['logs:read'], sample.rows, (r) => ({ id: r.serviceId ?? '' }))
+ : sample.rows;
const level: LogFacetsResponse['level'] = { error: 0, warn: 0, info: 0, debug: 0, other: 0 };
const svcMap = new Map<string, number>();
for (const r of rows) {
diff --git a/apps/bff/src/http/query/map-service-identity.test.ts b/apps/bff/src/http/query/map-service-identity.test.ts
index 7797f228..1ddb6995 100644
--- a/apps/bff/src/http/query/map-service-identity.test.ts
+++ b/apps/bff/src/http/query/map-service-identity.test.ts
@@ -209,15 +209,17 @@ describe('API dependency takes the whole roster row', () => {
expect(oap.asked('getEndpointDependencies')).toHaveLength(0);
});
- it('finds the endpoint by the id and builds the entity from the name + flag, with no roster lookup', async () => {
+ it('finds the endpoint by the id and builds the entity from the id\'s flag, with no roster lookup', async () => {
const oap = fakeOap();
+ // A real service's id with `normal=false` beside it: the flag would name
+ // its conjectured namesake, which is not the service that was checked.
const { status } = await get(registerEndpointDependencyRoute, oap.fetch, url(`${PAIR}&normal=false`));
expect(status).toBe(200);
expect(oap.asked('findEndpoint')[0]?.variables.serviceId).toBe(SERVICE_ID);
expect(oap.asked('listServices')).toHaveLength(0);
const metrics = oap.calls.find((c) => c.query.includes('execExpression'));
expect(metrics?.query).toContain(`serviceName: "${SERVICE_NAME}"`);
- expect(metrics?.query).toContain('normal: false');
+ expect(metrics?.query).toContain('normal: true');
});
});
diff --git a/apps/bff/src/http/query/menu-access.test.ts b/apps/bff/src/http/query/menu-access.test.ts
new file mode 100644
index 00000000..71814a59
--- /dev/null
+++ b/apps/bff/src/http/query/menu-access.test.ts
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The sidebar follows the verbs. A session with no layer grant sees the menu
+ * it always did — minus the operate layers, which were only ever hidden in
+ * the browser — and a session with layer grants sees the layers and group
+ * entries they reach, counted accordingly.
+ */
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import Fastify, { type FastifyInstance } from 'fastify';
+import cookie from '@fastify/cookie';
+import type { FetchLike, MenuResponse, UITemplateClient, UITemplateRow } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../../config/schema.js';
+import type { ConfigSource } from '../../config/loader.js';
+import { SessionStore } from '../../user/sessions.js';
+import { makeRouteAuthHook } from '../../rbac/route-policy.js';
+import { buildEnvelope, serializeEnvelope } from '../../logic/templates/names.js';
+import { invalidateSyncCache } from '../../logic/templates/sync.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from '../../logic/services/service-layer-catalog.js';
+import { ServiceIdentityResolver } from '../../logic/services/service-identity.js';
+import { registerMenuRoute } from './menu.js';
+
+const ROLES = {
+ viewer: ['metrics:read'],
+ maintainer: ['metrics:read', 'cluster:read'],
+ payments: ['metrics:read@GENERAL[payments]'],
+ bdb: ['metrics:read@BANYANDB'],
+ alarmsOnly: ['alarms:read', 'metrics:read@GENERAL[payments]'],
+ everyPage: ['metrics:read', 'traces:read', 'logs:read', 'topology:read'],
+};
+
+const snapshot: ServiceCatalog = {
+ layers: ['GENERAL', 'BANYANDB'],
+ byLayer: new Map([
+ [
+ 'GENERAL',
+ [
+ { id: 'a.1', name: 'payments::a', normal: true, group: 'payments' },
+ { id: 'b.1', name: 'payments::b', normal: true, group: 'payments' },
+ { id: 'c.1', name: 'risk::c', normal: true, group: 'risk' },
+ ],
+ ],
+ ['BANYANDB', [{ id: 'd.1', name: 'showcase-banyandb', normal: true, group: '' }]],
+ ]),
+ byName: new Map(),
+};
+
+const oapQuery: FetchLike = async () =>
+ new Response(
+ JSON.stringify({ data: { layers: ['GENERAL', 'BANYANDB'], levels: [] } }),
+ { status: 200, headers: { 'content-type': 'application/json' } },
+ );
+
+const layerRow = (key: string, extra: Record<string, unknown>): UITemplateRow =>
+ ({
+ id: key,
+ disabled: false,
+ configuration: serializeEnvelope(
+ buildEnvelope('layer', key, { key, alias: key, slots: { services: 'Services' }, components: { service: true }, ...extra }),
+ ),
+ }) as UITemplateRow;
+
+const store = [
+ layerRow('GENERAL', {
+ splitByServiceGroup: true,
+ components: { service: true, instances: true, topology: true, traces: true, logs: true },
+ }),
+ layerRow('BANYANDB', { visibility: 'operate' }),
+];
+
+const templateClient = (): UITemplateClient =>
+ ({
+ list: async () => store.map((r) => ({ ...r })),
+ create: () => Promise.reject(new Error('read only')),
+ update: () => Promise.reject(new Error('read only')),
+ disable: () => Promise.reject(new Error('read only')),
+ }) as unknown as UITemplateClient;
+
+let app: FastifyInstance | null = null;
+beforeEach(() => invalidateSyncCache());
+afterEach(async () => {
+ await app?.close();
+ app = null;
+});
+
+async function menuFor(role: keyof typeof ROLES): Promise<Array<{ key: string; serviceCount: number }>> {
+ return (await menuEntries(role)).map(({ key, serviceCount }) => ({ key, serviceCount }));
+}
+
+async function menuEntries(
+ role: keyof typeof ROLES,
+): Promise<Array<{ key: string; serviceCount: number; rows: string[]; slots: MenuResponse['layers'][number]['slots'] }>> {
+ const cfg = configSchema.parse({ rbac: { roles: ROLES } });
+ const config: ConfigSource = { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+ const sessions = new SessionStore({ ttlMinutes: 60 });
+ const catalog = { get: async () => snapshot } as unknown as ServiceLayerCatalog;
+ app = Fastify();
+ await app.register(cookie);
+ app.addHook(
+ 'onRoute',
+ makeRouteAuthHook({
+ config,
+ sessions,
+ access: {
+ services: new ServiceIdentityResolver({ config, catalog }),
+ classify: async () => ({ isOperate: (l: string) => l.toUpperCase() === 'BANYANDB' }),
+ },
+ }),
+ );
+ registerMenuRoute(app, { config, sessions, fetch: oapQuery, uiTemplateClient: templateClient, serviceCatalog: catalog });
+ await app.ready();
+ const sid = sessions.create(role, [role]).sid;
+ const res = await app.inject({ method: 'GET', url: '/api/menu', headers: { cookie: `horizon_sid=${sid}` } });
+ return (res.json() as MenuResponse).layers.map((l) => ({
+ key: l.key.toLowerCase(),
+ serviceCount: l.serviceCount,
+ rows: (l.menuRows ?? []).map((r) => r.path),
+ slots: l.slots,
+ }));
+}
+
+const keys = (m: Array<{ key: string }>) => m.map((l) => l.key).sort();
+
+describe('the menu follows the verbs', () => {
+ it('shows a plain viewer every layer but the operate ones', async () => {
+ const menu = keys(await menuFor('viewer'));
+ expect(menu).toEqual(expect.arrayContaining(['general~payments', 'general~risk', 'mysql']));
+ expect(menu).not.toContain('banyandb');
+ });
+
+ it('shows the operate layers to cluster:read', async () => {
+ expect(keys(await menuFor('maintainer'))).toEqual(expect.arrayContaining(['banyandb', 'general~payments', 'mysql']));
+ });
+
+ it('shows a group grant its own group entry only', async () => {
+ expect(await menuFor('payments')).toEqual([{ key: 'general~payments', serviceCount: 2 }]);
+ });
+
+ it('shows an explicit operate-layer grant that layer alone', async () => {
+ expect(keys(await menuFor('bdb'))).toEqual(['banyandb']);
+ });
+
+ it('shows a layer with all its pages or not at all', async () => {
+ const rowsOf = async (role: keyof typeof ROLES) =>
+ (await menuEntries(role)).find((e) => e.key === 'general~payments')?.rows;
+ const every = ['service', 'instance', 'topology', 'trace', 'logs'];
+ expect(await rowsOf('payments')).toEqual(every);
+ expect(await rowsOf('everyPage')).toEqual(every);
+ });
+
+ it('does not open layer pages through a verb that has none', async () => {
+ expect(keys(await menuFor('alarmsOnly'))).toEqual(['general~payments']);
+ });
+});
+
+describe('a stored layer row that spells its entity terms as `aliases`', () => {
+ it('still gives every entry, split ones included, the names the layer page reads', async () => {
+ const general = store[0]!;
+ store[0] = layerRow('GENERAL', {
+ slots: undefined,
+ aliases: { services: 'Apps' },
+ splitByServiceGroup: true,
+ components: { service: true, instances: true, topology: true, traces: true, logs: true },
+ });
+ try {
+ const entries = await menuEntries('viewer');
+ expect(entries.find((l) => l.key === 'general~payments')?.slots).toEqual({ services: 'Apps' });
+ // Neither spelling: an empty map, never a missing one.
+ store[0] = layerRow('GENERAL', { slots: undefined, splitByServiceGroup: true });
+ await app?.close();
+ invalidateSyncCache();
+ expect((await menuEntries('viewer')).find((l) => l.key === 'general~payments')?.slots).toEqual({});
+ } finally {
+ store[0] = general;
+ }
+ });
+});
diff --git a/apps/bff/src/http/query/menu.ts b/apps/bff/src/http/query/menu.ts
index 4e33694c..9b1a34b1 100644
--- a/apps/bff/src/http/query/menu.ts
+++ b/apps/bff/src/http/query/menu.ts
@@ -27,6 +27,8 @@ import type {
import { resolveLayerMenuRows } from '@skywalking-horizon-ui/api-client';
import type { LayerDefaultFilters, LayerExtPages } from '@skywalking-horizon-ui/api-client';
import type { AuthDeps } from '../../user/middleware.js';
+import type { RequestAccess } from '../../rbac/request-access.js';
+import { LAYER_PAGE_VERBS } from '../../rbac/verbs.js';
import { requireAuth } from '../../user/middleware.js';
import { buildOapOpts, graphqlPost } from '../../client/graphql.js';
import type { LayerTemplate } from '../../logic/layers/loader.js';
@@ -330,7 +332,9 @@ function buildLayerDef(
group: tpl.group,
visibility: tpl.visibility,
documentLink: tpl.documentLink ?? undefined,
- slots: tpl.slots,
+ // A bundled file's `aliases` becomes `slots` when it is loaded; a row
+ // stored on OAP is served as written, so it may still carry `aliases`.
+ slots: tpl.slots ?? (tpl as { aliases?: LayerSlots }).aliases ?? {},
// Caps come straight from the in-use REMOTE template's component
// flags. Missing flags fall to the componentsToCaps defaults, never
// to the bundled copy of an already-published layer: bundled is the
@@ -392,6 +396,48 @@ function applyLinkPolicy(layers: LayerDef[], trustedDomains: readonly string[]):
});
}
+/**
+ * The entries this caller may open, with the service counts they may see.
+ * Absent `access` (the scope gate is not wired — unit tests) leaves the menu
+ * as it was. A group-limited grant on an unsplit layer keeps the one entry
+ * but counts only the granted groups' services.
+ */
+function scopeMenu(
+ layers: LayerDef[],
+ access: RequestAccess | undefined,
+ groupsByCanonical: Map<string, Map<string, number>> | null,
+): LayerDef[] {
+ if (!access) return layers;
+ return layers.flatMap((l): LayerDef[] => {
+ const layerKey = l.key.split('~')[0]!;
+ if (!access.menuShows(layerKey, l.serviceGroup)) return [];
+ // A layer entry is shown with all its pages or not at all; a page whose
+ // data this caller cannot read answers with a refusal.
+ if (l.serviceGroup !== undefined || !groupsByCanonical || !access.session.hasLayerGrants()) return [l];
+ const reach = access.onLayer(LAYER_PAGE_VERBS, layerKey);
+ if (!reach || reach.whole) return [l];
+ let count = 0;
+ for (const [g, n] of groupsByCanonical.get(canonicalLayerKey(layerKey)) ?? []) if (reach.groups.has(g)) count += n;
+ return [{ ...l, serviceCount: count }];
+ });
+}
+
+
+/** The layers whose alarms the session reads, by base layer — see
+ * `MenuResponse.alarmLayers`. A plain `alarms:read` reaches layers the
+ * page-scoped sidebar leaves out. */
+function alarmLayersFor(layers: LayerDef[], access: RequestAccess | undefined): MenuResponse['alarmLayers'] {
+ if (!access || !access.session.hasLayerGrants()) return undefined;
+ const out = new Map<string, { key: string; name: string }>();
+ for (const l of layers) {
+ const key = canonicalLayerKey(l.key.split('~')[0]!);
+ if (l.serviceCount <= 0 || out.has(key) || !access.onLayer(['alarms:read'], key)) continue;
+ // A group entry's name leads with its group.
+ out.set(key, { key, name: l.serviceGroup ? l.name.replace(`${l.serviceGroup} · `, '') : l.name });
+ }
+ return [...out.values()];
+}
+
export function registerMenuRoute(app: FastifyInstance, deps: MenuRouteDeps): void {
const auth = requireAuth(deps);
app.get('/api/menu', { preHandler: auth }, async (req: FastifyRequest, reply: FastifyReply) => {
@@ -524,8 +570,10 @@ export function registerMenuRoute(app: FastifyInstance, deps: MenuRouteDeps): vo
}));
});
+ const alarmLayers = alarmLayersFor(layers, req.access);
const body: MenuResponse = {
- layers: applyLinkPolicy(layers, cfg.security.trustedLinkDomains),
+ layers: applyLinkPolicy(scopeMenu(layers, req.access, groupsByCanonical), cfg.security.trustedLinkDomains),
+ ...(alarmLayers ? { alarmLayers } : {}),
generatedAt: Date.now(),
oap: { reachable: true, queryUrl },
};
@@ -548,7 +596,7 @@ export function registerMenuRoute(app: FastifyInstance, deps: MenuRouteDeps): vo
layers.push(deriveLayer(key, false, null, -1, null, locale, emptyRows, null));
}
const body: MenuResponse = {
- layers: applyLinkPolicy(layers, cfg.security.trustedLinkDomains),
+ layers: applyLinkPolicy(scopeMenu(layers, req.access, null), cfg.security.trustedLinkDomains),
generatedAt: Date.now(),
oap: {
reachable: false,
diff --git a/apps/bff/src/http/query/mqe-exec-access.test.ts b/apps/bff/src/http/query/mqe-exec-access.test.ts
new file mode 100644
index 00000000..aaef348b
--- /dev/null
+++ b/apps/bff/src/http/query/mqe-exec-access.test.ts
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * An expression with no source service reads the metric across every service
+ * — `top_n` filters by `serviceName` alone, whatever the `dest*` side says —
+ * so it is raw metric access and needs `inspect:read`.
+ */
+
+import { afterEach, describe, expect, it } from 'vitest';
+import Fastify, { type FastifyInstance } from 'fastify';
+import cookie from '@fastify/cookie';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../../config/schema.js';
+import type { ConfigSource } from '../../config/loader.js';
+import { SessionStore } from '../../user/sessions.js';
+import { makeRouteAuthHook } from '../../rbac/route-policy.js';
+import { registerMqeExecRoute } from './mqe-exec.js';
+
+const oap: FetchLike = async (_url, init) => {
+ const q = String(JSON.parse(String(init?.body ?? '{}')).query ?? '');
+ const data = q.includes('getTimeInfo')
+ ? { result: { timezone: '+0000', currentTimestamp: Date.now() } }
+ : { execExpression: { type: 'SINGLE_VALUE', error: null, results: [] } };
+ return new Response(JSON.stringify({ data }), { status: 200, headers: { 'content-type': 'application/json' } });
+};
+
+let app: FastifyInstance | null = null;
+afterEach(async () => {
+ await app?.close();
+ app = null;
+});
+
+async function exec(role: 'reader' | 'inspector', entity: Record<string, unknown>): Promise<number> {
+ const cfg = configSchema.parse({ rbac: { roles: { reader: ['metrics:read'], inspector: ['metrics:read', 'inspect:read'] } } });
+ const config: ConfigSource = { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+ const sessions = new SessionStore({ ttlMinutes: 60 });
+ app = Fastify();
+ await app.register(cookie);
+ app.addHook('onRoute', makeRouteAuthHook({ config, sessions }));
+ registerMqeExecRoute(app, { config, sessions, fetch: oap });
+ await app.ready();
+ const res = await app.inject({
+ method: 'POST',
+ url: '/api/mqe/exec',
+ headers: { cookie: `horizon_sid=${sessions.create(role, [role]).sid}` },
+ payload: { expression: 'top_n(service_cpm,10,DES)', entity, step: 'MINUTE', startMs: 1_700_000_000_000, endMs: 1_700_000_600_000 },
+ });
+ return res.statusCode;
+}
+
+describe('an MQE with no source service', () => {
+ it('needs inspect:read, whatever the destination names', async () => {
+ expect(await exec('reader', { destServiceName: 'payments::checkout', destNormal: true })).toBe(403);
+ expect(await exec('reader', {})).toBe(403);
+ expect(await exec('inspector', { destServiceName: 'payments::checkout', destNormal: true })).toBe(200);
+ });
+
+ it('runs for metrics:read once the source service is named', async () => {
+ expect(await exec('reader', { serviceName: 'payments::checkout', normal: true })).toBe(200);
+ });
+});
diff --git a/apps/bff/src/http/query/mqe-exec.ts b/apps/bff/src/http/query/mqe-exec.ts
index 08d220d2..4a692b6b 100644
--- a/apps/bff/src/http/query/mqe-exec.ts
+++ b/apps/bff/src/http/query/mqe-exec.ts
@@ -44,6 +44,7 @@ import { clientGone } from '../client-gone.js';
import { withColdStage } from '../../util/duration.js';
import { getServerOffsetMinutes, windowFromRange } from '../../util/window.js';
import { expressionForServiceMetricSeries } from '../../util/mqe-catalog.js';
+import { sessionHasVerb } from '../../rbac/policy.js';
export interface MqeExecRouteDeps extends AuthDeps {
fetch?: FetchLike;
@@ -146,6 +147,15 @@ export function registerMqeExecRoute(app: FastifyInstance, deps: MqeExecRouteDep
return reply.code(400).send({ error: 'invalid_body', detail: parsed.error.flatten() });
}
const { entity, step, startMs, endMs } = parsed.data;
+ // With no source service the expression reads the metric across every
+ // service — `top_n` filters by `serviceName` alone, whatever `dest*`
+ // says — which is raw metric access: `inspect:read`, not `metrics:read`.
+ if (!entity.serviceName) {
+ const session = req.session;
+ if (!session || !sessionHasVerb(deps.config.current, session, 'inspect:read')) {
+ return reply.code(403).send({ error: 'permission_denied', verb: 'inspect:read', reason: 'expression_names_no_service' });
+ }
+ }
// A blank field is not a blank query: a service-list column with no
// `mqe` runs the catalog default derived from its metric id + layer,
diff --git a/apps/bff/src/http/query/services.ts b/apps/bff/src/http/query/services.ts
index 52f5b468..9e8d5373 100644
--- a/apps/bff/src/http/query/services.ts
+++ b/apps/bff/src/http/query/services.ts
@@ -38,6 +38,8 @@ import type { AuthDeps } from '../../user/middleware.js';
import { requireAuth } from '../../user/middleware.js';
import { serviceLayerCatalog } from '../../logic/services/service-layer-catalog.js';
+import { LAYER_PAGE_VERBS } from '../../rbac/verbs.js';
+
export interface LayerServicesRouteDeps extends AuthDeps {
fetch?: FetchLike;
}
@@ -63,7 +65,8 @@ export function registerLayerServicesRoute(
const group = (req.query as { group?: string }).group;
try {
const snap = await catalog.get();
- const all = snap.byLayer.get(layerUpper) ?? [];
+ const layerRows = snap.byLayer.get(layerUpper) ?? [];
+ const all = req.access ? req.access.filterRoster(LAYER_PAGE_VERBS, layerKey, layerRows) : layerRows;
const rows = group === undefined ? all : all.filter((r) => r.group === group);
return reply.send({
// Honest about the read that produced this. An empty roster from a
diff --git a/apps/bff/src/http/query/topology.ts b/apps/bff/src/http/query/topology.ts
index d1594c33..a52048d4 100644
--- a/apps/bff/src/http/query/topology.ts
+++ b/apps/bff/src/http/query/topology.ts
@@ -59,6 +59,13 @@ export interface TopologyRouteDeps extends AuthDeps {
const DEFAULT_WINDOW_MIN = 60;
+/** The groups a layer-limited caller may seed the whole-layer map with;
+ * `undefined` when they read the whole layer. */
+function seedGroupsFor(req: FastifyRequest, layerKey: string): ReadonlySet<string> | undefined {
+ const reach = req.access?.onLayer(['topology:read'], layerKey);
+ return reach && !reach.whole ? reach.groups : undefined;
+}
+
export function registerTopologyRoute(app: FastifyInstance, deps: TopologyRouteDeps): void {
const auth = requireAuth(deps);
app.get(
@@ -143,16 +150,18 @@ export function registerTopologyRoute(app: FastifyInstance, deps: TopologyRouteD
defaultMinuteWindow(offset, DEFAULT_WINDOW_MIN)
: defaultMinuteWindow(offset, DEFAULT_WINDOW_MIN);
+ const focus = serviceArg.split(',').map((s) => s.trim()).filter(Boolean);
const response = await buildServiceTopology({
opts,
perf: cfgCurrent.performance,
window,
coldStage: !!req.coldStage,
- cfg: topoCfg,
+ cfg: req.access ? await req.access.graphConfig(['topology:read'], focus, topoCfg) : topoCfg,
layerKey,
serviceArg,
depth,
group: q.group,
+ seedGroups: seedGroupsFor(req, layerKey),
});
return reply.send(response);
},
diff --git a/apps/bff/src/http/query/trace.ts b/apps/bff/src/http/query/trace.ts
index 38943385..20eca26c 100644
--- a/apps/bff/src/http/query/trace.ts
+++ b/apps/bff/src/http/query/trace.ts
@@ -544,11 +544,12 @@ export function registerTraceRoutes(app: FastifyInstance, deps: TraceRouteDeps):
QUERY_TRACE_DETAIL,
{ traceId: params.traceId, duration },
);
+ const spans = env.trace?.spans ?? [];
const detail: NativeTraceDetailResponse = {
source: 'native',
api,
traceId: params.traceId,
- spans: env.trace?.spans ?? [],
+ spans,
reachable: true,
};
return reply.send({
diff --git a/apps/bff/src/http/user.ts b/apps/bff/src/http/user.ts
index dacf8ef8..931302ba 100644
--- a/apps/bff/src/http/user.ts
+++ b/apps/bff/src/http/user.ts
@@ -238,6 +238,9 @@ function mePayload(cfg: HorizonConfig, session: Session) {
providerName: providerLabel(cfg, session.provider),
roles: session.roles,
verbs: resolveVerbsForRoles(cfg.rbac.roles, session.roles, cfg.rbac.enabled),
+ // An OAuth credential's scope cap. The client intersects every check with
+ // it, as the server does; absent for a browser session or an API token.
+ ...(session.verbCap ? { verbCap: session.verbCap } : {}),
landingRoute: pickLandingRoute(cfg.rbac.landingByRole, session.roles),
};
}
diff --git a/apps/bff/src/logic/dashboard/mqe.ts b/apps/bff/src/logic/dashboard/mqe.ts
index 5c5d912d..b6dd1c75 100644
--- a/apps/bff/src/logic/dashboard/mqe.ts
+++ b/apps/bff/src/logic/dashboard/mqe.ts
@@ -21,6 +21,7 @@
*/
import type { Window } from '../../util/window.js';
+import { entityServiceName } from '../services/service-identity.js';
interface MqeOwner {
scope?: string | null;
@@ -83,16 +84,16 @@ export function buildFragment(
let entity: string;
if (opts.serviceInstanceName) {
entity =
- `{ scope: ServiceInstance, serviceName: ${JSON.stringify(serviceName)},` +
+ `{ scope: ServiceInstance, serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` serviceInstanceName: ${JSON.stringify(opts.serviceInstanceName)},` +
` normal: ${normal ? 'true' : 'false'} }`;
} else if (opts.endpointName) {
entity =
- `{ scope: Endpoint, serviceName: ${JSON.stringify(serviceName)},` +
+ `{ scope: Endpoint, serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` endpointName: ${JSON.stringify(opts.endpointName)},` +
` normal: ${normal ? 'true' : 'false'} }`;
} else {
- entity = `{ scope: Service, serviceName: ${JSON.stringify(serviceName)}, normal: ${normal ? 'true' : 'false'} }`;
+ entity = `{ scope: Service, serviceName: ${JSON.stringify(entityServiceName(serviceName))}, normal: ${normal ? 'true' : 'false'} }`;
}
const coldFrag = opts.coldStage ? ', coldStage: true' : '';
return (
diff --git a/apps/bff/src/logic/layers/operate-layers.test.ts b/apps/bff/src/logic/layers/operate-layers.test.ts
new file mode 100644
index 00000000..d6629c8b
--- /dev/null
+++ b/apps/bff/src/logic/layers/operate-layers.test.ts
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { classifySnapshot } from './operate-layers.js';
+import type { SyncStatus, TemplateRow } from '../templates/sync.js';
+import { formatName } from '../templates/names.js';
+
+function row(key: string, content: Record<string, unknown>, over: Partial<TemplateRow> = {}): TemplateRow {
+ return {
+ name: formatName('layer', key),
+ kind: 'layer',
+ key,
+ status: 'in-sync',
+ effective: 'remote',
+ remote: {
+ id: key,
+ configuration: JSON.stringify({ name: formatName('layer', key), kind: 'layer', version: 1, content }),
+ disabled: false,
+ },
+ bundled: null,
+ ...over,
+ } as TemplateRow;
+}
+
+function sync(rows: TemplateRow[], unreachable = false): SyncStatus {
+ return { mode: 'live', unreachable, lastSuccessfulSyncAt: 1, generatedAt: 1, rows, conflicts: [], unreadable: [] } as SyncStatus;
+}
+
+describe('operate-layer classification', () => {
+ it('reads visibility from the stored template, aliases folded', () => {
+ const c = classifySnapshot(sync([row('BANYANDB', { key: 'BANYANDB', visibility: 'operate' }), row('GENERAL', { key: 'GENERAL' })]));
+ expect(c.isOperate('banyandb')).toBe(true);
+ expect(c.isOperate('GENERAL')).toBe(false);
+ expect(c.isOperate('MYSQL')).toBe(false);
+ });
+
+ it('keeps a disabled operate layer operate', () => {
+ const c = classifySnapshot(
+ sync([row('SO11Y_OAP', { key: 'SO11Y_OAP', visibility: 'operate' }, { status: 'disabled', effective: null })]),
+ );
+ expect(c.isOperate('SO11Y_OAP')).toBe(true);
+ });
+
+ it('ignores a row holding another layer\'s template', () => {
+ const c = classifySnapshot(sync([row('GENERAL', { key: 'BANYANDB', visibility: 'operate' })]));
+ expect(c.isOperate('GENERAL')).toBe(false);
+ });
+
+ it('fails closed on an unreachable store: only a retained row still says a layer is ordinary', () => {
+ const c = classifySnapshot(sync([row('GENERAL', { key: 'GENERAL' })], true));
+ expect(c.isOperate('GENERAL')).toBe(false);
+ expect(c.isOperate('MYSQL')).toBe(true);
+ });
+});
diff --git a/apps/bff/src/logic/layers/operate-layers.ts b/apps/bff/src/logic/layers/operate-layers.ts
new file mode 100644
index 00000000..bb2422b1
--- /dev/null
+++ b/apps/bff/src/logic/layers/operate-layers.ts
@@ -0,0 +1,95 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Which layers are operate layers (the Platform monitoring section), read from
+ * the layer templates' `visibility` — the same field the menu reads, so what
+ * the server enforces and what the sidebar shows cannot disagree.
+ *
+ * This decides access, so it fails CLOSED. A layer counts as operate when its
+ * template says so, and also when nothing is known about it: the template
+ * store has never been read and no row was retained. Once the store has been
+ * read, a layer with no readable template renders from the in-code defaults,
+ * which carry no `visibility`, so it is an ordinary layer — exactly what the
+ * menu shows for it.
+ */
+
+import type { UITemplateClient } from '@skywalking-horizon-ui/api-client';
+import { getSyncStatus, type SyncStatus } from '../templates/sync.js';
+import { iterateBundledTemplates } from '../templates/aggregator.js';
+import { parseEnvelope } from '../templates/names.js';
+import { canonicalLayerKey } from '../templates/identity.js';
+import { logger } from '../../logger.js';
+
+export interface LayerClassification {
+ isOperate(layer: string): boolean;
+}
+
+const NOTHING_IS_OPERATE: LayerClassification = { isOperate: () => false };
+const EVERYTHING_IS_OPERATE: LayerClassification = { isOperate: () => true };
+
+const bySnapshot = new WeakMap<SyncStatus, LayerClassification>();
+
+export function classifySnapshot(sync: SyncStatus): LayerClassification {
+ const operate = new Set<string>();
+ const known = new Set<string>();
+ for (const row of sync.rows) {
+ if (row.kind !== 'layer' || row.locale !== undefined) continue;
+ // A disabled row still says what the layer is: disabling hides a layer
+ // from the menu, it does not make its data an ordinary layer's.
+ if (!row.remote || (row.effective !== 'remote' && row.status !== 'disabled')) continue;
+ const env = parseEnvelope(row.remote.configuration);
+ const content = env?.content as { key?: unknown; visibility?: unknown } | undefined;
+ if (!content || typeof content.key !== 'string') continue;
+ const key = canonicalLayerKey(row.key);
+ if (canonicalLayerKey(content.key) !== key) continue;
+ known.add(key);
+ if (content.visibility === 'operate') operate.add(key);
+ }
+ if (!sync.unreachable) return { isOperate: (layer) => operate.has(canonicalLayerKey(layer)) };
+ // Unreachable: only a retained row still says anything.
+ return {
+ isOperate: (layer) => {
+ const key = canonicalLayerKey(layer);
+ return operate.has(key) || !known.has(key);
+ },
+ };
+}
+
+export async function classifyLayers(
+ uiTemplateClient: (() => UITemplateClient) | undefined,
+): Promise<LayerClassification> {
+ // Tests and deployments with no admin host wired have no templates to read
+ // an operate layer from; the in-code defaults name none.
+ if (!uiTemplateClient) return NOTHING_IS_OPERATE;
+ try {
+ const sync = await getSyncStatus({
+ client: uiTemplateClient(),
+ bundled: () => iterateBundledTemplates(),
+ logger,
+ });
+ let c = bySnapshot.get(sync);
+ if (!c) {
+ c = classifySnapshot(sync);
+ bySnapshot.set(sync, c);
+ }
+ return c;
+ } catch (err) {
+ logger.warn({ err }, 'layer classification unavailable — treating every layer as operate');
+ return EVERYTHING_IS_OPERATE;
+ }
+}
diff --git a/apps/bff/src/logic/layers/preview-traces.test.ts b/apps/bff/src/logic/layers/preview-traces.test.ts
index 1e217379..75e94bce 100644
--- a/apps/bff/src/logic/layers/preview-traces.test.ts
+++ b/apps/bff/src/logic/layers/preview-traces.test.ts
@@ -43,6 +43,11 @@ describe('preview traces block', () => {
expect(stores('{"source":"both"}')).toEqual(['native', 'zipkin']);
});
+ it('previews nothing from a draft that is not a string', () => {
+ // A repeated query parameter arrives as an array, which `JSON.parse` would coerce.
+ expect(stores(['{}'] as unknown as string)).toBeNull();
+ });
+
it('previews an explicit empty list as no stores', () => {
expect(stores('{"sources":[]}')).toEqual([]);
});
diff --git a/apps/bff/src/logic/layers/preview.ts b/apps/bff/src/logic/layers/preview.ts
index 0f59e712..37710493 100644
--- a/apps/bff/src/logic/layers/preview.ts
+++ b/apps/bff/src/logic/layers/preview.ts
@@ -67,7 +67,8 @@ function isMetricList(v: unknown): v is TopologyMetricDef[] {
}
function parseJson(raw: string | undefined): Record<string, unknown> | null {
- if (!raw || raw.length > MAX_RAW_BYTES) return null;
+ // A query string can arrive as an array, which `JSON.parse` would coerce.
+ if (typeof raw !== 'string' || !raw || raw.length > MAX_RAW_BYTES) return null;
try {
const o = JSON.parse(raw);
return o && typeof o === 'object' && !Array.isArray(o) ? (o as Record<string, unknown>) : null;
diff --git a/apps/bff/src/logic/oap/deployment.test.ts b/apps/bff/src/logic/oap/deployment.test.ts
new file mode 100644
index 00000000..41769a68
--- /dev/null
+++ b/apps/bff/src/logic/oap/deployment.test.ts
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The deployment view names its service in every metric it runs. A service the
+ * URL layer's roster does not hold must still be named — an empty name reads as
+ * no service at all, and a `top_n` then ranks every service.
+ */
+
+import { describe, expect, it } from 'vitest';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../../config/schema.js';
+import type { GraphqlOptions } from '../../client/graphql.js';
+import { buildDeployment } from './deployment.js';
+
+const SERVICE_ID = `${Buffer.from('payments::a').toString('base64')}.1`;
+const INSTANCE_ID = `${SERVICE_ID}_${Buffer.from('pod-1').toString('base64')}`;
+
+function oap(service: { id: string; name: string; normal: boolean } | null): { opts: GraphqlOptions; queries: string[] } {
+ const queries: string[] = [];
+ const fetch: FetchLike = async (_url, init) => {
+ const { query } = JSON.parse(String(init?.body ?? '{}')) as { query: string };
+ queries.push(query);
+ const data = query.includes('listServices')
+ ? { services: [] }
+ : query.includes('getServiceInstanceTopology')
+ ? { topology: { nodes: [], calls: [] } }
+ : query.includes('getService(')
+ ? { service }
+ : query.includes('listInstances')
+ ? { instances: [{ id: INSTANCE_ID, name: 'pod-1', attributes: [] }] }
+ : {};
+ return new Response(JSON.stringify({ data }), { status: 200, headers: { 'content-type': 'application/json' } });
+ };
+ return { opts: { queryUrl: 'http://oap:12800', timeoutMs: 5000, fetch }, queries };
+}
+
+const input = (opts: GraphqlOptions) => ({
+ opts,
+ perf: configSchema.parse({}).performance,
+ window: { start: '2026-09-28 1000', end: '2026-09-28 1015', step: 'MINUTE' as const },
+ coldStage: false,
+ cfg: { nodeMetrics: [{ id: 'cpm', label: 'Load', mqe: 'top_n(service_instance_cpm,5,des)' }] },
+ layerKey: 'banyandb',
+ serviceId: SERVICE_ID,
+});
+
+describe('a deployment for a service outside the URL layer\'s roster', () => {
+ it('names the service OAP returns for its id in every metric', async () => {
+ const { opts, queries } = oap({ id: SERVICE_ID, name: 'payments::a', normal: true });
+ const out = await buildDeployment(input(opts));
+ expect(out.serviceName).toBe('payments::a');
+ const metrics = queries.filter((q) => q.includes('execExpression'));
+ expect(metrics.length).toBeGreaterThan(0);
+ for (const q of metrics) expect(q).toContain('serviceName: "payments::a"');
+ });
+
+ it('runs no metric for a service OAP does not know', async () => {
+ const { opts, queries } = oap(null);
+ const out = await buildDeployment(input(opts));
+ expect(out.error).toMatch(/Unknown service/);
+ expect(queries.some((q) => q.includes('execExpression'))).toBe(false);
+ });
+});
diff --git a/apps/bff/src/logic/oap/deployment.ts b/apps/bff/src/logic/oap/deployment.ts
index e2c04f1b..56abd013 100644
--- a/apps/bff/src/logic/oap/deployment.ts
+++ b/apps/bff/src/logic/oap/deployment.ts
@@ -39,6 +39,7 @@ import type { GraphqlOptions } from '../../client/graphql.js';
import type { Window } from '../../util/window.js';
import { graphqlPost, fetchAliasedChunks } from '../../client/graphql.js';
import { type MqeShape, aggregateMqe, seriesFromMqe, instanceNodeFragment } from './topology-mqe.js';
+import { entityServiceName } from '../services/service-identity.js';
interface OapInstNode {
id: string;
@@ -75,6 +76,16 @@ const INSTANCE_TOPOLOGY = /* GraphQL */ `
}
`;
+const GET_SERVICE_FOR_RESOLVE = /* GraphQL */ `
+ query GetServiceForDeployment($id: String!) {
+ service: getService(serviceId: $id) {
+ id
+ name
+ normal
+ }
+ }
+`;
+
const LIST_SERVICES_FOR_RESOLVE = /* GraphQL */ `
query ListServicesForDeployment($layer: String!) {
services: listServices(layer: $layer) {
@@ -119,10 +130,10 @@ function relationFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
` entity: {` +
- ` serviceName: ${JSON.stringify(serviceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` normal: ${normal ? 'true' : 'false'},` +
` serviceInstanceName: ${JSON.stringify(srcInstanceName)},` +
- ` destServiceName: ${JSON.stringify(serviceName)},` +
+ ` destServiceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` destNormal: ${normal ? 'true' : 'false'},` +
` destServiceInstanceName: ${JSON.stringify(dstInstanceName)} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
@@ -202,11 +213,21 @@ export async function buildDeployment(input: BuildDeploymentInput): Promise<Depl
const data = await graphqlPost<{
services: Array<{ id: string; name: string; normal?: boolean | null }>;
}>(opts, LIST_SERVICES_FOR_RESOLVE, { layer: oapLayer });
- const svc = data.services.find((s) => s.id === serviceId) ?? null;
- if (svc) {
- serviceName = svc.name;
- serviceNormal = svc.normal !== false;
+ let svc = data.services.find((s) => s.id === serviceId) ?? null;
+ // Not in this layer's roster (another layer's URL, a roster that has not
+ // caught up): ask for the service itself. Every metric below names it,
+ // and an empty name would read as no service at all.
+ if (!svc) {
+ const one = await graphqlPost<{ service: { id: string; name: string; normal?: boolean | null } | null }>(
+ opts,
+ GET_SERVICE_FOR_RESOLVE,
+ { id: serviceId },
+ );
+ svc = one.service?.id === serviceId ? one.service : null;
}
+ if (!svc) return emptyDeploymentResponse(layerKey, serviceId, cfg, true, `Unknown service ${serviceId}.`);
+ serviceName = svc.name;
+ serviceNormal = svc.normal !== false;
} catch (err) {
return emptyDeploymentResponse(layerKey, serviceId, cfg, false, err instanceof Error ? err.message : String(err));
}
@@ -274,11 +295,7 @@ export async function buildDeployment(input: BuildDeploymentInput): Promise<Depl
];
const nodeById = new Map<string, OapInstNode>();
for (const n of nodes) nodeById.set(n.id, n);
- // OAP hands the decoded service name on each instance node; prefer the
- // roster name but fall back to it for services missing from the
- // roster snapshot.
- if (!serviceName) serviceName = nodes.find((n) => n.serviceId === serviceId)?.serviceName ?? null;
- const entityServiceName = serviceName ?? '';
+ const entityName = serviceName ?? '';
function attrsFor(n: OapInstNode): Array<{ name: string; value: string }> {
return attrsById.get(n.id) ?? attrsByName.get(n.name) ?? [];
}
@@ -373,7 +390,7 @@ export async function buildDeployment(input: BuildDeploymentInput): Promise<Depl
const alias = `s${i}_${j}`;
edgeAliasMap.set(alias, { callId: c.id, metric: m, side: 'server' });
edgeFragments.push(
- relationFragment(alias, m, entityServiceName, src.name, dst.name, serviceNormal, window, coldStage),
+ relationFragment(alias, m, entityName, src.name, dst.name, serviceNormal, window, coldStage),
);
});
}
@@ -382,7 +399,7 @@ export async function buildDeployment(input: BuildDeploymentInput): Promise<Depl
const alias = `c${i}_${j}`;
edgeAliasMap.set(alias, { callId: c.id, metric: m, side: 'client' });
edgeFragments.push(
- relationFragment(alias, m, entityServiceName, src.name, dst.name, serviceNormal, window, coldStage),
+ relationFragment(alias, m, entityName, src.name, dst.name, serviceNormal, window, coldStage),
);
});
}
diff --git a/apps/bff/src/logic/oap/endpoint-dependency.test.ts b/apps/bff/src/logic/oap/endpoint-dependency.test.ts
new file mode 100644
index 00000000..8b4bcfa3
--- /dev/null
+++ b/apps/bff/src/logic/oap/endpoint-dependency.test.ts
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../../config/schema.js';
+import { buildEndpointDependency } from './endpoint-dependency.js';
+
+const NAME = 'payments::db';
+const CONJECTURED = `${Buffer.from(NAME).toString('base64')}.0`;
+const ENDPOINT = `${CONJECTURED}_${Buffer.from('SELECT').toString('base64')}`;
+
+describe('the API dependency view', () => {
+ it('reads the focus service the checked id names, not the flag sent beside it', async () => {
+ const queries: string[] = [];
+ const fetch: FetchLike = async (_url, init) => {
+ const { query } = JSON.parse(String(init?.body ?? '{}')) as { query: string };
+ queries.push(query);
+ const data = query.includes('getEndpointDependencies')
+ ? { topology: { nodes: [{ id: ENDPOINT, name: 'SELECT', serviceId: CONJECTURED, serviceName: NAME, type: null, isReal: true }], calls: [] } }
+ : {};
+ return new Response(JSON.stringify({ data }), { status: 200, headers: { 'content-type': 'application/json' } });
+ };
+ await buildEndpointDependency({
+ opts: { queryUrl: 'http://oap:12800', timeoutMs: 5000, fetch },
+ perf: configSchema.parse({}).performance,
+ window: { start: '2026-09-28 1000', end: '2026-09-28 1015', step: 'MINUTE' },
+ coldStage: false,
+ cfg: { nodeMetrics: [{ id: 'rt', label: 'Latency', mqe: 'endpoint_resp_time' }] },
+ layerKey: 'virtual_database',
+ // The echo says `normal: true`; the id is the conjectured service's.
+ service: { id: CONJECTURED, name: NAME, normal: true },
+ endpointArg: ENDPOINT,
+ });
+ const node = queries.find((q) => q.includes('execExpression'));
+ expect(node).toContain('normal: false');
+ expect(node).not.toContain('normal: true');
+ });
+});
diff --git a/apps/bff/src/logic/oap/endpoint-dependency.ts b/apps/bff/src/logic/oap/endpoint-dependency.ts
index 5dff327f..f9315dcc 100644
--- a/apps/bff/src/logic/oap/endpoint-dependency.ts
+++ b/apps/bff/src/logic/oap/endpoint-dependency.ts
@@ -38,6 +38,7 @@ import type { GraphqlOptions } from '../../client/graphql.js';
import type { Window } from '../../util/window.js';
import { graphqlPost, fetchAliasedChunks } from '../../client/graphql.js';
import { type MqeShape, aggregateMqe, seriesFromMqe } from './topology-mqe.js';
+import { entityServiceName } from '../services/service-identity.js';
interface OapEpNode {
id: string;
@@ -88,7 +89,7 @@ function endpointFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
` entity: { scope: Endpoint,` +
- ` serviceName: ${JSON.stringify(serviceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` endpointName: ${JSON.stringify(endpointName)},` +
` normal: ${normal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
@@ -118,10 +119,10 @@ function endpointRelationFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
` entity: {` +
- ` serviceName: ${JSON.stringify(sourceServiceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(sourceServiceName))},` +
` endpointName: ${JSON.stringify(sourceEndpointName)},` +
` normal: ${sourceNormal ? 'true' : 'false'},` +
- ` destServiceName: ${JSON.stringify(destServiceName)},` +
+ ` destServiceName: ${JSON.stringify(entityServiceName(destServiceName))},` +
` destEndpointName: ${JSON.stringify(destEndpointName)},` +
` destNormal: ${destNormal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
@@ -181,9 +182,9 @@ export interface BuildEndpointDependencyInput {
/** The resolved (preview OR effective) endpoint-dependency config. */
cfg: EndpointDependencyConfig;
layerKey: string;
- /** The picked service's roster row: `id` finds its endpoint, `name` +
- * `normal` are what the endpoint-scoped MQE entity is built from (it has no
- * id form). Nothing here is looked up. */
+ /** The picked service's roster row: `id` finds its endpoint and decides the
+ * focus node's `normal` for the endpoint-scoped MQE entity (it has no id
+ * form); `name` labels an empty answer. Nothing here is looked up. */
service: { id: string; name: string; normal: boolean };
/** Endpoint NAME or id — resolved to an endpointId that PINS the chain. */
endpointArg: string;
@@ -193,11 +194,17 @@ export async function buildEndpointDependency(input: BuildEndpointDependencyInpu
const { opts, perf, window, coldStage, cfg: epCfg, layerKey, service, endpointArg } = input;
const serviceId = service.id;
const serviceArg = service.name;
- const normal = service.normal;
+ // The id carries the flag (`.1` real, `.0` conjectured) and is what was
+ // checked; the flag sent beside it could name the service's namesake.
+ const normal = serviceId.endsWith('.0') ? false : serviceId.endsWith('.1') ? true : service.normal;
const durationVar = coldStage
? { start: window.start, end: window.end, step: window.step, coldStage: true }
: { start: window.start, end: window.end, step: window.step };
+ // An endpoint id is used as it is, so it must be one of THIS service's.
+ if (/\.0_/.test(endpointArg) && !endpointArg.startsWith(`${serviceId}_`)) {
+ return emptyEndpointDependencyResponse(layerKey, serviceArg, endpointArg, null, epCfg, true, 'endpoint not found');
+ }
let endpointId = endpointArg;
if (!/\.0_/.test(endpointArg)) {
try {
diff --git a/apps/bff/src/logic/oap/instance-topology.ts b/apps/bff/src/logic/oap/instance-topology.ts
index ec576cba..a1f726bb 100644
--- a/apps/bff/src/logic/oap/instance-topology.ts
+++ b/apps/bff/src/logic/oap/instance-topology.ts
@@ -37,6 +37,7 @@ import type { GraphqlOptions } from '../../client/graphql.js';
import type { Window } from '../../util/window.js';
import { graphqlPost, fetchAliasedChunks } from '../../client/graphql.js';
import { type MqeShape, aggregateMqe, seriesFromMqe, instanceNodeFragment } from './topology-mqe.js';
+import { entityServiceName } from '../services/service-identity.js';
interface OapInstNode {
id: string;
@@ -102,10 +103,10 @@ function relationFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
` entity: {` +
- ` serviceName: ${JSON.stringify(srcServiceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(srcServiceName))},` +
` normal: ${srcNormal ? 'true' : 'false'},` +
` serviceInstanceName: ${JSON.stringify(srcInstanceName)},` +
- ` destServiceName: ${JSON.stringify(dstServiceName)},` +
+ ` destServiceName: ${JSON.stringify(entityServiceName(dstServiceName))},` +
` destNormal: ${dstNormal ? 'true' : 'false'},` +
` destServiceInstanceName: ${JSON.stringify(dstInstanceName)} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
diff --git a/apps/bff/src/logic/oap/profiling.ts b/apps/bff/src/logic/oap/profiling.ts
index 44cdb201..b56420ac 100644
--- a/apps/bff/src/logic/oap/profiling.ts
+++ b/apps/bff/src/logic/oap/profiling.ts
@@ -342,6 +342,8 @@ export interface AnalyzeNetworkProfilingInput {
offsetMinutes: number;
/** Read this task; when absent, the service's most recent NETWORK task. */
taskId?: string;
+ /** The id `service` resolved to, when the caller already looked it up. */
+ serviceId?: string;
}
const LIST_SERVICES_FOR_PROFILING = /* GraphQL */ `
@@ -360,7 +362,7 @@ const LIST_SERVICES_FOR_PROFILING = /* GraphQL */ `
* Throws whatever the round-trip throws — an unreachable OAP is not the same
* answer as an unknown service, and both callers report the difference.
*/
-async function profilingServiceId(
+export async function profilingServiceId(
opts: GraphqlOptions,
layerKey: string,
service: string,
@@ -617,7 +619,7 @@ export async function analyzeNetworkProfiling(input: AnalyzeNetworkProfilingInpu
return result;
};
try {
- const found = await profilingServiceId(opts, layerKey, service);
+ const found = input.serviceId ? { id: input.serviceId } : await profilingServiceId(opts, layerKey, service);
if ('error' in found) return fail(found.error);
const serviceId = found.id;
const task = await findNetworkTask(opts, serviceId, input.taskId);
@@ -720,6 +722,8 @@ export interface AnalyzeProfilingInput {
service: string;
/** Target a specific task; when absent, the most recent task of this type. */
taskId?: string;
+ /** The id `service` resolved to, when the caller already looked it up. */
+ serviceId?: string;
/** async only — which captured event to analyze when the task recorded more
* than one (its units are not shared, so only one renders per call). Absent
* or unrecognised falls back to the task's first event. */
@@ -739,7 +743,7 @@ export async function analyzeProfiling(input: AnalyzeProfilingInput): Promise<Pr
reachable: true,
};
try {
- const found = await profilingServiceId(opts, layerKey, service);
+ const found = input.serviceId ? { id: input.serviceId } : await profilingServiceId(opts, layerKey, service);
if ('error' in found) {
base.reachable = false;
base.error = found.error;
diff --git a/apps/bff/src/logic/oap/service-topology.ts b/apps/bff/src/logic/oap/service-topology.ts
index 098ca897..a7076767 100644
--- a/apps/bff/src/logic/oap/service-topology.ts
+++ b/apps/bff/src/logic/oap/service-topology.ts
@@ -142,10 +142,13 @@ export interface BuildServiceTopologyInput {
depth: number;
/** Layer-overview only: scope the all-services seed to one Service.group. */
group?: string;
+ /** Layer-overview only: the Service.group values the caller may read, when
+ * that is not every group. Neighbours still render as OAP returns them. */
+ seedGroups?: ReadonlySet<string>;
}
export async function buildServiceTopology(input: BuildServiceTopologyInput): Promise<TopologyResponse> {
- const { opts, perf, window, coldStage, cfg: topoCfg, layerKey, serviceArg, depth, group } = input;
+ const { opts, perf, window, coldStage, cfg: topoCfg, layerKey, serviceArg, depth, group, seedGroups } = input;
const oapLayer = layerKey.toUpperCase();
const durationVar = coldStage
? { start: window.start, end: window.end, step: window.step, coldStage: true }
@@ -177,6 +180,7 @@ export async function buildServiceTopology(input: BuildServiceTopologyInput): Pr
// layer-overview seed to one OAP Service.group; absent ⇒ all.
seedIds = data.services
.filter((s) => group === undefined || ((s as { group?: string }).group ?? '') === group)
+ .filter((s) => !seedGroups || seedGroups.has((s as { group?: string }).group ?? ''))
.map((s) => s.id);
}
} catch (err) {
diff --git a/apps/bff/src/logic/oap/topology-mqe.test.ts b/apps/bff/src/logic/oap/topology-mqe.test.ts
new file mode 100644
index 00000000..172cf376
--- /dev/null
+++ b/apps/bff/src/logic/oap/topology-mqe.test.ts
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { instanceNodeFragment, nodeFragment, relationFragment } from './topology-mqe.js';
+
+const w = { start: '2026-09-28 1000', end: '2026-09-28 1015', step: 'MINUTE' as const };
+const m = { id: 'cpm', label: 'Load', mqe: 'top_n(service_cpm,5,des)' };
+
+describe('graph MQE entities', () => {
+ it('name the blank service `_blank`, as OAP keys it, never as an empty name that reads every service', () => {
+ for (const q of [
+ nodeFragment('a', m, '', true, w, false),
+ instanceNodeFragment('a', m, '', 'pod-1', true, w, false),
+ relationFragment('a', m, '', true, '', true, w, false),
+ ]) {
+ expect(q).toContain('serviceName: "_blank"');
+ expect(q).not.toContain('serviceName: ""');
+ }
+ expect(nodeFragment('a', m, 'payments::a', true, w, false)).toContain('serviceName: "payments::a"');
+ });
+});
diff --git a/apps/bff/src/logic/oap/topology-mqe.ts b/apps/bff/src/logic/oap/topology-mqe.ts
index a0dafd14..3824afa1 100644
--- a/apps/bff/src/logic/oap/topology-mqe.ts
+++ b/apps/bff/src/logic/oap/topology-mqe.ts
@@ -28,6 +28,7 @@
import type { TopologyMetricDef } from '@skywalking-horizon-ui/api-client';
import type { Window } from '../../util/window.js';
+import { entityServiceName } from '../services/service-identity.js';
interface MqeValueRow {
value: string | number | null;
@@ -53,7 +54,7 @@ export function nodeFragment(
return (
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
- ` entity: { scope: Service, serviceName: ${JSON.stringify(serviceName)},` +
+ ` entity: { scope: Service, serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` normal: ${normal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
` ) { type error results { values { value } } }`
@@ -76,7 +77,7 @@ export function instanceNodeFragment(
return (
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
- ` entity: { scope: ServiceInstance, serviceName: ${JSON.stringify(serviceName)},` +
+ ` entity: { scope: ServiceInstance, serviceName: ${JSON.stringify(entityServiceName(serviceName))},` +
` normal: ${normal ? 'true' : 'false'}, serviceInstanceName: ${JSON.stringify(instanceName)} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
` ) { type error results { values { value } } }`
@@ -108,9 +109,9 @@ export function relationFragment(
`${alias}: execExpression(\n` +
` expression: ${JSON.stringify(m.mqe)},\n` +
` entity: {` +
- ` serviceName: ${JSON.stringify(sourceName)},` +
+ ` serviceName: ${JSON.stringify(entityServiceName(sourceName))},` +
` normal: ${sourceNormal ? 'true' : 'false'},` +
- ` destServiceName: ${JSON.stringify(destName)},` +
+ ` destServiceName: ${JSON.stringify(entityServiceName(destName))},` +
` destNormal: ${destNormal ? 'true' : 'false'} },\n` +
` duration: { start: ${JSON.stringify(w.start)}, end: ${JSON.stringify(w.end)}, step: ${w.step}${coldFrag} }\n` +
` ) { type error results { values { value } } }`
diff --git a/apps/bff/src/logic/overview/declared-expressions.test.ts b/apps/bff/src/logic/overview/declared-expressions.test.ts
new file mode 100644
index 00000000..bf89dcf4
--- /dev/null
+++ b/apps/bff/src/logic/overview/declared-expressions.test.ts
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { UITemplateClient, UITemplateRow } from '@skywalking-horizon-ui/api-client';
+import { buildEnvelope, serializeEnvelope } from '../templates/names.js';
+import { invalidateSyncCache } from '../templates/sync.js';
+import { overviewExpressionsForLayer } from './effective.js';
+
+const overview = {
+ id: 'services',
+ title: 'Services',
+ widgets: [
+ { id: 'w1', type: 'metric', layer: 'GENERAL', mqe: 'avg(top_n(service_cpm,{{topn}},DES))' },
+ { id: 'w2', type: 'kpi-tile', layer: 'general', kpis: [{ label: 'SLA', mqe: 'avg(top_n(service_sla,{{topn}},DES))' }] },
+ { id: 'w3', type: 'metric', layer: 'MESH', mqe: 'avg(top_n(service_resp_time,{{topn}},DES))' },
+ { id: 'w4', type: 'metric', layer: 'GENERAL~payments', mqe: 'avg(top_n(service_apdex,{{topn}},DES))' },
+ ],
+};
+
+const client = (): UITemplateClient =>
+ ({
+ list: async (): Promise<UITemplateRow[]> => [
+ { id: 'o1', disabled: false, configuration: serializeEnvelope(buildEnvelope('overview', 'services', overview)) } as UITemplateRow,
+ ],
+ create: () => Promise.reject(new Error('read only')),
+ update: () => Promise.reject(new Error('read only')),
+ disable: () => Promise.reject(new Error('read only')),
+ }) as unknown as UITemplateClient;
+
+beforeEach(() => invalidateSyncCache());
+
+describe('the layer-wide expressions a stored overview declares', () => {
+ it('collects widget and KPI expressions for the layer, case-folded, its group entries included', async () => {
+ const got = await overviewExpressionsForLayer(client, 'GENERAL');
+ expect([...got].sort()).toEqual([
+ 'avg(top_n(service_apdex,{{topn}},DES))',
+ 'avg(top_n(service_cpm,{{topn}},DES))',
+ 'avg(top_n(service_sla,{{topn}},DES))',
+ ]);
+ });
+
+ it('declares nothing for a layer no overview reads, nor without a template store', async () => {
+ expect((await overviewExpressionsForLayer(client, 'BANYANDB')).size).toBe(0);
+ expect((await overviewExpressionsForLayer(undefined, 'GENERAL')).size).toBe(0);
+ });
+});
diff --git a/apps/bff/src/logic/overview/effective.ts b/apps/bff/src/logic/overview/effective.ts
index 970c84f0..48008d03 100644
--- a/apps/bff/src/logic/overview/effective.ts
+++ b/apps/bff/src/logic/overview/effective.ts
@@ -37,6 +37,7 @@ import type { OverviewDashboard, UITemplateClient } from '@skywalking-horizon-ui
import { getSyncStatus, type TemplateRow } from '../templates/sync.js';
import { iterateBundledTemplates } from '../templates/aggregator.js';
import { formatName, parseEnvelope } from '../templates/names.js';
+import { canonicalLayerKey } from '../templates/identity.js';
import { logger } from '../../logger.js';
function isOverviewLike(v: unknown): v is OverviewDashboard {
@@ -77,6 +78,32 @@ export async function resolveEffectiveOverviews(
}
}
+/**
+ * The expressions the stored overviews evaluate across `layerKey` as a whole.
+ * The landing route runs a self-aggregating column — one with no service in
+ * its entity, so it reads every service of the metric — only when the column
+ * is one of these; otherwise any caller who can open one layer could ask any
+ * metric of any other through it.
+ */
+export async function overviewExpressionsForLayer(
+ uiTemplateClient: (() => UITemplateClient) | undefined,
+ layerKey: string,
+): Promise<Set<string>> {
+ // A widget on a split layer names `<layer>~<group>`; its landing read
+ // arrives as the layer with a `group` parameter.
+ const layerOf = (k: string) => canonicalLayerKey(k.split('~', 1)[0]!);
+ const key = layerOf(layerKey);
+ const out = new Set<string>();
+ for (const d of await resolveEffectiveOverviews(uiTemplateClient)) {
+ for (const w of d.widgets ?? []) {
+ if (!w.layer || layerOf(w.layer) !== key) continue;
+ if (w.mqe) out.add(w.mqe);
+ for (const k of w.kpis ?? []) if (k.mqe) out.add(k.mqe);
+ }
+ }
+ return out;
+}
+
export async function resolveEffectiveOverview(
uiTemplateClient: (() => UITemplateClient) | undefined,
id: string,
diff --git a/apps/bff/src/logic/services/service-identity.test.ts b/apps/bff/src/logic/services/service-identity.test.ts
new file mode 100644
index 00000000..70caa347
--- /dev/null
+++ b/apps/bff/src/logic/services/service-identity.test.ts
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { entityServiceName, serviceIdOf, serviceIdOfChild } from './service-identity.js';
+
+describe('service identity', () => {
+ it('names the blank service as OAP keys its data, not as an empty entity', () => {
+ expect(entityServiceName('')).toBe('_blank');
+ expect(entityServiceName(' ')).toBe('_blank');
+ expect(entityServiceName('\u0000\t')).toBe('_blank');
+ expect(entityServiceName('payments::a')).toBe('payments::a');
+ // Java's trim() keeps U+00A0, so OAP files that name under its own id.
+ expect(entityServiceName('\u00a0')).toBe('\u00a0');
+ });
+
+ it('files a blank name under `_blank`, as OAP builds the id', () => {
+ expect(serviceIdOf('', true)).toBe(serviceIdOf('_blank', true));
+ expect(serviceIdOf(' \t', false)).toBe(serviceIdOf('_blank', false));
+ expect(serviceIdOf('\u00a0', true)).not.toBe(serviceIdOf('_blank', true));
+ });
+
+ it('finds the owning service in an instance or endpoint id', () => {
+ const svc = serviceIdOf('payments::a', true);
+ expect(serviceIdOfChild(`${svc}_${Buffer.from('i-1').toString('base64')}`)).toBe(svc);
+ expect(serviceIdOfChild('no-owner')).toBeNull();
+ });
+});
diff --git a/apps/bff/src/logic/services/service-identity.ts b/apps/bff/src/logic/services/service-identity.ts
new file mode 100644
index 00000000..5d35ac65
--- /dev/null
+++ b/apps/bff/src/logic/services/service-identity.ts
@@ -0,0 +1,208 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Who a service is, for an access decision: its exact OAP id, name, `normal`
+ * flag, group and EVERY layer it reports into.
+ *
+ * Built from the shared service catalog, indexed by exact id — never by the
+ * catalog's lower-cased, last-wins name map, which is a display aid. A miss
+ * (a service registered since the last refresh, or a catalog that could not
+ * be read) asks OAP for that one service; a service OAP does not know is
+ * `null`, and the caller refuses.
+ */
+
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { buildOapOpts, graphqlPost } from '../../client/graphql.js';
+import type { ConfigSource } from '../../config/loader.js';
+import { canonicalLayerKey } from '../templates/identity.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from './service-layer-catalog.js';
+
+/** OAP could not be asked. Not the same as "OAP says there is no such
+ * service": an access decision may take the second as an answer, never the
+ * first. */
+export class ServiceLookupUnavailable extends Error {
+ constructor(cause: unknown) {
+ super(`service lookup unavailable: ${cause instanceof Error ? cause.message : String(cause)}`);
+ this.name = 'ServiceLookupUnavailable';
+ }
+}
+
+export interface ResolvedService {
+ id: string;
+ name: string;
+ normal: boolean | null;
+ group: string;
+ /** Canonical layer keys. */
+ layers: string[];
+}
+
+export interface ServiceIdentityDeps {
+ config: ConfigSource;
+ fetch?: FetchLike;
+ catalog: ServiceLayerCatalog;
+}
+
+interface Index {
+ byId: Map<string, ResolvedService>;
+ /** Exact name → every service carrying it (normal and conjectural). */
+ byName: Map<string, ResolvedService[]>;
+}
+
+const indexes = new WeakMap<ServiceCatalog, Index>();
+
+/** How long rows kept through failed refreshes still decide access. Past it
+ * they are re-checked with OAP, so a service that has since moved into a layer
+ * the caller cannot read is not granted on old membership. */
+const RETAINED_TRUST_MS = 5 * 60_000;
+
+function trusted(snapshot: ServiceCatalog): boolean {
+ if (!snapshot.stale && !snapshot.unreachable) return true;
+ return snapshot.readAt !== undefined && Date.now() - snapshot.readAt < RETAINED_TRUST_MS;
+}
+
+function indexOf(snapshot: ServiceCatalog): Index {
+ const cached = indexes.get(snapshot);
+ if (cached) return cached;
+ const byId = new Map<string, ResolvedService>();
+ for (const [layer, rows] of snapshot.byLayer) {
+ const key = canonicalLayerKey(layer);
+ for (const r of rows) {
+ const s = byId.get(r.id);
+ if (s) {
+ if (!s.layers.includes(key)) s.layers.push(key);
+ } else {
+ byId.set(r.id, { id: r.id, name: r.name, normal: r.normal, group: r.group, layers: [key] });
+ }
+ }
+ }
+ const byName = new Map<string, ResolvedService[]>();
+ for (const s of byId.values()) {
+ const list = byName.get(s.name);
+ if (list) list.push(s);
+ else byName.set(s.name, [s]);
+ }
+ const idx = { byId, byName };
+ indexes.set(snapshot, idx);
+ return idx;
+}
+
+/** OAP's own blank test: Java's `trim()` drops every character up to U+0020
+ * and nothing else, so a name of U+00A0 is a real name to OAP. */
+// eslint-disable-next-line no-control-regex
+const OAP_BLANK = /^[\u0000-\u0020]*$/;
+
+export function isBlankToOap(name: string): boolean {
+ return OAP_BLANK.test(name);
+}
+
+/**
+ * The name to put in an MQE entity for a roster row. OAP lists its blank-named
+ * service with an empty name, but an MQE entity whose `serviceName` is empty
+ * reads as NO service — a `top_n` then ranks the whole deployment — while OAP
+ * keys that service's data under `_blank`.
+ */
+export function entityServiceName(name: string): string {
+ return isBlankToOap(name) ? '_blank' : name;
+}
+
+/** OAP's service id: base64 of the UTF-8 name, `.`, then 1 (normal) or 0. A
+ * blank name is filed under `_blank`, as OAP's own id builder does. */
+export function serviceIdOf(name: string, normal: boolean): string {
+ return `${Buffer.from(entityServiceName(name), 'utf8').toString('base64')}.${normal ? 1 : 0}`;
+}
+
+/** Instance and endpoint ids are `<serviceId>_<base64(name)>`; base64 has no
+ * `_`, so the owning service is everything before the first one. */
+export function serviceIdOfChild(childId: string): string | null {
+ const cut = childId.indexOf('_');
+ return cut > 0 ? childId.slice(0, cut) : null;
+}
+
+const GET_SERVICE = /* GraphQL */ `
+ query HorizonAccessService($id: String!) {
+ service: getService(serviceId: $id) { id name normal group layers }
+ }
+`;
+
+interface RawService {
+ id: string;
+ name: string;
+ normal?: boolean | null;
+ group?: string | null;
+ layers?: string[] | null;
+}
+
+export class ServiceIdentityResolver {
+ constructor(private readonly deps: ServiceIdentityDeps) {}
+
+ /** Null when OAP answers that it has no such service; throws
+ * {@link ServiceLookupUnavailable} when it could not be asked. Rows kept
+ * through failed refreshes decide access only while recent. */
+ async byId(id: string, signal?: AbortSignal): Promise<ResolvedService | null> {
+ const snapshot = await this.deps.catalog.get();
+ if (trusted(snapshot)) {
+ const hit = indexOf(snapshot).byId.get(id);
+ if (hit) return hit;
+ }
+ const opts = buildOapOpts(this.deps.config.current, this.deps.fetch, signal);
+ let got: { service: RawService | null };
+ try {
+ got = await graphqlPost<{ service: RawService | null }>(opts, GET_SERVICE, { id });
+ } catch (err) {
+ throw new ServiceLookupUnavailable(err);
+ }
+ const s = got.service;
+ if (!s || s.id !== id) return null;
+ return {
+ id: s.id,
+ name: s.name,
+ normal: s.normal === true ? true : s.normal === false ? false : null,
+ group: s.group ?? '',
+ layers: [...new Set((s.layers ?? []).map(canonicalLayerKey))],
+ };
+ }
+
+ /**
+ * Every service a NAME can mean. With `normal` given there is exactly one
+ * candidate id; without it a name can mean both the real and the
+ * conjectural service, and the caller must be allowed BOTH.
+ */
+ async byName(name: string, normal: boolean | undefined, signal?: AbortSignal): Promise<ResolvedService[] | null> {
+ if (normal !== undefined) {
+ const one = await this.byId(serviceIdOf(name, normal), signal);
+ return one ? [one] : null;
+ }
+ const snapshot = await this.deps.catalog.get();
+ if (trusted(snapshot)) {
+ // Both ids the name addresses, as well as the rows carrying it: OAP lists
+ // its blank-named service with an empty name, and files it under `_blank`
+ // — the same ids a service literally named `_blank` has.
+ const idx = indexOf(snapshot);
+ const known = new Map((idx.byName.get(name) ?? []).map((s) => [s.id, s]));
+ for (const id of [serviceIdOf(name, true), serviceIdOf(name, false)]) {
+ const s = idx.byId.get(id);
+ if (s) known.set(id, s);
+ }
+ if (known.size > 0) return [...known.values()];
+ }
+ const found = (
+ await Promise.all([this.byId(serviceIdOf(name, true), signal), this.byId(serviceIdOf(name, false), signal)])
+ ).filter((s): s is ResolvedService => s !== null);
+ return found.length > 0 ? found : null;
+ }
+}
diff --git a/apps/bff/src/logic/services/service-layer-catalog.ts b/apps/bff/src/logic/services/service-layer-catalog.ts
index 3d633b7f..432e57ca 100644
--- a/apps/bff/src/logic/services/service-layer-catalog.ts
+++ b/apps/bff/src/logic/services/service-layer-catalog.ts
@@ -82,6 +82,9 @@ export interface ServiceCatalog {
* anything that reports health must still treat the read as failed.
*/
stale?: boolean;
+ /** When the rows were read from OAP (epoch ms). Kept with the rows through a
+ * failed refresh, so a reader can tell how old retained rows are. */
+ readAt?: number;
}
export interface ServiceLayerCatalogDeps {
@@ -201,7 +204,7 @@ export class ServiceLayerCatalog {
byLayer.set(layer, rows);
for (const r of rows) if (r.name) byName.set(r.name.toLowerCase(), layer);
});
- return { layers, byLayer, byName };
+ return { layers, byLayer, byName, readAt: Date.now() };
} catch (err) {
logger.warn({ err }, 'service-layer-catalog: listServices fan-out failed');
return { layers, byLayer: new Map(), byName: new Map(), unreachable: true };
diff --git a/apps/bff/src/oauth/scopes.ts b/apps/bff/src/oauth/scopes.ts
index bddb68a6..6c2b4daa 100644
--- a/apps/bff/src/oauth/scopes.ts
+++ b/apps/bff/src/oauth/scopes.ts
@@ -33,7 +33,7 @@
*/
import type { HorizonConfig } from '../config/schema.js';
-import { hasVerb, resolveVerbsForRoles } from '../rbac/verbs.js';
+import { capGrant, hasVerb, resolveVerbsForRoles } from '../rbac/verbs.js';
export const DEFAULT_SCOPE = 'horizon:read';
@@ -93,5 +93,6 @@ export function grantedVerbs(config: HorizonConfig, roles: readonly string[], sc
// `metrics:*` as matching nothing, so a role granted a whole area was shown
// fewer permissions than the grant actually carried — the one direction a
// consent screen must never be wrong in.
- return [...owned].filter((v) => hasVerb(cap, v)).sort();
+ // A layer grant keeps its layer and loses only the verbs the cap excludes.
+ return [...new Set([...owned].flatMap((v) => (v.includes('@') ? capGrant(v, cap) : hasVerb(cap, v) ? [v] : [])))].sort();
}
diff --git a/apps/bff/src/rbac/builtin-roles-access.test.ts b/apps/bff/src/rbac/builtin-roles-access.test.ts
new file mode 100644
index 00000000..fe060385
--- /dev/null
+++ b/apps/bff/src/rbac/builtin-roles-access.test.ts
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The built-in roles hold no layer grant, so the layer rules must leave them
+ * as they were: maintainer, operator and admin read every layer and are never
+ * checked per service; viewer reads every layer except the Platform monitoring
+ * ones, which were only ever meant for `cluster:read`.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { BUILTIN_ROLES } from '../config/builtin-roles.js';
+import { configSchema } from '../config/schema.js';
+import type { ConfigSource } from '../config/loader.js';
+import { ServiceIdentityResolver } from '../logic/services/service-identity.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from '../logic/services/service-layer-catalog.js';
+import { LAYER_SCOPED_VERBS, resolveVerbsForRoles } from './verbs.js';
+import { SessionAccess } from './layer-access.js';
+import { RequestAccess } from './request-access.js';
+
+const cfg = configSchema.parse({});
+const config: ConfigSource = { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+const empty: ServiceCatalog = { layers: [], byLayer: new Map(), byName: new Map() };
+const catalog = { get: async () => empty } as unknown as ServiceLayerCatalog;
+const services = new ServiceIdentityResolver({ config, catalog, fetch: async () => new Response('{}') });
+const facts = { isOperate: (l: string) => l === 'BANYANDB' || l.startsWith('SO11Y_'), canonical: (l: string) => l.toUpperCase() };
+
+const accessFor = (role: string) =>
+ new RequestAccess(new SessionAccess(resolveVerbsForRoles(BUILTIN_ROLES, [role], true), undefined, facts), services);
+const held = (role: string) => [...LAYER_SCOPED_VERBS].filter((v) => accessFor(role).plain(v));
+
+describe('the built-in roles under layer grants', () => {
+ it('hold no layer grant, so every verb they have is held plainly', () => {
+ for (const role of Object.keys(BUILTIN_ROLES)) {
+ const a = accessFor(role);
+ expect(a.session.hasLayerGrants(), role).toBe(false);
+ for (const v of held(role)) expect(a.layerLimited([v]), `${role} ${v}`).toBe(false);
+ }
+ });
+
+ it('let maintainer, operator and admin read every layer without a per-service check', () => {
+ for (const role of ['maintainer', 'operator', 'admin']) {
+ const a = accessFor(role);
+ expect(held(role).length, role).toBeGreaterThan(0);
+ for (const v of held(role)) expect(a.readsEveryLayer([v]), `${role} ${v}`).toBe(true);
+ for (const layer of ['GENERAL', 'MESH', 'BANYANDB', 'SO11Y_OAP']) expect(a.menuShows(layer), `${role} ${layer}`).toBe(true);
+ }
+ });
+
+ it('let viewer read every layer but the Platform monitoring ones, with the menu it always had', () => {
+ const a = accessFor('viewer');
+ for (const layer of ['GENERAL', 'MESH', 'K8S_SERVICE', 'VIRTUAL_DATABASE']) {
+ expect(a.menuShows(layer), layer).toBe(true);
+ expect(a.onLayer(['metrics:read'], layer)?.whole, layer).toBe(true);
+ }
+ for (const layer of ['BANYANDB', 'SO11Y_OAP', 'SO11Y_SATELLITE']) {
+ expect(a.menuShows(layer), layer).toBe(false);
+ expect(a.onLayer(['metrics:read'], layer), layer).toBeNull();
+ }
+ });
+
+ it('give operator and admin the template-write permission a draft preview needs', () => {
+ for (const role of ['operator', 'admin']) {
+ expect(accessFor(role).plain('layer-template:write'), role).toBe(true);
+ }
+ for (const role of ['viewer', 'maintainer']) {
+ // Neither can open the template editor either, so neither has a preview to run.
+ expect(accessFor(role).plain('layer-template:read'), role).toBe(false);
+ }
+ });
+});
diff --git a/apps/bff/src/rbac/layer-access.ts b/apps/bff/src/rbac/layer-access.ts
new file mode 100644
index 00000000..1ab8558a
--- /dev/null
+++ b/apps/bff/src/rbac/layer-access.ts
@@ -0,0 +1,159 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Which layers, and which services in them, a session may read with a verb.
+ *
+ * Two kinds of grant answer the question. A PLAIN verb (`metrics:read`) reaches
+ * every layer except the operate layers (Platform monitoring), which also need
+ * `cluster:read` — the rule the sidebar and the Roles page have always stated.
+ * A LAYER verb (`metrics:read@GENERAL[payments]`) reaches exactly its layer,
+ * and within it only the named OAP service groups; an explicit grant on an
+ * operate layer opens it without `cluster:read`.
+ *
+ * A service is reachable when one of the layers it belongs to is reachable for
+ * its group. OAP keys a service by `(name, normal)` with no layer in the id, so
+ * a service in two layers is one entity: granting either layer grants it.
+ *
+ * Pure: the caller supplies which layers are operate and who the service is.
+ */
+
+import type { Verb } from './verbs.js';
+import { hasVerb, parseGrant, qualifiedVerbCovers, type ParsedGrant } from './verbs.js';
+
+export interface LayerReach {
+ /** Every service of the layer. */
+ whole: boolean;
+ /** When not whole: the OAP `Service.group` values reachable (`''` = ungrouped). */
+ groups: ReadonlySet<string>;
+}
+
+export interface ServiceIdentity {
+ id: string;
+ name: string;
+ normal: boolean | null;
+ /** OAP `Service.group`, `''` when the service has none. */
+ group: string;
+ /** Canonical layer keys the service reports into. */
+ layers: readonly string[];
+}
+
+export interface AccessFacts {
+ /** Canonical layer key → is it an operate (Platform monitoring) layer. */
+ isOperate(layer: string): boolean;
+ /** Fold an OAP / grant layer spelling to the canonical key. */
+ canonical(layer: string): string;
+}
+
+const WHOLE: LayerReach = { whole: true, groups: new Set() };
+
+export class SessionAccess {
+ private readonly qualified: ParsedGrant[];
+
+ constructor(
+ /** The session's resolved grants (roles expanded, aliases applied). */
+ private readonly grants: readonly Verb[],
+ /** An OAuth scope's plain-verb cap; absent = no cap. */
+ private readonly cap: readonly Verb[] | undefined,
+ private readonly facts: AccessFacts,
+ ) {
+ this.qualified = [];
+ for (const g of grants) {
+ if (!g.includes('@')) continue;
+ const parsed = parseGrant(g);
+ if (parsed?.qualifier) this.qualified.push(parsed);
+ }
+ }
+
+ /** The cap narrows by verb and never by layer, so `*:read` over
+ * `metrics:read@GENERAL` leaves `metrics:read@GENERAL`. */
+ private capAllows(verb: Verb): boolean {
+ return this.cap ? hasVerb(this.cap, verb) : true;
+ }
+
+ /** The question every route asked before layer grants existed. A route
+ * that is not about one layer or one service still asks exactly this. */
+ plain(verb: Verb): boolean {
+ return this.capAllows(verb) && hasVerb(this.grants, verb);
+ }
+
+ isOperate(layer: string): boolean {
+ return this.facts.isOperate(this.facts.canonical(layer));
+ }
+
+ /** Does the session hold any layer-limited grant at all? A session with
+ * none sees the menu it has always seen. */
+ hasLayerGrants(): boolean {
+ return this.qualified.length > 0;
+ }
+
+ /** Is `verb` held at all — plainly, or on some layer? */
+ holds(verb: Verb): boolean {
+ if (this.plain(verb)) return true;
+ return this.capAllows(verb) && this.qualified.some((q) => qualifiedVerbCovers(q, verb));
+ }
+
+ /** Is `verb` held only through layer grants (no plain grant)? Decided per
+ * verb: a plain `alarms:read` beside `metrics:read@GENERAL` leaves metrics
+ * layer-limited and alarms not. */
+ layerLimited(verb: Verb): boolean {
+ return !this.plain(verb);
+ }
+
+ onLayer(verb: Verb, layer: string): LayerReach | null {
+ if (!this.capAllows(verb)) return null;
+ const key = this.facts.canonical(layer);
+ if (hasVerb(this.grants, verb) && (!this.facts.isOperate(key) || this.plain('cluster:read'))) {
+ return WHOLE;
+ }
+ let groups: Set<string> | null = null;
+ for (const q of this.qualified) {
+ if (this.facts.canonical(q.qualifier!.layer) !== key || !qualifiedVerbCovers(q, verb)) continue;
+ if (!q.qualifier!.groups) return WHOLE;
+ groups ??= new Set();
+ for (const g of q.qualifier!.groups) groups.add(g);
+ }
+ return groups ? { whole: false, groups } : null;
+ }
+
+ /** Any of `verbs` reaching `layer`, merged. */
+ onLayerAny(verbs: readonly Verb[], layer: string): LayerReach | null {
+ let merged: Set<string> | null = null;
+ for (const v of verbs) {
+ const r = this.onLayer(v, layer);
+ if (!r) continue;
+ if (r.whole) return WHOLE;
+ merged ??= new Set();
+ for (const g of r.groups) merged.add(g);
+ }
+ return merged ? { whole: false, groups: merged } : null;
+ }
+
+ onService(verb: Verb, service: ServiceIdentity): boolean {
+ return this.onServiceAny([verb], service);
+ }
+
+ onServiceAny(verbs: readonly Verb[], service: ServiceIdentity): boolean {
+ // A service OAP reports under no layer cannot be in an operate layer, and
+ // no layer grant can name it.
+ if (service.layers.length === 0) return verbs.some((v) => this.plain(v));
+ return service.layers.some((layer) => {
+ const r = this.onLayerAny(verbs, layer);
+ return r !== null && (r.whole || r.groups.has(service.group));
+ });
+ }
+}
diff --git a/apps/bff/src/rbac/layer-grants.test.ts b/apps/bff/src/rbac/layer-grants.test.ts
new file mode 100644
index 00000000..d8cd469d
--- /dev/null
+++ b/apps/bff/src/rbac/layer-grants.test.ts
@@ -0,0 +1,161 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import {
+ LAYER_PAGE_VERBS,
+ LAYER_SCOPED_VERBS,
+ capGrant,
+ hasVerb,
+ hasVerbOnSomeLayer,
+ isGrantRecognised,
+ parseGrant,
+ resolveVerbsForRoles,
+} from './verbs.js';
+import { SessionAccess, type ServiceIdentity } from './layer-access.js';
+import { ROUTE_POLICY } from './route-policy.js';
+import { ROUTE_SCOPE } from './route-scope.js';
+
+const OPERATE = new Set(['BANYANDB', 'SO11Y_OAP']);
+const facts = {
+ isOperate: (l: string) => OPERATE.has(l),
+ canonical: (l: string) => {
+ const u = l.toUpperCase();
+ return u === 'DATABASE' ? 'VIRTUAL_DATABASE' : u;
+ },
+};
+const access = (grants: string[], cap?: string[]) => new SessionAccess(grants, cap, facts);
+const svc = (group: string, ...layers: string[]): ServiceIdentity => ({
+ id: 'x.1',
+ name: `${group}::x`,
+ normal: true,
+ group,
+ layers,
+});
+
+describe('grant grammar', () => {
+ it('parses a layer and its groups', () => {
+ expect(parseGrant('metrics:read@general')).toEqual({ verb: 'metrics:read', qualifier: { layer: 'GENERAL' } });
+ expect(parseGrant('metrics:read@GENERAL[payments, risk]')).toEqual({
+ verb: 'metrics:read',
+ qualifier: { layer: 'GENERAL', groups: ['payments', 'risk'] },
+ });
+ expect(parseGrant('logs:read@GENERAL[-]')?.qualifier?.groups).toEqual(['']);
+ });
+
+ it('refuses a malformed qualifier rather than widening it', () => {
+ for (const bad of ['metrics:read@', '@GENERAL', 'metrics:read@GENERAL[]', 'metrics:read@GENERAL[a,,b]', 'metrics:read@GENERAL[a]x']) {
+ expect(parseGrant(bad)).toBeNull();
+ expect(isGrantRecognised(bad)).toBe(false);
+ }
+ });
+
+ it('never lets a layer grant answer a question without a layer', () => {
+ for (const g of ['metrics:read@GENERAL', '*:read@GENERAL', '*@GENERAL', 'metrics:*@GENERAL']) {
+ expect(hasVerb([g], 'metrics:read')).toBe(false);
+ expect(hasVerbOnSomeLayer([g], 'metrics:read')).toBe(true);
+ }
+ expect(hasVerbOnSomeLayer(['metrics:read@GENERAL'], 'overview:read')).toBe(false);
+ });
+
+ it('grants nothing on a verb whose data has no layer, nor through admin', () => {
+ for (const g of ['cluster:read@GENERAL', 'overview:read@GENERAL', 'admin@GENERAL', 'audit:read@GENERAL']) {
+ expect(isGrantRecognised(g)).toBe(false);
+ expect(hasVerbOnSomeLayer([g], g.split('@')[0]!)).toBe(false);
+ }
+ expect(hasVerbOnSomeLayer(['*@GENERAL'], 'audit:read')).toBe(false);
+ expect(hasVerbOnSomeLayer(['*:read@GENERAL'], 'cluster:read')).toBe(false);
+ });
+
+ it('does not expand a retired name written with a layer', () => {
+ const verbs = resolveVerbsForRoles({ r: ['dashboard:read@GENERAL'] }, ['r'], true);
+ expect(verbs).toEqual(['dashboard:read@GENERAL']);
+ expect(hasVerb(verbs, 'layer-template:read')).toBe(false);
+ });
+
+ it('caps a layer grant by verb and keeps its layer', () => {
+ expect(capGrant('metrics:*@GENERAL[a]', ['*:read'])).toEqual(['metrics:read@GENERAL[a]']);
+ expect(capGrant('profile:enable@GENERAL', ['*:read'])).toEqual([]);
+ expect(capGrant('metrics:read@GENERAL', undefined)).toEqual(['metrics:read@GENERAL']);
+ });
+
+ it('lists every verb a layer route needs among the layer-scoped verbs', () => {
+ for (const [key, policy] of Object.entries(ROUTE_POLICY)) {
+ if (!key.includes(' /api/layer/:key/')) continue;
+ const verbs =
+ typeof policy === 'string' ? [policy] : Array.isArray(policy) ? policy : 'anyOf' in policy ? policy.anyOf : [];
+ for (const v of verbs) expect(LAYER_SCOPED_VERBS.has(v), `${key} → ${v}`).toBe(true);
+ }
+ for (const v of LAYER_PAGE_VERBS) expect(LAYER_SCOPED_VERBS.has(v)).toBe(true);
+ });
+
+ it('keys every scope rule on a route the policy table knows', () => {
+ for (const key of Object.keys(ROUTE_SCOPE)) expect(ROUTE_POLICY[key], key).toBeDefined();
+ });
+});
+
+describe('which layers a session reaches', () => {
+ it('a plain verb reaches every layer but the operate ones', () => {
+ const a = access(['metrics:read']);
+ expect(a.onLayer('metrics:read', 'general')?.whole).toBe(true);
+ expect(a.onLayer('metrics:read', 'banyandb')).toBeNull();
+ });
+
+ it('cluster:read opens the operate layers to a plain verb', () => {
+ expect(access(['metrics:read', 'cluster:read']).onLayer('metrics:read', 'BANYANDB')?.whole).toBe(true);
+ });
+
+ it('an explicit layer grant opens an operate layer without cluster:read', () => {
+ const a = access(['metrics:read@BANYANDB']);
+ expect(a.onLayer('metrics:read', 'BANYANDB')?.whole).toBe(true);
+ expect(a.onLayer('metrics:read', 'GENERAL')).toBeNull();
+ expect(a.plain('metrics:read')).toBe(false);
+ });
+
+ it('merges groups across grants and roles, and folds OAP layer aliases', () => {
+ const a = access(['metrics:read@GENERAL[payments]', 'metrics:read@general[risk]', 'metrics:read@DATABASE']);
+ const r = a.onLayer('metrics:read', 'GENERAL');
+ expect(r?.whole).toBe(false);
+ expect([...(r?.groups ?? [])].sort()).toEqual(['payments', 'risk']);
+ expect(a.onLayer('metrics:read', 'VIRTUAL_DATABASE')?.whole).toBe(true);
+ });
+
+ it('decides layer-limited per verb', () => {
+ const a = access(['alarms:read', 'metrics:read@GENERAL']);
+ expect(a.layerLimited('metrics:read')).toBe(true);
+ expect(a.layerLimited('alarms:read')).toBe(false);
+ });
+
+ it('reads a service through any layer it reports into, for its group only', () => {
+ const a = access(['metrics:read@MESH[mesh-svr]']);
+ expect(a.onService('metrics:read', svc('mesh-svr', 'MESH', 'MESH_DP'))).toBe(true);
+ expect(a.onService('metrics:read', svc('other', 'MESH'))).toBe(false);
+ expect(a.onService('metrics:read', svc('mesh-svr', 'MESH_DP'))).toBe(false);
+ });
+
+ it('keeps a service that lives only in an operate layer from a plain viewer', () => {
+ expect(access(['metrics:read']).onService('metrics:read', svc('', 'BANYANDB'))).toBe(false);
+ expect(access(['metrics:read']).onService('metrics:read', svc('', 'BANYANDB', 'K8S_SERVICE'))).toBe(true);
+ });
+
+ it('narrows by the OAuth cap, never widens', () => {
+ const a = access(['metrics:*@GENERAL', 'profile:enable'], ['*:read']);
+ expect(a.onLayer('metrics:read', 'GENERAL')?.whole).toBe(true);
+ expect(a.onLayer('profile:enable', 'GENERAL')).toBeNull();
+ expect(a.holds('profile:enable')).toBe(false);
+ });
+});
diff --git a/apps/bff/src/rbac/policy.ts b/apps/bff/src/rbac/policy.ts
index 6caa9469..73efdbca 100644
--- a/apps/bff/src/rbac/policy.ts
+++ b/apps/bff/src/rbac/policy.ts
@@ -22,7 +22,7 @@
*/
import type { HorizonConfig } from '../config/schema.js';
-import { hasVerb, resolveVerbsForRoles } from './verbs.js';
+import { hasVerb, hasVerbOnSomeLayer, resolveVerbsForRoles } from './verbs.js';
/**
* Whoever a verb is being checked FOR. Takes the session rather than its roles
@@ -50,3 +50,16 @@ export function sessionHasVerb(
if (!hasVerb(verbs, required)) return false;
return subject.verbCap ? hasVerb(subject.verbCap, required) : true;
}
+
+/** The same question for a route that reads one layer or one service: a
+ * layer grant counts here, and which layer it reaches is the scope gate's
+ * to decide. */
+export function sessionHasVerbOnSomeLayer(
+ config: HorizonConfig,
+ subject: VerbSubject,
+ required: string,
+): boolean {
+ const verbs = resolveVerbsForRoles(config.rbac.roles, subject.roles, config.rbac.enabled);
+ if (!hasVerbOnSomeLayer(verbs, required)) return false;
+ return subject.verbCap ? hasVerb(subject.verbCap, required) : true;
+}
diff --git a/apps/bff/src/rbac/request-access.test.ts b/apps/bff/src/rbac/request-access.test.ts
new file mode 100644
index 00000000..d984a2df
--- /dev/null
+++ b/apps/bff/src/rbac/request-access.test.ts
@@ -0,0 +1,209 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../config/schema.js';
+import type { ConfigSource } from '../config/loader.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from '../logic/services/service-layer-catalog.js';
+import { isExactIdentity, RequestAccess } from './request-access.js';
+import { ServiceIdentityResolver, ServiceLookupUnavailable, serviceIdOf } from '../logic/services/service-identity.js';
+import { SessionAccess } from './layer-access.js';
+
+const cfg = configSchema.parse({});
+const config: ConfigSource = { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+const facts = { isOperate: (l: string) => l === 'BANYANDB', canonical: (l: string) => l.toUpperCase() };
+const BDB = { id: serviceIdOf('showcase-banyandb', true), name: 'showcase-banyandb', normal: true, group: '' };
+
+const oap = (answer: 'down' | 'none' | 'banyandb'): FetchLike => async () => {
+ if (answer === 'down') throw new Error('ETIMEDOUT');
+ const service = answer === 'none' ? null : { ...BDB, layers: ['BANYANDB'] };
+ return new Response(JSON.stringify({ data: { service } }), { status: 200, headers: { 'content-type': 'application/json' } });
+};
+
+function viewer(snapshot: ServiceCatalog, fetch: FetchLike): RequestAccess {
+ const catalog = { get: async () => snapshot } as unknown as ServiceLayerCatalog;
+ const services = new ServiceIdentityResolver({ config, fetch, catalog });
+ return new RequestAccess(new SessionAccess(['metrics:read'], undefined, facts), services);
+}
+
+const empty: ServiceCatalog = { layers: [], byLayer: new Map(), byName: new Map() };
+
+describe('a service lookup that could not be answered', () => {
+ it('refuses rather than taking "unavailable" as "unknown"', async () => {
+ expect(await viewer(empty, oap('down')).allows(['metrics:read'], { id: BDB.id })).toBe(false);
+ });
+
+ it('still lets a plain verb name a service OAP answers it does not know', async () => {
+ expect(await viewer(empty, oap('none')).allows(['metrics:read'], { id: BDB.id })).toBe(true);
+ });
+});
+
+describe('a catalog kept through a failed refresh', () => {
+ it('re-checks its rows with OAP before they decide access', async () => {
+ // The retained row still says GENERAL; OAP now says BANYANDB only.
+ const stale: ServiceCatalog = {
+ layers: ['GENERAL'],
+ byLayer: new Map([['GENERAL', [BDB]]]),
+ byName: new Map(),
+ unreachable: true,
+ stale: true,
+ };
+ expect(await viewer(stale, oap('banyandb')).allows(['metrics:read'], { id: BDB.id })).toBe(false);
+ expect(await viewer(stale, oap('down')).allows(['metrics:read'], { id: BDB.id })).toBe(false);
+ });
+
+ it('trusts rows read in the last few minutes, and re-checks older ones', async () => {
+ const retained = (ageMs: number): ServiceCatalog => ({
+ layers: ['GENERAL'],
+ byLayer: new Map([['GENERAL', [BDB]]]),
+ byName: new Map(),
+ unreachable: true,
+ stale: true,
+ readAt: Date.now() - ageMs,
+ });
+ expect(await viewer(retained(60_000), oap('down')).allows(['metrics:read'], { id: BDB.id })).toBe(true);
+ expect(await viewer(retained(10 * 60_000), oap('banyandb')).allows(['metrics:read'], { id: BDB.id })).toBe(false);
+ });
+});
+
+describe('an empty identity', () => {
+ it('reads every service for a plain verb, as before, and nothing for a layer-limited one', async () => {
+ expect(await viewer(empty, oap('down')).allows(['metrics:read'], { id: '' })).toBe(true);
+ const catalog = { get: async () => empty } as unknown as ServiceLayerCatalog;
+ const services = new ServiceIdentityResolver({ config, fetch: oap('down'), catalog });
+ const limited = new RequestAccess(new SessionAccess(['metrics:read@GENERAL'], undefined, facts), services);
+ expect(await limited.allows(['metrics:read'], { id: '' })).toBe(false);
+ expect(await limited.allows(['metrics:read'], { name: '' })).toBe(false);
+ });
+});
+
+describe('an identity OAP reads exactly as written', () => {
+ it('refuses what OAP would trim, fold to _blank, or encode differently', () => {
+ expect(isExactIdentity('payments::checkout')).toBe(true);
+ expect(isExactIdentity('支付::结账 🚀')).toBe(true);
+ for (const v of ['', ' ', 'a ', '\u0000', 'a\u0007b', 'a\uD800', '\uDC00a']) expect(isExactIdentity(v), JSON.stringify(v)).toBe(false);
+ });
+});
+
+describe('filtering the rows of a read that named no service', () => {
+ it('reports an ownership lookup OAP could not answer instead of dropping the row', async () => {
+ const rows = [{ serviceId: BDB.id }];
+ await expect(viewer(empty, oap('down')).keepReadable(['metrics:read'], rows, (r) => ({ id: r.serviceId }))).rejects.toBeInstanceOf(
+ ServiceLookupUnavailable,
+ );
+ expect(await viewer(empty, oap('none')).keepReadable(['metrics:read'], rows, (r) => ({ id: r.serviceId }))).toEqual(rows);
+ });
+
+ it('asks nothing for a caller who reads every layer', async () => {
+ const catalog = { get: async () => empty } as unknown as ServiceLayerCatalog;
+ const services = new ServiceIdentityResolver({ config, fetch: oap('down'), catalog });
+ const everyLayer = new RequestAccess(new SessionAccess(['metrics:read', 'cluster:read'], undefined, facts), services);
+ const rows = [{ serviceId: BDB.id }];
+ expect(await everyLayer.keepReadable(['metrics:read'], rows, (r) => ({ id: r.serviceId }))).toEqual(rows);
+ });
+});
+
+describe('a graph whose metrics read by name alone', () => {
+ const cfg = {
+ nodeMetrics: [
+ { id: 'cpm', mqe: 'service_cpm' },
+ { id: 'predicted', mqe: 'baseline(service_cpm,value)' },
+ ],
+ };
+ const real = { id: serviceIdOf('payments::a', true), name: 'payments::a', normal: true, group: 'payments' };
+ const conjectured = { ...real, id: serviceIdOf('payments::a', false), normal: false };
+ const catalogOf = (withNamesake: boolean): ServiceCatalog => ({
+ layers: ['GENERAL', 'VIRTUAL_DATABASE'],
+ byLayer: new Map([
+ ['GENERAL', [real]],
+ ['VIRTUAL_DATABASE', withNamesake ? [conjectured] : []],
+ ]),
+ byName: new Map(),
+ });
+ const access = (grants: string[], withNamesake: boolean) => {
+ const catalog = { get: async () => catalogOf(withNamesake) } as unknown as ServiceLayerCatalog;
+ const services = new ServiceIdentityResolver({ config, fetch: oap('none'), catalog });
+ return new RequestAccess(new SessionAccess(grants, undefined, facts), services);
+ };
+ const ids = (c: typeof cfg) => c.nodeMetrics.map((m) => m.id);
+
+ it('keeps them when every service of the focus name is readable', async () => {
+ expect(ids(await access(['topology:read@GENERAL[payments]'], false).graphConfig(['topology:read'], [real.id], cfg))).toEqual(['cpm', 'predicted']);
+ });
+
+ it('leaves them out when a namesake is not, and on a layer-wide map for a limited caller', async () => {
+ const limited = access(['topology:read@GENERAL[payments]'], true);
+ expect(ids(await limited.graphConfig(['topology:read'], [real.id], cfg))).toEqual(['cpm']);
+ expect(ids(await access(['topology:read@GENERAL[payments]'], false).graphConfig(['topology:read'], [], cfg))).toEqual(['cpm']);
+ });
+
+ it('leaves them out for a focus OAP does not know, which still has a name to answer for', async () => {
+ const unknownFocus = serviceIdOf('payments::a', false);
+ expect(ids(await access(['topology:read'], false).graphConfig(['topology:read'], [unknownFocus], cfg))).toEqual(['cpm']);
+ });
+
+ it('checks the name MQE sends: a blank one is `_blank`, which another service may carry', async () => {
+ // A conjectured service with a blank name, and a real one literally named
+ // `_blank` that reports only into an operate layer. Both answer to `_blank`.
+ const blank = { id: serviceIdOf('_blank', false), name: '', normal: false, group: '' };
+ const literal = { id: serviceIdOf('_blank', true), name: '_blank', normal: true, group: '' };
+ const catalog = {
+ get: async (): Promise<ServiceCatalog> => ({
+ layers: ['GENERAL', 'BANYANDB'],
+ byLayer: new Map([
+ ['GENERAL', [blank]],
+ ['BANYANDB', [literal]],
+ ]),
+ byName: new Map(),
+ }),
+ } as unknown as ServiceLayerCatalog;
+ const services = new ServiceIdentityResolver({ config, fetch: oap('none'), catalog });
+ const plain = new RequestAccess(new SessionAccess(['topology:read'], undefined, facts), services);
+ expect(ids(await plain.graphConfig(['topology:read'], [blank.id], cfg))).toEqual(['cpm']);
+ });
+
+ it('keeps them for a caller who reads every layer', async () => {
+ expect(ids(await access(['topology:read', 'cluster:read'], true).graphConfig(['topology:read'], [], cfg))).toEqual(['cpm', 'predicted']);
+ });
+});
+
+describe('a name that also addresses the blank-named service', () => {
+ it('reads every service filed under it, whichever name the roster shows', async () => {
+ // A conjectured service literally named `_blank`, readable to a viewer, and
+ // a real service with an empty name, which OAP files under `_blank` too and
+ // which reports only into an operate layer.
+ const literal = { id: serviceIdOf('_blank', false), name: '_blank', normal: false, group: '' };
+ const blankNamed = { id: serviceIdOf('', true), name: '', normal: true, group: '' };
+ expect(blankNamed.id).toBe(serviceIdOf('_blank', true));
+ const snapshot: ServiceCatalog = {
+ layers: ['VIRTUAL_DATABASE', 'BANYANDB'],
+ byLayer: new Map([
+ ['VIRTUAL_DATABASE', [literal]],
+ ['BANYANDB', [blankNamed]],
+ ]),
+ byName: new Map(),
+ };
+ expect(await viewer(snapshot, oap('none')).allows(['metrics:read'], { name: '_blank' })).toBe(false);
+ expect(await viewer(snapshot, oap('none')).allows(['metrics:read'], { id: literal.id })).toBe(true);
+ // An empty name is that same service, not the absence of one: a row that
+ // carries it is decided like any other.
+ expect(await viewer(snapshot, oap('none')).allows(['metrics:read'], { name: '' })).toBe(false);
+ const rows = [{ service: '' }, { service: ' ' }];
+ expect(await viewer(snapshot, oap('none')).keepReadable(['metrics:read'], rows, (r) => ({ name: r.service }))).toEqual([]);
+ });
+});
diff --git a/apps/bff/src/rbac/request-access.ts b/apps/bff/src/rbac/request-access.ts
new file mode 100644
index 00000000..e8014e72
--- /dev/null
+++ b/apps/bff/src/rbac/request-access.ts
@@ -0,0 +1,301 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * One request's answer to "may this caller read that": the session's grants,
+ * the operate-layer classification and the service resolver, bound together.
+ * Route pre-handlers, handlers that filter rosters, and the AI / MCP tool
+ * context all ask through this, so the three cannot drift apart.
+ *
+ * An identity OAP answers it does not know is allowed for a PLAIN verb, which
+ * is what every request did before layer grants existed: an operate-layer
+ * service is always one OAP knows, so nothing that rule protects slips
+ * through. For a LAYER-LIMITED verb it is refused. An identity OAP could not
+ * be asked about decides nothing either way; the gate reports it as an outage.
+ */
+
+import type { HorizonConfig } from '../config/schema.js';
+import type { LayerClassification } from '../logic/layers/operate-layers.js';
+import { canonicalLayerKey } from '../logic/templates/identity.js';
+import {
+ ServiceLookupUnavailable,
+ entityServiceName,
+ isBlankToOap,
+ serviceIdOf,
+ serviceIdOfChild,
+ type ResolvedService,
+ type ServiceIdentityResolver,
+} from '../logic/services/service-identity.js';
+import { SessionAccess, type LayerReach } from './layer-access.js';
+import type { VerbSubject } from './policy.js';
+import { LAYER_PAGE_VERBS, resolveVerbsForRoles, type Verb } from './verbs.js';
+
+export interface AccessDeps {
+ services: ServiceIdentityResolver;
+ classify(): Promise<LayerClassification>;
+}
+
+/** A service named by the request, in whichever form it arrived. */
+export type ServiceRef =
+ | { id: string }
+ | { name: string; normal?: boolean }
+ /** Instance / endpoint / browser-version / page-path id: owned by the service in its prefix. */
+ | { childId: string }
+ /** Either an id or a name — the dashboard and evaluation-record `service` field. */
+ | { idOrName: string };
+
+export type Resolution =
+ | { kind: 'found'; services: ResolvedService[] }
+ /** OAP answered: no such service. */
+ | { kind: 'unknown' }
+ /** OAP could not be asked — never taken as an answer. */
+ | { kind: 'unavailable' };
+
+/** MQE functions OAP evaluates by the service NAME alone — `baseline` looks up
+ * its prediction by name, whatever the entity's `normal` says — so they read
+ * every service the name can mean. */
+const NAME_ONLY_MQE = /\bbaseline\s*\(/;
+
+export function readsByNameOnly(expressions: readonly string[]): boolean {
+ return expressions.some((e) => NAME_ONLY_MQE.test(e));
+}
+
+/** A graph metric definition (`{ mqe }`, in any template graph block) that
+ * reads by service name alone. */
+function isNameOnlyMetric(v: unknown): boolean {
+ const mqe = v && typeof v === 'object' ? (v as { mqe?: unknown }).mqe : undefined;
+ return typeof mqe === 'string' && NAME_ONLY_MQE.test(mqe);
+}
+
+function hasNameOnlyMetric(v: unknown): boolean {
+ if (isNameOnlyMetric(v)) return true;
+ if (Array.isArray(v)) return v.some(hasNameOnlyMetric);
+ return !!v && typeof v === 'object' && Object.values(v).some(hasNameOnlyMetric);
+}
+
+function withoutNameOnlyMetrics(v: unknown): unknown {
+ if (Array.isArray(v)) return v.filter((x) => !isNameOnlyMetric(x)).map(withoutNameOnlyMetrics);
+ if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, withoutNameOnlyMetrics(x)]));
+ return v;
+}
+
+const SERVICE_ID = /^[A-Za-z0-9+/=]+\.[01]$/;
+
+// eslint-disable-next-line no-control-regex
+const CONTROL = /[\u0000-\u001f\u007f]/;
+const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
+
+/**
+ * Does OAP read this service name, or id, exactly as written? OAP trims a name
+ * (Java's `trim()`, which also drops control characters) and reads a blank one
+ * as `_blank`; its encoder writes a lone UTF-16 surrogate as `?` where Node's
+ * writes U+FFFD. Any of those makes the service checked differ from the one
+ * read, so such an identity is refused rather than interpreted.
+ */
+export function isExactIdentity(v: string): boolean {
+ return v !== '' && v === v.trim() && !CONTROL.test(v) && !LONE_SURROGATE.test(v);
+}
+
+
+export class RequestAccess {
+ constructor(
+ readonly session: SessionAccess,
+ private readonly services: ServiceIdentityResolver,
+ private readonly signal?: AbortSignal,
+ ) {}
+
+ plain(verb: Verb): boolean {
+ return this.session.plain(verb);
+ }
+
+ isOperate(layer: string): boolean {
+ return this.session.isOperate(layer);
+ }
+
+ /**
+ * Should the sidebar show this layer (and, when it is split, this group's
+ * entry)? A session with no layer grant sees exactly the menu it always
+ * has: every layer, with the operate layers only for `cluster:read`. A
+ * session with layer grants sees the layers its page verbs reach.
+ */
+ menuShows(layer: string, group?: string): boolean {
+ if (!this.session.hasLayerGrants()) return !this.isOperate(layer) || this.plain('cluster:read');
+ const reach = this.onLayer(LAYER_PAGE_VERBS, layer);
+ if (!reach) return false;
+ return reach.whole || group === undefined || reach.groups.has(group);
+ }
+
+ /** Holds one of `verbs` on every layer, operate layers included, so nothing
+ * a request names can be out of reach. */
+ readsEveryLayer(verbs: readonly Verb[]): boolean {
+ return verbs.some((v) => this.plain(v)) && this.plain('cluster:read');
+ }
+
+ /** Every verb in `verbs` is held only through layer grants. */
+ layerLimited(verbs: readonly Verb[]): boolean {
+ return verbs.every((v) => this.session.layerLimited(v));
+ }
+
+ onLayer(verbs: readonly Verb[], layer: string): LayerReach | null {
+ return this.session.onLayerAny(verbs, layer);
+ }
+
+ private readonly resolved = new Map<string, Promise<Resolution>>();
+
+ resolve(ref: ServiceRef): Promise<Resolution> {
+ const key = JSON.stringify(ref);
+ let r = this.resolved.get(key);
+ if (!r) {
+ r = this.lookup(ref).catch((err: unknown) => {
+ if (err instanceof ServiceLookupUnavailable) return { kind: 'unavailable' } as const;
+ throw err;
+ });
+ this.resolved.set(key, r);
+ }
+ return r;
+ }
+
+ private async lookup(ref: ServiceRef): Promise<Resolution> {
+ // A name means the service OAP files it under — a blank one is `_blank`.
+ // An empty id names no service at all.
+ let found: ResolvedService[] | null = null;
+ if ('id' in ref) {
+ if (isBlankToOap(ref.id)) return { kind: 'unknown' };
+ const one = await this.services.byId(ref.id, this.signal);
+ found = one ? [one] : null;
+ } else if ('childId' in ref) {
+ if (isBlankToOap(ref.childId)) return { kind: 'unknown' };
+ const owner = serviceIdOfChild(ref.childId);
+ const one = owner ? await this.services.byId(owner, this.signal) : null;
+ found = one ? [one] : null;
+ } else if ('idOrName' in ref) {
+ if (SERVICE_ID.test(ref.idOrName)) {
+ const one = await this.services.byId(ref.idOrName, this.signal);
+ if (one) found = [one];
+ }
+ found ??= await this.services.byName(entityServiceName(ref.idOrName), undefined, this.signal);
+ } else {
+ found = await this.services.byName(entityServiceName(ref.name), ref.normal, this.signal);
+ }
+ return found && found.length > 0 ? { kind: 'found', services: found } : { kind: 'unknown' };
+ }
+
+ /** May the caller read this service with any of `verbs`? A name that can
+ * mean several services must be allowed for every one of them. */
+ async allows(verbs: readonly Verb[], ref: ServiceRef): Promise<boolean> {
+ return (await this.decide(verbs, ref)) === 'allow';
+ }
+
+ /** {@link allows}, keeping "OAP could not be asked" apart from "no": the
+ * first is an outage to report as one, not a refusal. */
+ async decide(verbs: readonly Verb[], ref: ServiceRef): Promise<'allow' | 'deny' | 'unavailable'> {
+ const r = await this.resolve(ref);
+ if (r.kind === 'unavailable') return 'unavailable';
+ if (r.kind === 'unknown') return verbs.some((v) => this.session.plain(v)) ? 'allow' : 'deny';
+ return r.services.every((s) => this.allowsResolved(verbs, s)) ? 'allow' : 'deny';
+ }
+
+ /**
+ * The graph block a caller may evaluate. A graph's metrics run for every
+ * node it draws, and a `baseline` among them reads a service by name alone —
+ * the real service and any conjectured namesake. Such metrics stay only when
+ * every name of the FOCUS services (`focusIds` the caller reads; other ends
+ * are drawn as neighbours) is readable, as MQE sends it. A layer-wide map
+ * with no focus keeps them for a caller holding the verb plainly, as before
+ * layer grants existed. Otherwise they are left out of the graph, as a
+ * refused landing column is.
+ */
+ async graphConfig<T>(verbs: readonly Verb[], focusIds: readonly string[], cfg: T): Promise<T> {
+ if (!hasNameOnlyMetric(cfg) || this.readsEveryLayer(verbs)) return cfg;
+ if (focusIds.length === 0 && !this.layerLimited(verbs)) return cfg;
+ let keep = true;
+ let checked = 0;
+ for (const id of focusIds) {
+ if ((await this.decide(verbs, { id })) !== 'allow') continue;
+ checked++;
+ const r = await this.resolve({ id });
+ // A focus OAP does not know has no name to check, but OAP still answers
+ // a `baseline` for whatever name the request carries.
+ if (r.kind !== 'found') keep = false;
+ else {
+ for (const s of r.services) {
+ if ((await this.decide(verbs, { name: entityServiceName(s.name) })) !== 'allow') keep = false;
+ }
+ }
+ }
+ return keep && checked > 0 ? cfg : (withoutNameOnlyMetrics(cfg) as T);
+ }
+
+ /** For a read that named no service: keep the rows of services the caller
+ * may read, each decided by the service it carries — an empty name is the
+ * service OAP files under `_blank`, not the absence of one. Throws
+ * {@link ServiceLookupUnavailable} when OAP could not say whose a row is:
+ * dropping it would pass a partial answer off as whole. */
+ async keepReadable<T>(verbs: readonly Verb[], rows: readonly T[], refOf: (row: T) => ServiceRef): Promise<T[]> {
+ if (this.readsEveryLayer(verbs)) return [...rows];
+ const out: T[] = [];
+ for (const row of rows) {
+ const d = await this.decide(verbs, refOf(row));
+ if (d === 'unavailable') throw new ServiceLookupUnavailable('OAP did not answer which service a row belongs to');
+ if (d === 'allow') out.push(row);
+ }
+ return out;
+ }
+
+ /** Synchronous check for a service the caller already resolved (a roster
+ * row, a catalog entry). */
+ allowsResolved(verbs: readonly Verb[], service: ResolvedService): boolean {
+ if (this.blankIsOutOfReach(verbs, service.name)) return false;
+ return this.session.onServiceAny(verbs, service);
+ }
+
+ /** OAP lists its blank-named service with the name it was registered
+ * under, and files its data under `_blank`. No layer grant is meant to
+ * reach it, so a layer-limited caller may not read through it. */
+ private blankIsOutOfReach(verbs: readonly Verb[], name: string | undefined): boolean {
+ return name !== undefined && isBlankToOap(name) && this.layerLimited(verbs);
+ }
+
+ /** Keep the roster rows of `layer` the caller may read. Rows carry their
+ * own group; the layer is the one they were listed under. */
+ filterRoster<T extends { group?: string | null; name?: string }>(verbs: readonly Verb[], layer: string, rows: T[]): T[] {
+ const reach = this.onLayer(verbs, layer);
+ if (!reach) return [];
+ const named = rows.filter((r) => !this.blankIsOutOfReach(verbs, r.name));
+ if (reach.whole) return named;
+ return named.filter((r) => reach.groups.has(r.group ?? ''));
+ }
+}
+
+export function serviceRefFromName(name: string, normal?: boolean): ServiceRef {
+ return normal === undefined ? { name } : { id: serviceIdOf(name, normal) };
+}
+
+export async function buildRequestAccess(
+ config: HorizonConfig,
+ subject: VerbSubject,
+ deps: AccessDeps,
+ signal?: AbortSignal,
+): Promise<RequestAccess> {
+ const grants = resolveVerbsForRoles(config.rbac.roles, subject.roles, config.rbac.enabled);
+ const classification = await deps.classify();
+ const session = new SessionAccess(grants, subject.verbCap, {
+ isOperate: (layer) => classification.isOperate(layer),
+ canonical: canonicalLayerKey,
+ });
+ return new RequestAccess(session, deps.services, signal);
+}
diff --git a/apps/bff/src/rbac/route-policy.test.ts b/apps/bff/src/rbac/route-policy.test.ts
index 3400e688..8ecd25b2 100644
--- a/apps/bff/src/rbac/route-policy.test.ts
+++ b/apps/bff/src/rbac/route-policy.test.ts
@@ -28,6 +28,7 @@ import {
import { setTemplateReadOnly } from '../logic/templates/sync.js';
import { configSchema } from '../config/schema.js';
import type { AuthDeps } from '../user/middleware.js';
+import { LAYER_PAGE_VERBS } from './verbs.js';
describe('isTemplateWriteRoute — which routes the readonly backstop covers', () => {
it('matches non-GET config-template write routes', () => {
@@ -186,7 +187,7 @@ describe('denyTemplateWriteWhenReadOnly — the BFF backstop', () => {
});
describe('evaluation record selector route policies', () => {
const config = configSchema.parse({ rbac: { roles: {
- 'metrics-only': ['metrics:read'], 'logs-only': ['logs:read'], empty: [],
+ 'metrics-only': ['metrics:read'], 'logs-only': ['logs:read'], 'alarms-only': ['alarms:read@GENERAL[risk]'], empty: [],
} } });
const deps = { config: { current: config } } as unknown as AuthDeps;
type PreHandler = (req: FastifyRequest, reply: FastifyReply) => Promise<void>;
@@ -205,14 +206,16 @@ describe('evaluation record selector route policies', () => {
expect(gate).toBeDefined();
return run(gate!, role);
}
- it('allows either metrics:read or logs:read', async () => {
- for (const route of ['GET /api/layer/:key/instances']) {
+ it('allows any permission that opens a layer page, and alarms:read, whose page narrows by them', async () => {
+ for (const route of ['GET /api/layer/:key/instances', 'GET /api/layer/:key/endpoints']) {
expect(await decide(route, 'logs-only')).toEqual({});
expect(await decide(route, 'metrics-only')).toEqual({});
+ expect(await decide(route, 'alarms-only')).toEqual({});
}
});
it('denies a role with neither permission', async () => {
- expect(await decide('GET /api/layer/:key/instances', 'empty')).toEqual({ code: 403, body: { error: 'permission_denied', verb: 'metrics:read or logs:read' } });
+ const verb = [...LAYER_PAGE_VERBS, 'alarms:read'].join(' or ');
+ expect(await decide('GET /api/layer/:key/instances', 'empty')).toEqual({ code: 403, body: { error: 'permission_denied', verb } });
});
it('requires metrics:read for landing and permits logs:read on the evaluation catalog', async () => {
expect(await decide('POST /api/layer/:key/landing', 'logs-only')).toEqual({ code: 403, body: { error: 'permission_denied', verb: 'metrics:read' } });
diff --git a/apps/bff/src/rbac/route-policy.ts b/apps/bff/src/rbac/route-policy.ts
index db1e75d3..46d57e27 100644
--- a/apps/bff/src/rbac/route-policy.ts
+++ b/apps/bff/src/rbac/route-policy.ts
@@ -29,8 +29,15 @@
*/
import type { FastifyReply, FastifyRequest, RouteOptions } from 'fastify';
-import { sessionHasVerb } from './policy.js';
+import { sessionHasVerb, sessionHasVerbOnSomeLayer } from './policy.js';
import type { AuthDeps } from '../user/middleware.js';
+import type { AccessDeps } from './request-access.js';
+import { ROUTE_SCOPE } from './route-scope.js';
+import { scopeGate } from './scope-gate.js';
+import { LAYER_PAGE_VERBS, LAYER_SCOPED_VERBS } from './verbs.js';
+
+/** Any verb that opens a layer page may fill that page's pickers. */
+const LAYER_PICKER_VERBS: readonly string[] = LAYER_PAGE_VERBS;
import { requireAuth } from '../user/middleware.js';
import { isTemplateReadOnly } from '../logic/templates/sync.js';
import { logger } from '../logger.js';
@@ -68,7 +75,8 @@ export async function denyTemplateWriteWhenReadOnly(
* conjunction — all are required, and the first one the session lacks is the
* one reported back.
*/
-export function checkVerb(deps: AuthDeps, verb: string | readonly string[]) {
+export function checkVerb(deps: AuthDeps, verb: string | readonly string[], onSomeLayer = false) {
+ const has = onSomeLayer ? sessionHasVerbOnSomeLayer : sessionHasVerb;
const required = typeof verb === 'string' ? [verb] : verb;
return async function verbOnlyPreHandler(req: FastifyRequest, reply: FastifyReply): Promise<void> {
const session = req.session;
@@ -76,18 +84,19 @@ export function checkVerb(deps: AuthDeps, verb: string | readonly string[]) {
return void reply.code(401).send({ error: 'unauthenticated' });
}
for (const v of required) {
- if (!sessionHasVerb(deps.config.current, session, v)) {
+ if (!has(deps.config.current, session, v)) {
return void reply.code(403).send({ error: 'permission_denied', verb: v });
}
}
};
}
-export function checkAnyVerb(deps: AuthDeps, verbs: readonly string[]) {
+export function checkAnyVerb(deps: AuthDeps, verbs: readonly string[], onSomeLayer = false) {
+ const has = onSomeLayer ? sessionHasVerbOnSomeLayer : sessionHasVerb;
return async function anyVerbPreHandler(req: FastifyRequest, reply: FastifyReply): Promise<void> {
const session = req.session;
if (!session) return void reply.code(401).send({ error: 'unauthenticated' });
- if (verbs.some((verb) => sessionHasVerb(deps.config.current, session, verb))) return;
+ if (verbs.some((verb) => has(deps.config.current, session, verb))) return;
return void reply.code(403).send({ error: 'permission_denied', verb: verbs.join(' or ') });
};
}
@@ -200,9 +209,14 @@ export const ROUTE_POLICY: Record<string, RoutePolicy> = {
'POST /api/mqe/exec': 'metrics:read',
'GET /api/layer/:key/dashboard/config': 'metrics:read',
'POST /api/layer/:key/landing': 'metrics:read',
- 'GET /api/layer/:key/instances': { anyOf: ['metrics:read', 'logs:read'] },
- 'GET /api/layer/:key/endpoints': 'metrics:read',
- 'GET /api/layer/:key/services': 'metrics:read',
+ // The instance and endpoint pickers sit on every layer tab, like the
+ // service picker, and narrow the Alarms page too; the grant still decides
+ // whose instances they list.
+ 'GET /api/layer/:key/instances': { anyOf: [...LAYER_PICKER_VERBS, 'alarms:read'] },
+ 'GET /api/layer/:key/endpoints': { anyOf: [...LAYER_PICKER_VERBS, 'alarms:read'] },
+ // Every layer tab picks a service here, so any verb that opens a layer page
+ // may list its services; which services is the caller's grant.
+ 'GET /api/layer/:key/services': { anyOf: LAYER_PICKER_VERBS },
'GET /api/evaluation-record/caller-services': 'logs:read',
// Profiling reads — task-creation is operator (profile:enable) below.
@@ -357,7 +371,21 @@ export const ROUTE_POLICY: Record<string, RoutePolicy> = {
* double-auth call is O(1) and the cost is negligible compared with
* the upstream OAP fetch most handlers perform.
*/
-export function makeRouteAuthHook(deps: AuthDeps) {
+/** The verbs a policy names; empty for 'public' / 'auth'. */
+function policyVerbs(p: RoutePolicy): string[] {
+ if (p === 'public' || p === 'auth') return [];
+ if (typeof p === 'string') return [p];
+ if (Array.isArray(p)) return [...p];
+ return [...(p as { anyOf: readonly string[] }).anyOf];
+}
+
+export interface RouteAuthDeps extends AuthDeps {
+ /** Resolves which layers and services a caller may read. Absent only in
+ * unit tests that exercise verb gating alone; then no scope is checked. */
+ access?: AccessDeps;
+}
+
+export function makeRouteAuthHook(deps: RouteAuthDeps) {
return function onRoute(route: RouteOptions): void {
const methods = Array.isArray(route.method) ? route.method : [route.method];
// A route can be registered for multiple methods; if any one needs
@@ -419,15 +447,25 @@ export function makeRouteAuthHook(deps: AuthDeps) {
typeof h === 'function' && h.name === 'authPreHandler',
);
+ const verbs = policyVerbs(chosen);
+ const scopeKey = chosenKey ?? '';
+ const scope = ROUTE_SCOPE[scopeKey] ?? ROUTE_SCOPE[scopeKey.replace(/^HEAD /, 'GET ')];
+ if (!scope && route.url.startsWith('/api/') && verbs.some((v) => LAYER_SCOPED_VERBS.has(v))) {
+ const msg = `rbac: route ${String(methods)} ${route.url} reads per-service data but has no entry in ROUTE_SCOPE; add one in apps/bff/src/rbac/route-scope.ts`;
+ logger.error({ method: methods, url: route.url }, msg);
+ throw new Error(msg);
+ }
+
const newHandlers = [];
if (!hasAuth) newHandlers.push(requireAuth(deps));
if (chosen !== 'auth') {
if (typeof chosen === 'object' && !Array.isArray(chosen) && 'anyOf' in chosen) {
- newHandlers.push(checkAnyVerb(deps, chosen.anyOf));
+ newHandlers.push(checkAnyVerb(deps, chosen.anyOf, scope !== undefined));
} else {
- newHandlers.push(checkVerb(deps, chosen as string | readonly string[]));
+ newHandlers.push(checkVerb(deps, chosen as string | readonly string[], scope !== undefined));
}
}
+ if (scope) newHandlers.push(scopeGate(deps.config, deps.access, scope, verbs));
// readonly-mode backstop on the config-template write routes.
if (methods.some((m) => isTemplateWriteRoute(String(m).toUpperCase(), route.url))) {
newHandlers.push(denyTemplateWriteWhenReadOnly);
diff --git a/apps/bff/src/rbac/route-scope.ts b/apps/bff/src/rbac/route-scope.ts
new file mode 100644
index 00000000..31e731c1
--- /dev/null
+++ b/apps/bff/src/rbac/route-scope.ts
@@ -0,0 +1,328 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Which layer and which services each data route reads, so the gate can check
+ * them before the handler runs.
+ *
+ * `ROUTE_POLICY` says WHAT a route needs (a verb). This table says WHERE: the
+ * URL's layer, and every request field that names a service or something a
+ * service owns. The gate resolves each one and asks {@link RequestAccess}
+ * whether the caller may read it with the route's verb. Every route whose verb
+ * can carry a layer (`LAYER_SCOPED_VERBS`) must have an entry — registration
+ * throws otherwise, the same contract `ROUTE_POLICY` holds — so a new data
+ * route cannot ship without saying what it reads.
+ *
+ * What the gate cannot see from the request is the handler's to check, and
+ * the entry says so in `handler`: rosters it filters, trace ids it resolves.
+ */
+
+import type { FastifyRequest } from 'fastify';
+import { isExactIdentity } from './request-access.js';
+
+type Where = 'query' | 'body' | 'params';
+
+interface Field {
+ at: Where;
+ name: string;
+}
+
+/** A request field that names a service, or something one service owns. */
+export type IdSpec =
+ /** An OAP service id. */
+ | { serviceId: Field }
+ /** Comma-separated service ids (topology seeds). */
+ | { serviceIds: Field }
+ /** A service name; `normal` names the field carrying its flag, if any. */
+ | { serviceName: Field; normal?: Field }
+ /** Either a service id or a name. */
+ | { serviceIdOrName: Field }
+ /** An instance / endpoint / browser-version / page-path id — `<serviceId>_…`. */
+ | { childId: Field }
+ /** An array of such ids. */
+ | { childIds: Field }
+ /** A trace / async / pprof profiling task id — `<createTime>_<serviceId>`. */
+ | { taskId: Field }
+ /** An MQE `Entity` object: its service, and its `dest*` side. */
+ | { entity: Field }
+ /** A list of `{ name, normal }` services (the 3D map). */
+ | { serviceList: Field }
+ /** `{ serviceName, normal? }` objects (process-relation ends); `normal` defaults to true. */
+ | { processEnd: Field }
+ /** A service id, or when it is absent an id-or-name — the one the handler
+ * queries when a request carries both. */
+ | { serviceIdElse: Field; idOrName: Field };
+
+export interface ScopeRule {
+ /** The route's URL carries the layer as `:key`; the caller must reach it. */
+ layer?: boolean;
+ /** The layer the data belongs to whatever the URL names; the caller must
+ * reach it too. */
+ fixedLayer?: string;
+ /** Every identity present must be readable by the caller. */
+ ids?: readonly IdSpec[];
+ /** Two ends of one relation: reading either end is enough. */
+ relation?: readonly IdSpec[];
+ /** With no service named, the OAP query reads EVERY service. A caller
+ * whose verb is layer-limited must name one. A function decides it per
+ * request, for a route where only some request shapes read every service. */
+ requireService?: boolean | ((req: FastifyRequest) => boolean);
+ /** Request shapes a layer-limited caller may not use: a store with no
+ * service scoping, or an id the BFF cannot attribute to a service. */
+ limitedDenied?: (req: FastifyRequest) => string | null;
+ /** A field carrying a draft template to evaluate — the editor's preview.
+ * Running it needs `layer-template:write`, whoever else may read. */
+ preview?: Field;
+ /** What the handler checks itself with `req.access`. Documentation for the
+ * reader; the gate does nothing with it. */
+ handler?: string;
+}
+
+const q = (name: string): Field => ({ at: 'query', name });
+const b = (name: string): Field => ({ at: 'body', name });
+const p = (name: string): Field => ({ at: 'params', name });
+
+/** The `serviceId` a service picker sends. Its `service` name rides along as
+ * an echo these handlers never query by, so it is not checked: a name can
+ * mean both a real and a conjectured service, and checking it would refuse a
+ * caller the one service the request actually reads. */
+const byId = (at: (n: string) => Field): IdSpec[] => [{ serviceId: at('serviceId') }];
+
+const evaluationEnds: IdSpec[] = [
+ { serviceId: b('providerId') },
+ { childId: b('modelId') },
+ // The handler reads `service` only when `serviceId` is absent.
+ { serviceIdElse: b('serviceId'), idOrName: b('service') },
+];
+
+function bodyOf(req: FastifyRequest): Record<string, unknown> {
+ return req.body && typeof req.body === 'object' ? (req.body as Record<string, unknown>) : {};
+}
+
+function queryOf(req: FastifyRequest): Record<string, unknown> {
+ return req.query && typeof req.query === 'object' ? (req.query as Record<string, unknown>) : {};
+}
+
+export const ROUTE_SCOPE: Record<string, ScopeRule> = {
+ // ── Navigation ──
+ 'GET /api/menu': { handler: 'drops layers and group entries the caller cannot reach' },
+
+ // ── Traces ──
+ // A trace crosses services and layers by nature, so the BFF narrows no trace
+ // store and no lookup by id: only the native list's picked service — the
+ // page's own service — is checked, and a Zipkin service name is Zipkin's.
+ 'POST /api/layer/:key/traces': {
+ layer: true,
+ ids: [{ serviceId: b('serviceId') }, { childId: b('instanceId') }, { childId: b('endpointId') }],
+ // Only the native `traceId` narrows the native query; `traceIds` is the
+ // Zipkin half's, and the native half ignores it. OAP drops a blank trace
+ // id and lists every service's traces, so only an exact one counts.
+ requireService: (req) => {
+ const body = bodyOf(req);
+ return body.source !== 'zipkin' && !(typeof body.traceId === 'string' && isExactIdentity(body.traceId));
+ },
+ preview: b('previewConfig'),
+ },
+ 'GET /api/trace/:traceId': {},
+
+ // ── Logs ──
+ 'POST /api/layer/:key/logs': {
+ layer: true,
+ ids: [...byId(b), { childId: b('serviceInstanceId') }, { childId: b('endpointId') }],
+ requireService: true,
+ },
+ 'POST /api/layer/:key/logs/facets': {
+ layer: true,
+ ids: [...byId(b), { childId: b('serviceInstanceId') }, { childId: b('endpointId') }],
+ requireService: true,
+ },
+ 'GET /api/layer/:key/pod-logs/containers': { layer: true, ids: [{ childId: q('instance') }], requireService: true },
+ 'POST /api/layer/:key/pod-logs': { layer: true, ids: [{ childId: b('serviceInstanceId') }], requireService: true },
+ // A record is one call from an application service to a GenAI provider: the
+ // provider's owner reads all its callers, a caller's owner its own calls.
+ 'POST /api/layer/:key/evaluation-records': {
+ layer: true,
+ fixedLayer: 'VIRTUAL_GENAI',
+ relation: evaluationEnds,
+ requireService: true,
+ },
+ 'POST /api/layer/:key/evaluation-records/facets': {
+ layer: true,
+ fixedLayer: 'VIRTUAL_GENAI',
+ relation: evaluationEnds,
+ requireService: true,
+ },
+ 'GET /api/evaluation-record/caller-services': { handler: 'keeps the services the caller may read' },
+
+ // ── Browser errors ──
+ 'POST /api/layer/:key/browser-errors': {
+ layer: true,
+ ids: [...byId(b), { childId: b('serviceVersionId') }, { childId: b('pagePathId') }],
+ requireService: true,
+ },
+
+ // ── Events, alarms ──
+ 'POST /api/events': { ids: [{ serviceName: b('service') }], requireService: true },
+ 'GET /api/alarms': { ids: [{ serviceName: q('service'), normal: q('normal') }], requireService: true },
+ 'GET /api/alarms/count': {
+ limitedDenied: () => 'alarm_counts_are_deployment_wide',
+ },
+ 'GET /api/alarms/services': { handler: 'keeps the services of the layer the caller may read' },
+
+ // ── AI agent conversations ──
+ 'POST /api/layer/:key/ai-conversations': { layer: true, ids: [{ serviceName: b('service') }], requireService: true },
+ 'GET /api/ai-conversation/:conversation/view': { ids: [{ serviceName: q('service') }], requireService: true },
+ 'GET /api/ai-conversation/:conversation/files': { ids: [{ serviceName: q('service') }], requireService: true },
+
+ // ── Metrics ──
+ 'POST /api/layer/:key/dashboard': {
+ layer: true,
+ handler: 'checks the service it picks from this layer\'s roster, by name, id or default',
+ },
+ 'POST /api/mqe/exec': {
+ ids: [{ entity: b('entity') }],
+ handler: 'an expression with no service reads every service: needs inspect:read',
+ },
+ 'GET /api/layer/:key/dashboard/config': { layer: true },
+ 'POST /api/layer/:key/landing': {
+ layer: true,
+ handler: 'keeps the caller\'s services; layer-wide totals only for callers who read the whole layer',
+ },
+ 'GET /api/layer/:key/instances': { layer: true, ids: byId(q), requireService: true },
+ 'GET /api/layer/:key/endpoints': { layer: true, ids: byId(q), requireService: true },
+ 'GET /api/layer/:key/services': { layer: true, handler: 'keeps the services the caller may read' },
+
+ // ── Topology ──
+ 'GET /api/layer/:key/topology': {
+ layer: true,
+ ids: [{ serviceIds: q('serviceId') }],
+ preview: q('previewConfig'),
+ handler: 'with no service, seeds only the services the caller may read',
+ },
+ 'GET /api/layer/:key/service-hierarchy': { layer: true, ids: [{ serviceId: q('serviceId') }], requireService: true },
+ 'GET /api/layer/:key/instance-topology': {
+ layer: true,
+ relation: [{ serviceId: q('client') }, { serviceId: q('server') }],
+ requireService: true,
+ preview: q('previewConfig'),
+ },
+ 'GET /api/layer/:key/deployment': { layer: true, ids: byId(q), requireService: true, preview: q('previewConfig') },
+ 'GET /api/layer/:key/endpoint-dependency': {
+ layer: true,
+ ids: [...byId(q), { childId: q('endpoint') }],
+ requireService: true,
+ preview: q('previewConfig'),
+ },
+
+ // ── Profiling ──
+ 'GET /api/layer/:key/profile/tasks': { layer: true, ids: byId(q), requireService: true },
+ 'POST /api/layer/:key/profile/tasks': { layer: true, ids: [{ serviceId: b('serviceId') }], requireService: true },
+ 'GET /api/profile/tasks/:taskId/segments': { ids: [{ taskId: p('taskId') }], requireService: true },
+ 'GET /api/profile/tasks/:taskId/logs': { ids: [{ taskId: p('taskId') }], requireService: true },
+ 'POST /api/profile/analyze': { limitedDenied: () => 'segment_ids_name_no_service' },
+ 'GET /api/layer/:key/async/tasks': { layer: true, ids: byId(q), requireService: true },
+ 'POST /api/layer/:key/async/tasks': {
+ layer: true,
+ ids: [{ serviceId: b('serviceId') }, { childIds: b('serviceInstanceIds') }],
+ requireService: true,
+ },
+ 'GET /api/async/tasks/:taskId/progress': { ids: [{ taskId: p('taskId') }], requireService: true },
+ 'POST /api/async/analyze': {
+ ids: [{ taskId: b('taskId') }, { childIds: b('instanceIds') }],
+ requireService: true,
+ },
+ 'GET /api/layer/:key/pprof/tasks': { layer: true, ids: byId(q), requireService: true },
+ 'POST /api/layer/:key/pprof/tasks': {
+ layer: true,
+ ids: [{ serviceId: b('serviceId') }, { childIds: b('serviceInstanceIds') }],
+ requireService: true,
+ },
+ 'GET /api/pprof/tasks/:taskId/progress': { ids: [{ taskId: p('taskId') }], requireService: true },
+ 'POST /api/pprof/analyze': {
+ ids: [{ taskId: b('taskId') }, { childIds: b('instanceIds') }],
+ requireService: true,
+ },
+ 'GET /api/layer/:key/ebpf/tasks': { layer: true, ids: byId(q), requireService: true },
+ 'POST /api/layer/:key/ebpf/tasks': { layer: true, ids: [{ serviceId: b('serviceId') }], requireService: true },
+ 'GET /api/ebpf/tasks/:taskId/schedules': {
+ handler: 'keeps the schedules whose process belongs to a service the caller may read',
+ },
+ 'POST /api/ebpf/analyze': { limitedDenied: () => 'schedule_ids_name_no_service' },
+ 'GET /api/layer/:key/ebpf/network/tasks': {
+ layer: true,
+ ids: [...byId(q), { childId: q('serviceInstance') }],
+ requireService: true,
+ },
+ 'GET /api/ebpf/network/topology': { ids: [{ childId: q('serviceInstance') }], requireService: true },
+ 'GET /api/ebpf/network/processes': { ids: [{ childId: q('serviceInstance') }], requireService: true },
+ 'POST /api/ebpf/network/tasks': { ids: [{ childId: b('instanceId') }], requireService: true },
+ 'POST /api/ebpf/network/tasks/:taskId/keep-alive': { limitedDenied: () => 'task_id_names_no_service' },
+ 'POST /api/layer/:key/ebpf/network/process-relation-metrics': {
+ layer: true,
+ // An edge between two processes opens for a role that reads either end,
+ // as the instance map does.
+ relation: [{ processEnd: b('source') }, { processEnd: b('dest') }],
+ requireService: true,
+ preview: b('previewConfig'),
+ },
+ 'GET /api/continuous-profiling/policy-summary': {
+ handler: 'summarises only the services of the layer the caller may read',
+ },
+ 'GET /api/continuous-profiling/policies': { ids: byId(q), requireService: true },
+ 'POST /api/continuous-profiling/policies': { ids: [{ serviceId: b('serviceId') }], requireService: true },
+ 'GET /api/continuous-profiling/instances': { ids: byId(q), requireService: true },
+
+ // ── The 3D map: its own verb, but its services are still services ──
+ 'POST /api/infra-3d/metrics': { ids: [{ serviceList: b('services') }] },
+
+ // ── Trace stores and their autocomplete: traces cross layers ──
+ ...Object.fromEntries(
+ [
+ 'GET /api/zipkin/services',
+ 'GET /api/zipkin/spans',
+ 'GET /api/zipkin/remote-services',
+ 'GET /api/zipkin/traces',
+ 'GET /api/zipkin/trace/:traceId',
+ 'GET /api/zipkin/autocomplete/keys',
+ 'GET /api/zipkin/autocomplete/values',
+ 'GET /api/traceql/sources',
+ 'GET /api/traceql/:ds/search',
+ 'GET /api/traceql/:ds/trace/:traceId',
+ 'GET /api/traceql/:ds/tags',
+ 'GET /api/traceql/:ds/tag-values',
+ 'GET /api/trace-tags/keys',
+ 'GET /api/trace-tags/values',
+ ].map((route): [string, ScopeRule] => [route, {}]),
+ ),
+
+ // ── Reads that name no service the BFF can check: whole-deployment only ──
+ ...Object.fromEntries(
+ [
+ 'GET /api/log-tags/keys',
+ 'GET /api/log-tags/values',
+ // Source maps are not attributed to a browser app: a map holds the
+ // original source of whichever app it was built from.
+ 'GET /api/browser-errors/source-maps',
+ 'POST /api/browser-errors/resolve',
+ ].map((route): [string, ScopeRule] => [route, { limitedDenied: () => 'not_attributable_to_a_service' }]),
+ ),
+};
+
+export function fieldValue(req: FastifyRequest, f: Field): unknown {
+ const src = f.at === 'body' ? bodyOf(req) : f.at === 'query' ? queryOf(req) : (req.params as Record<string, unknown>);
+ return src?.[f.name];
+}
diff --git a/apps/bff/src/rbac/scope-gate.test.ts b/apps/bff/src/rbac/scope-gate.test.ts
new file mode 100644
index 00000000..c5e3a694
--- /dev/null
+++ b/apps/bff/src/rbac/scope-gate.test.ts
@@ -0,0 +1,355 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The route gate against the paths reproduced on a live OAP: the operate-layer
+ * reads a plain viewer could make before, and the cross-group / cross-layer
+ * reads a layer grant must refuse. Handlers here are stubs — what is under test
+ * is whether the request reaches them.
+ */
+
+import { afterEach, describe, expect, it } from 'vitest';
+import Fastify, { type FastifyInstance } from 'fastify';
+import cookie from '@fastify/cookie';
+import type { FetchLike } from '@skywalking-horizon-ui/api-client';
+import { configSchema } from '../config/schema.js';
+import type { ConfigSource } from '../config/loader.js';
+import { SessionStore } from '../user/sessions.js';
+import { makeRouteAuthHook, ROUTE_POLICY } from './route-policy.js';
+import { ServiceIdentityResolver, serviceIdOf } from '../logic/services/service-identity.js';
+import type { ServiceCatalog, ServiceLayerCatalog } from '../logic/services/service-layer-catalog.js';
+import type { AccessDeps } from './request-access.js';
+
+const PAY = { id: serviceIdOf('payments::checkout', true), name: 'payments::checkout', normal: true, group: 'payments' };
+const RISK = { id: serviceIdOf('risk::scorer', true), name: 'risk::scorer', normal: true, group: 'risk' };
+/** A payments service no other service shares a name with. */
+const LEDGER = { id: serviceIdOf('payments::ledger', true), name: 'payments::ledger', normal: true, group: 'payments' };
+const BDB = { id: serviceIdOf('showcase-banyandb', true), name: 'showcase-banyandb', normal: true, group: '' };
+/** A conjectured service sharing PAY's name, in a layer the payments role is not granted. */
+const PAY_VIRTUAL = { id: serviceIdOf('payments::checkout', false), name: 'payments::checkout', normal: false, group: 'payments' };
+
+const snapshot: ServiceCatalog = {
+ layers: ['GENERAL', 'BANYANDB', 'VIRTUAL_DATABASE'],
+ byLayer: new Map([
+ ['GENERAL', [PAY, RISK, LEDGER]],
+ ['BANYANDB', [BDB]],
+ ['VIRTUAL_DATABASE', [PAY_VIRTUAL]],
+ ]),
+ byName: new Map(),
+};
+
+const ROLES = {
+ viewer: ['metrics:read', 'logs:read', 'traces:read', 'topology:read', 'profile:read'],
+ maintainer: ['metrics:read', 'logs:read', 'traces:read', 'topology:read', 'profile:read', 'cluster:read'],
+ payments: [
+ 'metrics:read@GENERAL[payments]',
+ 'logs:read@GENERAL[payments]',
+ 'traces:read@GENERAL[payments]',
+ 'topology:read@GENERAL[payments]',
+ 'profile:read@GENERAL[payments]',
+ 'events:read@GENERAL[payments]',
+ ],
+ bdb: ['metrics:read@BANYANDB'],
+ payGenai: ['logs:read@GENERAL[payments]', 'logs:read@VIRTUAL_GENAI[payments]'],
+ editor: ['metrics:read', 'topology:read', 'layer-template:write'],
+};
+
+function config(): ConfigSource {
+ const cfg = configSchema.parse({ rbac: { roles: ROLES } });
+ return { current: cfg, current_: () => cfg, path: '', onChange: () => () => {}, close: async () => {} };
+}
+
+// OAP knows no service beyond the catalog.
+const unknownToOap: FetchLike = async () =>
+ new Response(JSON.stringify({ data: { service: null } }), { status: 200, headers: { 'content-type': 'application/json' } });
+
+const oapDown: FetchLike = async () => {
+ throw new Error('connect ECONNREFUSED');
+};
+
+function accessDeps(cfg: ConfigSource, fetch: FetchLike): AccessDeps {
+ const catalog = { get: async () => snapshot } as unknown as ServiceLayerCatalog;
+ return {
+ services: new ServiceIdentityResolver({ config: cfg, fetch, catalog }),
+ classify: async () => ({ isOperate: (l: string) => l.toUpperCase() === 'BANYANDB' }),
+ };
+}
+
+let app: FastifyInstance | null = null;
+afterEach(async () => {
+ await app?.close();
+ app = null;
+});
+
+async function build(fetch: FetchLike = unknownToOap): Promise<{ as: (role: keyof typeof ROLES) => string }> {
+ const cfg = config();
+ const sessions = new SessionStore({ ttlMinutes: 60 });
+ app = Fastify();
+ await app.register(cookie);
+ app.addHook('onRoute', makeRouteAuthHook({ config: cfg, sessions, access: accessDeps(cfg, fetch) }));
+ const ok = async () => ({ ok: true });
+ app.get('/api/layer/:key/instances', ok);
+ app.post('/api/layer/:key/logs', ok);
+ app.get('/api/layer/:key/instance-topology', ok);
+ app.post('/api/layer/:key/evaluation-records', ok);
+ app.get('/api/layer/:key/topology', ok);
+ app.get('/api/profile/tasks/:taskId/segments', ok);
+ app.get('/api/zipkin/services', ok);
+ app.post('/api/layer/:key/traces', ok);
+ app.post('/api/mqe/exec', ok);
+ app.post('/api/events', ok);
+ app.post('/api/layer/:key/ebpf/network/process-relation-metrics', ok);
+ app.get('/api/menu', async (req) => ({ access: req.access !== undefined }));
+ await app.ready();
+ return { as: (role) => `horizon_sid=${sessions.create(role, [role]).sid}` };
+}
+
+async function call(cookieHeader: string, method: 'GET' | 'POST', url: string, payload?: unknown) {
+ const res = await app!.inject({ method, url, headers: { cookie: cookieHeader }, ...(payload ? { payload } : {}) });
+ return { status: res.statusCode, body: res.json() as { reason?: string } };
+}
+
+const q = (s: { id: string; name: string }) =>
+ `serviceId=${encodeURIComponent(s.id)}&service=${encodeURIComponent(s.name)}`;
+
+describe('the operate layers need cluster:read or an explicit grant', () => {
+ it('refuses a plain viewer the operate layer and its services, through any layer URL', async () => {
+ const { as } = await build();
+ const viewer = as('viewer');
+ expect((await call(viewer, 'GET', `/api/layer/banyandb/instances?${q(BDB)}`)).body.reason).toBe('layer_not_granted');
+ expect((await call(viewer, 'GET', `/api/layer/general/instances?${q(BDB)}`)).body.reason).toBe('service_not_granted');
+ expect((await call(viewer, 'GET', `/api/layer/general/instances?${q(PAY)}`)).status).toBe(200);
+ });
+
+ it('checks the id the handler queries, not the name echoed beside it', async () => {
+ const { as } = await build();
+ const echo = (id: string, name: string) => `serviceId=${encodeURIComponent(id)}&service=${encodeURIComponent(name)}`;
+ // The instances handler reads `serviceId` only, so the name cannot widen the read…
+ expect((await call(as('viewer'), 'GET', `/api/layer/general/instances?${echo(PAY.id, BDB.name)}`)).status).toBe(200);
+ expect((await call(as('viewer'), 'GET', `/api/layer/general/instances?${echo(BDB.id, PAY.name)}`)).status).toBe(403);
+ // …and a list of names on a multi-service topology is not read as one service.
+ const ids = `${PAY.id},${RISK.id}`;
+ const names = `${PAY.name},${RISK.name}`;
+ const topo = `/api/layer/general/topology?serviceId=${encodeURIComponent(ids)}&service=${encodeURIComponent(names)}`;
+ expect((await call(as('viewer'), 'GET', topo)).status).toBe(200);
+ });
+
+ it('reads the one service an id names when a conjectured one shares its name', async () => {
+ const { as } = await build();
+ const url = `/api/layer/general/instances?serviceId=${encodeURIComponent(PAY.id)}&service=${encodeURIComponent(PAY.name)}`;
+ expect((await call(as('payments'), 'GET', url)).status).toBe(200);
+ });
+
+ it('opens them to cluster:read, and to an explicit layer grant alone', async () => {
+ const { as } = await build();
+ expect((await call(as('maintainer'), 'GET', `/api/layer/banyandb/instances?${q(BDB)}`)).status).toBe(200);
+ expect((await call(as('bdb'), 'GET', `/api/layer/banyandb/instances?${q(BDB)}`)).status).toBe(200);
+ expect((await call(as('bdb'), 'GET', `/api/layer/general/instances?${q(PAY)}`)).body.reason).toBe('layer_not_granted');
+ });
+
+ it('refuses an MQE entity naming an operate-only service', async () => {
+ const { as } = await build();
+ const body = (name: string) => ({ expression: 'x', entity: { serviceName: name, normal: true }, step: 'MINUTE', startMs: 1, endMs: 2 });
+ expect((await call(as('viewer'), 'POST', '/api/mqe/exec', body(BDB.name))).status).toBe(403);
+ expect((await call(as('viewer'), 'POST', '/api/mqe/exec', body(PAY.name))).status).toBe(200);
+ });
+
+ it('reads a Service-scope metric through its source, never through the destination', async () => {
+ const { as } = await build();
+ const body = { expression: 'service_cpm', entity: { serviceName: RISK.name, normal: true, destServiceName: PAY.name, destNormal: true }, step: 'MINUTE', startMs: 1, endMs: 2 };
+ expect((await call(as('payments'), 'POST', '/api/mqe/exec', body)).status).toBe(403);
+ const own = { ...body, entity: { serviceName: PAY.name, normal: true, destServiceName: RISK.name, destNormal: true } };
+ expect((await call(as('payments'), 'POST', '/api/mqe/exec', own)).status).toBe(200);
+ // A destination alone names no service: the dummy handler here stands in
+ // for mqe-exec's own inspect:read check, so the gate must let it through.
+ const destOnly = { ...body, entity: { destServiceName: PAY.name, destNormal: true } };
+ expect((await call(as('payments'), 'POST', '/api/mqe/exec', destOnly)).status).toBe(200);
+ });
+
+ it('checks a name exactly as the handler will send it', async () => {
+ const { as } = await build();
+ expect((await call(as('payments'), 'POST', '/api/events', { service: LEDGER.name })).status).toBe(200);
+ expect((await call(as('payments'), 'POST', '/api/events', { service: ` ${LEDGER.name}` })).body.reason).toBe('identity_not_normalized');
+ });
+
+ it('refuses a padded identity, which one handler trims and another does not', async () => {
+ const { as } = await build();
+ const body = { expression: 'service_cpm', entity: { serviceName: `${BDB.name} `, normal: true }, step: 'MINUTE', startMs: 1, endMs: 2 };
+ expect((await call(as('viewer'), 'POST', '/api/mqe/exec', body)).body.reason).toBe('identity_not_normalized');
+ });
+
+ it('refuses a name that is only whitespace, or carries control characters', async () => {
+ const { as } = await build();
+ for (const service of [' ', `payments::led\u0007ger`, `payments::ledger\uD800`]) {
+ expect((await call(as('payments'), 'POST', '/api/events', { service })).body.reason).toBe('identity_not_normalized');
+ }
+ });
+
+ it('leaves a caller who reads every layer to the handler, as before', async () => {
+ const { as } = await build(oapDown);
+ const body = { expression: 'service_cpm', entity: { serviceName: `${BDB.name} `, normal: true }, step: 'MINUTE', startMs: 1, endMs: 2 };
+ expect((await call(as('maintainer'), 'POST', '/api/mqe/exec', body)).status).toBe(200);
+ const ghost = { id: serviceIdOf('ghost', true), name: 'ghost' };
+ expect((await call(as('maintainer'), 'GET', `/api/layer/general/instances?${q(ghost)}`)).status).toBe(200);
+ });
+
+ it('answers an OAP it could not ask with an outage, not a refusal', async () => {
+ const { as } = await build(oapDown);
+ const ghost = { id: serviceIdOf('ghost', true), name: 'ghost' };
+ const res = await call(as('viewer'), 'GET', `/api/layer/general/instances?${q(ghost)}`);
+ expect(res.status).toBe(503);
+ expect(res.body).toMatchObject({ error: 'oap_unreachable' });
+ // A service the catalog already holds is decided without asking.
+ expect((await call(as('viewer'), 'GET', `/api/layer/general/instances?${q(PAY)}`)).status).toBe(200);
+ });
+
+ it('reads a baseline through every service its name can mean', async () => {
+ const { as } = await build();
+ const body = (expression: string) => ({ expression, entity: { serviceName: PAY.name, normal: true }, step: 'HOUR', startMs: 1, endMs: 2 });
+ expect((await call(as('payments'), 'POST', '/api/mqe/exec', body('service_cpm'))).status).toBe(200);
+ // OAP looks a baseline up by name, so the conjectured namesake is read too.
+ expect((await call(as('payments'), 'POST', '/api/mqe/exec', body('baseline(service_cpm,value)'))).status).toBe(403);
+ });
+
+ it('lets a plain viewer name a service OAP does not know, as before', async () => {
+ const { as } = await build();
+ const ghost = { id: serviceIdOf('ghost', true), name: 'ghost' };
+ expect((await call(as('viewer'), 'GET', `/api/layer/general/instances?${q(ghost)}`)).status).toBe(200);
+ });
+});
+
+describe('a group-limited grant reads its own services only', () => {
+ it('refuses another group, and an instance of another group under its own service id', async () => {
+ const { as } = await build();
+ const pay = as('payments');
+ expect((await call(pay, 'POST', '/api/layer/general/logs', { serviceId: PAY.id, service: PAY.name })).status).toBe(200);
+ expect((await call(pay, 'POST', '/api/layer/general/logs', { serviceId: RISK.id, service: RISK.name })).status).toBe(403);
+ const riskInstance = `${RISK.id}_aW5zdA==`;
+ const res = await call(pay, 'POST', '/api/layer/general/logs', { serviceId: PAY.id, serviceInstanceId: riskInstance });
+ expect(res.status).toBe(403);
+ });
+
+ it('must name a service where OAP would read every one', async () => {
+ const { as } = await build();
+ expect((await call(as('payments'), 'POST', '/api/layer/general/logs', {})).body.reason).toBe('service_required');
+ expect((await call(as('viewer'), 'POST', '/api/layer/general/logs', {})).status).toBe(200);
+ });
+
+ it('reads a relation when it owns either end', async () => {
+ const { as } = await build();
+ const url = (a: string, b: string) =>
+ `/api/layer/general/instance-topology?client=${encodeURIComponent(a)}&server=${encodeURIComponent(b)}`;
+ expect((await call(as('payments'), 'GET', url(PAY.id, RISK.id))).status).toBe(200);
+ expect((await call(as('payments'), 'GET', url(RISK.id, RISK.id))).status).toBe(403);
+ });
+
+ it('reads evaluation records only with the VIRTUAL_GENAI layer, whatever the URL', async () => {
+ const { as } = await build();
+ const res = await call(as('payments'), 'POST', '/api/layer/general/evaluation-records', { serviceId: PAY.id });
+ expect(res.body.reason).toBe('layer_not_granted');
+ });
+
+ it('reads an evaluation record through either end of the call', async () => {
+ const { as } = await build();
+ const pay = as('payGenai');
+ const url = '/api/layer/virtual_genai/evaluation-records';
+ expect((await call(pay, 'POST', url, { providerId: PAY.id })).status).toBe(200);
+ expect((await call(pay, 'POST', url, { providerId: RISK.id, serviceId: PAY.id })).status).toBe(200);
+ expect((await call(pay, 'POST', url, { providerId: RISK.id })).status).toBe(403);
+ // The handler queries `serviceId` and ignores `service` beside it.
+ expect((await call(pay, 'POST', url, { serviceId: RISK.id, service: PAY.name })).status).toBe(403);
+ expect((await call(pay, 'POST', url, {})).body.reason).toBe('service_required');
+ });
+
+ it('reads a process end as the service the handler reads, normal unless it says false', async () => {
+ const { as } = await build();
+ const url = '/api/layer/general/ebpf/network/process-relation-metrics';
+ const end = (normal?: unknown) => ({ source: { serviceName: PAY.name, ...(normal === undefined ? {} : { normal }) } });
+ expect((await call(as('payments'), 'POST', url, end())).status).toBe(200);
+ expect((await call(as('payments'), 'POST', url, end('false'))).status).toBe(200);
+ // The conjectured namesake sits in a layer the payments role is not granted.
+ expect((await call(as('payments'), 'POST', url, end(false))).status).toBe(403);
+ // An edge opens for a role that reads either end.
+ const edge = (from: { name: string }, to: { name: string }) => ({
+ source: { serviceName: from.name, processName: 'p' },
+ dest: { serviceName: to.name, processName: 'q' },
+ });
+ expect((await call(as('payments'), 'POST', url, edge(PAY, RISK))).status).toBe(200);
+ expect((await call(as('payments'), 'POST', url, edge(RISK, PAY))).status).toBe(200);
+ expect((await call(as('payments'), 'POST', url, edge(RISK, RISK))).status).toBe(403);
+ for (const serviceName of ['', null, undefined]) {
+ const ends = { source: { serviceName, processName: 'p' }, dest: { serviceName: PAY.name, processName: 'q' } };
+ expect((await call(as('viewer'), 'POST', url, ends)).body.reason, String(serviceName)).toBe('identity_not_normalized');
+ }
+ });
+
+ it('attributes a profiling task to the service its id ends with', async () => {
+ const { as } = await build();
+ const url = (task: string) => `/api/profile/tasks/${encodeURIComponent(task)}/segments`;
+ expect((await call(as('payments'), 'GET', url(`1700000000000_${PAY.id}`))).status).toBe(200);
+ expect((await call(as('payments'), 'GET', url(`1700000000000_${RISK.id}`))).status).toBe(403);
+ expect((await call(as('payments'), 'GET', url('opaque'))).body.reason).toBe('id_names_no_service');
+ expect((await call(as('viewer'), 'GET', url('opaque'))).status).toBe(200);
+ });
+
+ it('leaves trace stores and trace-id lookups to the trace, which crosses layers', async () => {
+ const { as } = await build();
+ expect((await call(as('payments'), 'GET', '/api/zipkin/services')).status).toBe(200);
+ const traces = (body: Record<string, unknown>) => call(as('payments'), 'POST', '/api/layer/general/traces', body);
+ expect((await traces({ source: 'zipkin', service: 'any-zipkin-name' })).status).toBe(200);
+ expect((await traces({ source: 'native', traceId: 't-1' })).status).toBe(200);
+ // OAP drops a blank trace id and lists every service's traces.
+ for (const traceId of [' ', '', ' t-1']) {
+ expect((await traces({ source: 'native', traceId })).body.reason, JSON.stringify(traceId)).toBe('service_required');
+ }
+ expect((await traces({ source: 'native', traceIds: ['t-1'] })).body.reason).toBe('service_required');
+ expect((await traces({ source: 'native' })).body.reason).toBe('service_required');
+ expect((await traces({ source: 'native', serviceId: RISK.id })).status).toBe(403);
+ });
+});
+
+describe('the gate itself', () => {
+ it('runs a draft template only for someone who may write templates', async () => {
+ const { as } = await build();
+ const url = '/api/layer/general/topology?previewConfig=%7B%7D';
+ expect((await call(as('viewer'), 'GET', url)).body.reason).toBe('preview_needs_template_write');
+ expect((await call(as('editor'), 'GET', url)).status).toBe(200);
+ // A draft in any other shape is still a draft: a parser could coerce it.
+ expect((await call(as('viewer'), 'GET', `${url}&previewConfig=%7B%7D`)).body.reason).toBe('preview_needs_template_write');
+ const relation = '/api/layer/general/ebpf/network/process-relation-metrics';
+ const body = { source: { serviceName: PAY.name, processName: 'p' }, dest: { serviceName: PAY.name, processName: 'q' } };
+ expect((await call(as('viewer'), 'POST', relation, { ...body, previewConfig: ['{}'] })).body.reason).toBe('preview_needs_template_write');
+ });
+
+ it('hands the menu its access object', async () => {
+ const { as } = await build();
+ expect((await call(as('viewer'), 'GET', '/api/menu')).body).toEqual({ access: true });
+ });
+
+ it('refuses to register a per-service route the scope table does not list', async () => {
+ const cfg = config();
+ const probe = Fastify();
+ probe.addHook('onRoute', makeRouteAuthHook({ config: cfg, sessions: new SessionStore({ ttlMinutes: 60 }) }));
+ ROUTE_POLICY['GET /api/layer/:key/unlisted'] = 'metrics:read';
+ try {
+ expect(() => probe.get('/api/layer/:key/unlisted', async () => ({}))).toThrow(/ROUTE_SCOPE/);
+ } finally {
+ delete ROUTE_POLICY['GET /api/layer/:key/unlisted'];
+ await probe.close();
+ }
+ });
+});
diff --git a/apps/bff/src/rbac/scope-gate.ts b/apps/bff/src/rbac/scope-gate.ts
new file mode 100644
index 00000000..d6f8c3c7
--- /dev/null
+++ b/apps/bff/src/rbac/scope-gate.ts
@@ -0,0 +1,238 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The pre-handler that applies a {@link ScopeRule}: builds the request's
+ * {@link RequestAccess}, then checks the URL's layer and every identity the
+ * rule names before the handler runs.
+ */
+
+import type { FastifyReply, FastifyRequest } from 'fastify';
+import type { ConfigSource } from '../config/loader.js';
+import { clientGone } from '../http/client-gone.js';
+import {
+ buildRequestAccess,
+ isExactIdentity,
+ readsByNameOnly,
+ serviceRefFromName,
+ type AccessDeps,
+ type RequestAccess,
+ type ServiceRef,
+} from './request-access.js';
+import { sessionHasVerb } from './policy.js';
+import { fieldValue, type IdSpec, type ScopeRule } from './route-scope.js';
+import type { Verb } from './verbs.js';
+
+declare module 'fastify' {
+ interface FastifyRequest {
+ /** Set by the scope gate on every route `ROUTE_SCOPE` lists. Absent where
+ * the gate is not wired (unit tests), which handlers read as "no layer
+ * restriction" — the behaviour before layer grants existed. */
+ access?: RequestAccess;
+ }
+}
+
+const SERVICE_ID = /^[A-Za-z0-9+/=]+\.[01]$/;
+/** An id a service owns: `<serviceId>_<base64 name>`. A value that does not
+ * look like one is a NAME the handler searches within an already-checked
+ * service (the endpoint-dependency `endpoint` field), not an id to check. */
+const CHILD_ID = /^[A-Za-z0-9+/=]+\.[01]_./;
+
+/** What the request names: services to check one by one, relation ends of
+ * which one is enough, and ids the BFF cannot attribute to a service. */
+interface Named {
+ refs: ServiceRef[];
+ relations: ServiceRef[][];
+ unattributable: boolean;
+ /** An identity OAP would not read as written — see `isExactIdentity`. The
+ * service checked could differ from the one read, so it is refused; no
+ * client sends one. */
+ padded: boolean;
+}
+
+function flag(v: unknown): boolean | undefined {
+ if (v === true || v === 'true') return true;
+ if (v === false || v === 'false') return false;
+ return undefined;
+}
+
+/** A non-empty identity value. One OAP would not read as written is recorded
+ * as padded (see {@link Named.padded}). */
+function str(v: unknown, into: Named): string | null {
+ if (typeof v !== 'string' || v === '') return null;
+ if (!isExactIdentity(v)) into.padded = true;
+ return v;
+}
+
+function refsOf(req: FastifyRequest, spec: IdSpec, into: Named): ServiceRef[] {
+ const out: ServiceRef[] = [];
+ if ('serviceId' in spec) {
+ const v = str(fieldValue(req, spec.serviceId), into);
+ if (v) out.push({ id: v });
+ } else if ('serviceIds' in spec) {
+ const v = str(fieldValue(req, spec.serviceIds), into);
+ for (const id of v ? v.split(',') : []) if (id.trim()) out.push({ id: id.trim() });
+ } else if ('serviceName' in spec) {
+ const v = str(fieldValue(req, spec.serviceName), into);
+ if (v) out.push(serviceRefFromName(v, spec.normal ? flag(fieldValue(req, spec.normal)) : undefined));
+ } else if ('serviceIdOrName' in spec) {
+ const v = str(fieldValue(req, spec.serviceIdOrName), into);
+ if (v) out.push({ idOrName: v });
+ } else if ('childId' in spec) {
+ const v = str(fieldValue(req, spec.childId), into);
+ if (v && CHILD_ID.test(v)) out.push({ childId: v });
+ } else if ('childIds' in spec) {
+ const v = fieldValue(req, spec.childIds);
+ for (const c of Array.isArray(v) ? v : []) {
+ const s = str(c, into);
+ if (s && CHILD_ID.test(s)) out.push({ childId: s });
+ else if (s) into.unattributable = true;
+ }
+ } else if ('taskId' in spec) {
+ const v = str(fieldValue(req, spec.taskId), into);
+ if (v) {
+ const cut = v.indexOf('_');
+ const owner = cut > 0 ? v.slice(cut + 1) : '';
+ if (SERVICE_ID.test(owner)) out.push({ id: owner });
+ else into.unattributable = true;
+ }
+ } else if ('entity' in spec) {
+ const e = fieldValue(req, spec.entity);
+ if (e && typeof e === 'object') {
+ const ent = e as Record<string, unknown>;
+ const src = str(ent.serviceName, into);
+ // The entity does not say the metric's scope: a Service-scope metric
+ // reads `serviceName` and ignores the `dest*` side. So the source must be
+ // readable whatever the destination is; a relation then reads the
+ // caller's own outbound calls, which it owns an end of.
+ // With no source the expression names no service at all (a `top_n`
+ // filters by `serviceName` only): the handler asks for inspect:read.
+ // `baseline` ignores `normal`: it reads every service the name can mean.
+ const expression = bodyOf(req).expression;
+ const byName = typeof expression === 'string' && readsByNameOnly([expression]);
+ if (src) out.push(byName ? { name: src } : serviceRefFromName(src, flag(ent.normal)));
+ }
+ } else if ('serviceList' in spec) {
+ const v = fieldValue(req, spec.serviceList);
+ for (const item of Array.isArray(v) ? v : []) {
+ const s = item && typeof item === 'object' ? (item as Record<string, unknown>) : {};
+ const name = str(s.name, into);
+ const byName = typeof s.mqe === 'string' && readsByNameOnly([s.mqe]);
+ if (name) out.push(byName ? { name } : serviceRefFromName(name, flag(s.normal)));
+ }
+ } else if ('serviceIdElse' in spec) {
+ const id = str(fieldValue(req, spec.serviceIdElse), into);
+ const other = id ? null : str(fieldValue(req, spec.idOrName), into);
+ if (id) out.push({ id });
+ else if (other) out.push({ idOrName: other });
+ } else if ('processEnd' in spec) {
+ const v = fieldValue(req, spec.processEnd);
+ const s = v && typeof v === 'object' ? (v as Record<string, unknown>) : {};
+ // The handler sends whatever the end carries: an empty name OAP reads as
+ // `_blank`, a missing one as no service (a `top_n` then ranks them all).
+ if (v !== undefined && !(typeof s.serviceName === 'string' && isExactIdentity(s.serviceName))) into.padded = true;
+ const name = str(s.serviceName, into);
+ // The handler reads anything but boolean `false` as true; check the same service.
+ if (name) out.push(serviceRefFromName(name, s.normal !== false));
+ }
+ return out;
+}
+
+function bodyOf(req: FastifyRequest): Record<string, unknown> {
+ return req.body && typeof req.body === 'object' ? (req.body as Record<string, unknown>) : {};
+}
+
+function named(req: FastifyRequest, rule: ScopeRule): Named {
+ const n: Named = { refs: [], relations: [], unattributable: false, padded: false };
+ for (const spec of rule.ids ?? []) n.refs.push(...refsOf(req, spec, n));
+ if (rule.relation) {
+ const ends = rule.relation.flatMap((spec) => refsOf(req, spec, n));
+ if (ends.length > 0) n.relations.push(ends);
+ }
+ return n;
+}
+
+function unavailable(reply: FastifyReply): void {
+ reply.code(503).send({ error: 'oap_unreachable', message: 'OAP did not answer who owns the service this request reads' });
+}
+
+function deny(reply: FastifyReply, verbs: readonly Verb[], reason: string, extra: Record<string, unknown> = {}): void {
+ reply.code(403).send({ error: 'permission_denied', verb: verbs.join(' or '), reason, ...extra });
+}
+
+export function scopeGate(
+ config: ConfigSource,
+ deps: AccessDeps | undefined,
+ rule: ScopeRule,
+ verbs: readonly Verb[],
+) {
+ return async function scopePreHandler(req: FastifyRequest, reply: FastifyReply): Promise<void> {
+ const session = req.session;
+ if (!session) return void reply.code(401).send({ error: 'unauthenticated' });
+ const cfg = config.current;
+
+ const draft = rule.preview ? fieldValue(req, rule.preview) : undefined;
+ // Anything but an empty string counts: a parser may coerce other shapes.
+ const hasDraft = typeof draft === 'string' ? draft.trim() !== '' : draft !== undefined && draft !== null;
+ if (hasDraft && !sessionHasVerb(cfg, session, 'layer-template:write')) {
+ return deny(reply, ['layer-template:write'], 'preview_needs_template_write');
+ }
+ if (!deps) return;
+
+ const access = await buildRequestAccess(cfg, session, deps, clientGone(reply));
+ req.access = access;
+ // A route with no layer and no service in it (the menu, a roster the
+ // handler filters) only needs the access object.
+ if (verbs.length === 0) return;
+ if (access.readsEveryLayer(verbs)) return;
+
+ const limited = access.layerLimited(verbs);
+ if (limited && rule.limitedDenied) {
+ const reason = rule.limitedDenied(req);
+ if (reason) return deny(reply, verbs, reason);
+ }
+
+ if (rule.layer) {
+ const key = (req.params as { key?: string }).key ?? '';
+ if (!access.onLayer(verbs, key)) return deny(reply, verbs, 'layer_not_granted', { layer: key });
+ }
+ // The data lives in one layer whatever the URL says.
+ if (rule.fixedLayer && !access.onLayer(verbs, rule.fixedLayer)) {
+ return deny(reply, verbs, 'layer_not_granted', { layer: rule.fixedLayer });
+ }
+
+ const n = named(req, rule);
+ if (n.padded) return deny(reply, verbs, 'identity_not_normalized');
+ if (n.unattributable && limited) return deny(reply, verbs, 'id_names_no_service');
+ for (const ref of n.refs) {
+ const d = await access.decide(verbs, ref);
+ if (d === 'unavailable') return unavailable(reply);
+ if (d === 'deny') return deny(reply, verbs, 'service_not_granted');
+ }
+ for (const ends of n.relations) {
+ const ds = [];
+ for (const ref of ends) ds.push(await access.decide(verbs, ref));
+ if (ds.includes('allow')) continue;
+ if (ds.includes('unavailable')) return unavailable(reply);
+ return deny(reply, verbs, 'service_not_granted');
+ }
+ const requireService = typeof rule.requireService === 'function' ? rule.requireService(req) : rule.requireService;
+ if (requireService && limited && n.refs.length === 0 && n.relations.length === 0) {
+ return deny(reply, verbs, 'service_required');
+ }
+ };
+}
diff --git a/apps/bff/src/rbac/verb-enforcement.test.ts b/apps/bff/src/rbac/verb-enforcement.test.ts
index 20f01e9f..8377d90a 100644
--- a/apps/bff/src/rbac/verb-enforcement.test.ts
+++ b/apps/bff/src/rbac/verb-enforcement.test.ts
@@ -92,8 +92,9 @@ const POLICY_VERBS = new Set(
);
/** A call that can deny the request. `hasVerb` covers the UI's
- * `auth.hasVerb(...)` and the AI tools' `ctx.hasVerb(...)` alike. */
-const CHECK_CALL = /(?:ensureVerb|sessionHasVerb|checkVerb|hasVerb)\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)/g;
+ * `auth.hasVerb(...)` and the AI tools' `ctx.hasVerb(...)` alike; the
+ * layer-aware forms gate the same verbs for a layer or a service. */
+const CHECK_CALL = /(?:ensureVerb|sessionHasVerb|sessionHasVerbOnSomeLayer|checkVerb|hasVerbOnLayer|hasVerbOnSomeLayer|hasVerb)\s*\(([^()]*(?:\([^()]*\)[^()]*)*)\)/g;
const QUOTED = /'([^'\n]+)'|"([^"\n]+)"/g;
const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
diff --git a/apps/bff/src/rbac/verbs.ts b/apps/bff/src/rbac/verbs.ts
index b1804e26..7fc3efbb 100644
--- a/apps/bff/src/rbac/verbs.ts
+++ b/apps/bff/src/rbac/verbs.ts
@@ -198,10 +198,103 @@ function aliasesFor(grant: string): readonly Verb[] {
return [];
}
+/**
+ * A grant limited to one layer, and optionally to OAP service groups in it:
+ * `metrics:read@GENERAL`, `metrics:read@GENERAL[payments,risk]`. The groups
+ * are OAP `Service.group` values (the `<group>::` prefix); `-` names the
+ * services that have no group.
+ */
+export interface LayerQualifier {
+ /** Upper-cased as written; the access check canonicalises aliases. */
+ layer: string;
+ /** Absent = the whole layer. `''` is the ungrouped services. */
+ groups?: readonly string[];
+}
+
+export interface ParsedGrant {
+ verb: Verb;
+ qualifier?: LayerQualifier;
+}
+
+/** How a grant spells "the services with no group". */
+export const UNGROUPED_GRANT = '-';
+
+/**
+ * The verbs a layer qualifier means something on: their data belongs to one
+ * service, so "which layer, which group" has an answer. Any other verb written
+ * with `@` grants nothing — `cluster:read@GENERAL` or `overview:read@GENERAL`
+ * would promise a narrowing no route could enforce. `layer-grants.test.ts`
+ * checks every `/api/layer/:key/` route's verb is listed here.
+ */
+export const LAYER_SCOPED_VERBS: ReadonlySet<Verb> = new Set<Verb>([
+ 'metrics:read',
+ 'traces:read',
+ 'logs:read',
+ 'browser-errors:read',
+ 'ai-conversation:read',
+ 'events:read',
+ 'alarms:read',
+ 'topology:read',
+ 'profile:read',
+ 'profile:enable',
+]);
+
+/** The verbs that open a layer PAGE — a sidebar entry is shown to a caller
+ * who holds one of them on that layer. Alarms and events have pages of their
+ * own, and `profile:enable` only acts on a page something else opened. */
+export const LAYER_PAGE_VERBS: readonly Verb[] = [
+ 'metrics:read',
+ 'traces:read',
+ 'logs:read',
+ 'topology:read',
+ 'profile:read',
+ 'browser-errors:read',
+ 'ai-conversation:read',
+];
+
+const QUALIFIER = /^([A-Za-z0-9_]+)(?:\[([^\]]*)\])?$/;
+
+/**
+ * Split a grant into its verb and its layer qualifier. `null` for a malformed
+ * qualifier (`metrics:read@`, `@GENERAL[]`, `@GENERAL[a,,b]`, anything after
+ * the `]`), which grants nothing — a typo must not confer the whole layer.
+ */
+export function parseGrant(grant: string): ParsedGrant | null {
+ const at = grant.indexOf('@');
+ if (at < 0) return { verb: grant };
+ const verb = grant.slice(0, at);
+ const m = QUALIFIER.exec(grant.slice(at + 1));
+ if (!verb || !m) return null;
+ const layer = m[1]!.toUpperCase();
+ if (m[2] === undefined) return { verb, qualifier: { layer } };
+ const groups = m[2].split(',').map((g) => g.trim());
+ if (groups.some((g) => g === '')) return null;
+ return {
+ verb,
+ qualifier: { layer, groups: groups.map((g) => (g === UNGROUPED_GRANT ? '' : g)) },
+ };
+}
+
+/**
+ * Does a layer grant's VERB part cover `required`? `*@GENERAL` covers every
+ * layer-scoped verb on GENERAL; `admin@GENERAL` covers nothing — the sentinel
+ * means "everything", and everything has no layer.
+ */
+export function qualifiedVerbCovers(grant: ParsedGrant, required: Verb): boolean {
+ if (!grant.qualifier || grant.verb === 'admin' || !LAYER_SCOPED_VERBS.has(required)) return false;
+ return grant.verb === '*' || matchOne(grant.verb, required);
+}
+
/** True for a grant the verb grammar accepts even though it names no known
* verb: the wildcards, and any retired name still expanded by VERB_ALIASES.
- * Used by the boot-time warning so it does not flag the stock `admin` role. */
+ * Used by the boot-time warning so it does not flag the stock `admin` role.
+ * A layer grant is recognised only when it covers a layer-scoped verb. */
export function isGrantRecognised(grant: string): boolean {
+ if (grant.includes('@')) {
+ const parsed = parseGrant(grant);
+ if (!parsed?.qualifier) return false;
+ return [...LAYER_SCOPED_VERBS].some((v) => qualifiedVerbCovers(parsed, v));
+ }
if (grant === '*' || grant === 'admin') return true;
if (aliasesFor(grant).length > 0) return true;
// Ask the matcher itself rather than re-deriving the grammar beside it: a
@@ -213,6 +306,9 @@ export function isGrantRecognised(grant: string): boolean {
}
function matchOne(grant: Verb, required: Verb): boolean {
+ // A layer-limited grant never answers a question that has no layer in it:
+ // `metrics:read@GENERAL` must not open the overview or the 3D map.
+ if (grant.includes('@')) return false;
if (grant === '*' || grant === 'admin') return true;
if (grant === required) return true;
if (WILDCARD_EXEMPT_VERBS.has(required)) return false;
@@ -250,7 +346,38 @@ export function resolveVerbsForRoles(
for (const r of userRoles)
for (const v of rolePolicy[r] ?? []) {
set.add(v);
+ // Retired names expand only when written plain: `dashboard:read@X`
+ // names no layer verb, and expanding it would hand out an UNQUALIFIED
+ // `layer-template:read` from a grant that asked for one layer.
for (const a of aliasesFor(v)) set.add(a);
}
return [...set];
}
+
+/**
+ * What a grant still confers under an OAuth scope's cap. A cap is a set of
+ * PLAIN verbs and narrows by verb, never by layer: `metrics:*@GENERAL` under
+ * `*:read` is `metrics:read@GENERAL`. A plain grant is returned as it is —
+ * the gate intersects it with the cap on every check.
+ */
+export function capGrant(grant: Verb, cap: readonly Verb[] | undefined): Verb[] {
+ if (!cap || !grant.includes('@')) return [grant];
+ const parsed = parseGrant(grant);
+ if (!parsed?.qualifier) return [];
+ if (hasVerb(cap, parsed.verb)) return [grant];
+ const where = grant.slice(grant.indexOf('@'));
+ return [...LAYER_SCOPED_VERBS].filter((v) => qualifiedVerbCovers(parsed, v) && hasVerb(cap, v)).map((v) => `${v}${where}`);
+}
+
+/** Does any grant cover `required`, plain or on some layer? The route gate
+ * asks this for a route that names a layer or a service, so a user whose
+ * only grant is `metrics:read@GENERAL` reaches the handler; which layer and
+ * which service they may read is decided per request after that. */
+export function hasVerbOnSomeLayer(grantedVerbs: readonly Verb[], required: Verb): boolean {
+ if (hasVerb(grantedVerbs, required)) return true;
+ for (const g of grantedVerbs) {
+ const parsed = g.includes('@') ? parseGrant(g) : null;
+ if (parsed && qualifiedVerbCovers(parsed, required)) return true;
+ }
+ return false;
+}
diff --git a/apps/bff/src/server.ts b/apps/bff/src/server.ts
index 5b0ff8c7..2daccdc1 100644
--- a/apps/bff/src/server.ts
+++ b/apps/bff/src/server.ts
@@ -29,8 +29,11 @@ import { LdapHealth } from './user/ldap-health.js';
import { UserSeenCache } from './user/seen-cache.js';
import { loadConfig, type ConfigSource, BootstrapError } from './config/loader.js';
import type { HorizonConfig } from './config/schema.js';
-import { isGrantRecognised } from './rbac/verbs.js';
+import { isGrantRecognised, parseGrant } from './rbac/verbs.js';
import { makeRouteAuthHook } from './rbac/route-policy.js';
+import type { AccessDeps } from './rbac/request-access.js';
+import { ServiceIdentityResolver } from './logic/services/service-identity.js';
+import { classifyLayers } from './logic/layers/operate-layers.js';
// User
import { registerAuthRoutes } from './http/user.js';
import { registerOidcRoutes } from './user/oidc/route.js';
@@ -160,14 +163,27 @@ setTemplateReadOnly(bootTemplatesMode === 'readonly');
// `rbac.roles` is read per request, so an edit takes effect without a restart.
function warnUnrecognisedGrants(cfg: HorizonConfig): void {
const unknown: string[] = [];
+ const noLayer: string[] = [];
for (const [role, grants] of Object.entries(cfg.rbac.roles))
- for (const g of grants) if (!isGrantRecognised(g)) unknown.push(`${role}: ${g}`);
+ for (const g of grants) {
+ if (isGrantRecognised(g)) continue;
+ // `cluster:read@GENERAL`: a real verb, but one whose data has no layer.
+ const base = g.includes('@') ? parseGrant(g)?.verb : undefined;
+ if (base && isGrantRecognised(base)) noLayer.push(`${role}: ${g}`);
+ else unknown.push(`${role}: ${g}`);
+ }
if (unknown.length > 0) {
logger.warn(
{ grants: unknown },
'rbac.roles names verbs this build does not know; they grant nothing — check for a typo or a verb retired by an upgrade',
);
}
+ if (noLayer.length > 0) {
+ logger.warn(
+ { grants: noLayer },
+ 'rbac.roles limits verbs to a layer that have no layer to limit (only per-service reads such as metrics:read or traces:read can carry @LAYER); these grants give nothing',
+ );
+ }
}
warnUnrecognisedGrants(source.current);
if (source.current.auth.backend === 'ldap' && source.current.auth.local.users.length > 0) {
@@ -267,6 +283,12 @@ await sourceMapStore.loadMountDir(source.current.sourceMaps.bootMountDir);
// mapping. 60s TTL + single-flight dedup; one OAP fan-out per minute
// regardless of how many routes are polling.
const serviceLayer = serviceLayerCatalog({ config: source });
+// Which layers and services each caller may read — shared by the route gate,
+// the handlers that filter rosters, and the AI / MCP tool context.
+const accessDeps: AccessDeps = {
+ services: new ServiceIdentityResolver({ config: source, catalog: serviceLayer }),
+ classify: () => classifyLayers(() => buildOapClients(source.current).uiTemplate()),
+};
await app.register(cookie);
@@ -315,7 +337,7 @@ registerColdStageHook(app);
// Auto-apply RBAC pre-handlers to every route as it's registered. Must
// be added BEFORE the route registrations below — onRoute fires for
// each subsequent app.get/post/...
-app.addHook('onRoute', makeRouteAuthHook({ ...authDeps }));
+app.addHook('onRoute', makeRouteAuthHook({ ...authDeps, access: accessDeps }));
// ── User ───────────────────────────────────────────────────────────
registerAuthRoutes(app, { ...authDeps, ldapHealth, seenCache, audit });
@@ -379,6 +401,7 @@ registerAlarmsQueryRoutes(app, { ...authDeps, serviceLayer });
registerAiRoutes(app, {
...authDeps,
uiTemplateClient: () => buildOapClients(source.current).uiTemplate(),
+ access: accessDeps,
});
registerOAuthRoutes(app, {
...authDeps,
@@ -388,6 +411,7 @@ registerMcpRoutes(app, {
...authDeps,
uiTemplateClient: () => buildOapClients(source.current).uiTemplate(),
version: HORIZON_VERSION,
+ access: accessDeps,
});
registerPreflightRoutes(app, { ...authDeps });
registerTtlRoute(app, { ...authDeps });
diff --git a/apps/ui/src/api/client.ts b/apps/ui/src/api/client.ts
index d608576a..b1f4ba2a 100644
--- a/apps/ui/src/api/client.ts
+++ b/apps/ui/src/api/client.ts
@@ -51,6 +51,7 @@ import type {
import { pushEvent } from '@/controls/eventLog';
import { COLD_STAGE_HEADER, readColdStageHeader } from '@/controls/coldStage';
import { currentLocale } from '@/i18n';
+import { describeRefusal, permissionDeniedOf, permissionDeniedText } from './permissionDenied';
import { SessionApi } from './scopes/session';
import { OAuthApi } from './scopes/oauth';
import { OidcApi } from './scopes/oidc';
@@ -321,7 +322,13 @@ export interface MeResponse {
provider?: string;
providerName?: string;
roles: string[];
+ /** Resolved grants. A grant may be limited to a layer and its OAP service
+ * groups — `metrics:read@GENERAL[payments]` — and then never answers a
+ * plain check; see `state/verbGrammar.ts`. */
verbs: string[];
+ /** An OAuth credential's scope: plain verbs every check is intersected
+ * with. Absent for a browser session or an API token. */
+ verbCap?: string[];
/** Server-suggested landing route based on the user's role. The
* router uses this on fresh login when no `?redirect=` is set. */
landingRoute?: string;
@@ -462,6 +469,8 @@ export class BffApiError extends Error {
* both the {@link BffApiError} envelope AND the upstream
* `{ status: 'error', code, message }` shape that surfaces through it. */
export function describeApiError(err: unknown): string {
+ const refusal = permissionDeniedText(err);
+ if (refusal) return refusal;
if (
err instanceof BffApiError ||
(typeof err === 'object' && err !== null && 'status' in err && 'body' in err)
@@ -961,7 +970,11 @@ export class BffClient {
extra = ` · ${parsed}`;
}
pushEvent('api', 'err', `${method} ${path} · ${res.status}${extra}`);
- throw new BffApiError(res.status, `${method} ${path} failed (${res.status})`, parsed, method, path);
+ // A refusal with a reason becomes the message itself, so every page that
+ // prints `err.message` says why rather than "failed (403)".
+ const denied = permissionDeniedOf(res.status, parsed);
+ const refusal = denied ? describeRefusal(denied) : null;
+ throw new BffApiError(res.status, refusal ?? `${method} ${path} failed (${res.status})`, parsed, method, path);
}
if (res.status === 204) return undefined as T;
const ct = res.headers.get('content-type') ?? '';
diff --git a/apps/ui/src/api/permissionDenied.test.ts b/apps/ui/src/api/permissionDenied.test.ts
new file mode 100644
index 00000000..371f5eab
--- /dev/null
+++ b/apps/ui/src/api/permissionDenied.test.ts
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { BffApiError, bffClient, describeApiError } from './client';
+import { errorText, isPermissionDenied, permissionDeniedText } from './permissionDenied';
+
+const refused = (body: unknown) => new BffApiError(403, 'POST /api/layer/general/logs failed (403)', body);
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('a refused data read', () => {
+ it('reads as a sentence when the BFF says why', () => {
+ const err = refused({ error: 'permission_denied', verb: 'logs:read', reason: 'service_required' });
+ expect(permissionDeniedText(err)).toMatch(/^Pick a service/);
+ expect(describeApiError(err)).toMatch(/^Pick a service/);
+ expect(errorText(err)).toMatch(/^Pick a service/);
+ expect(permissionDeniedText(refused({ error: 'permission_denied', verb: 'metrics:read', reason: 'layer_not_granted', layer: 'banyandb' })))
+ .toBe('You do not have access to the BANYANDB layer.');
+ });
+
+ it('keeps today\'s wording for a refusal without a reason, and for any other failure', () => {
+ const plain = refused({ error: 'permission_denied', verb: 'metrics:read' });
+ expect(isPermissionDenied(plain)).toBe(true);
+ expect(permissionDeniedText(plain)).toBeNull();
+ expect(describeApiError(plain)).toBe('403: permission_denied');
+ const failed = new BffApiError(500, 'GET /api/x failed (500)', { error: 'boom' });
+ expect(isPermissionDenied(failed)).toBe(false);
+ expect(errorText(failed)).toBe(String(failed));
+ });
+
+ it('becomes the thrown error\'s message, so pages printing err.message say why', async () => {
+ vi.stubGlobal('fetch', vi.fn(async () => new Response(
+ JSON.stringify({ error: 'permission_denied', verb: 'traces:read', reason: 'service_not_granted' }),
+ { status: 403, headers: { 'content-type': 'application/json' } },
+ )));
+ await expect(bffClient.request('POST', '/api/layer/general/traces', {})).rejects.toThrow('You do not have access to this service.');
+ });
+});
diff --git a/apps/ui/src/api/permissionDenied.ts b/apps/ui/src/api/permissionDenied.ts
new file mode 100644
index 00000000..60ff7406
--- /dev/null
+++ b/apps/ui/src/api/permissionDenied.ts
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The BFF's refusal of a data read: HTTP 403 `{ error: 'permission_denied',
+ * verb, reason?, layer? }`. A `reason` comes with a refusal decided by which
+ * layer or service the request reached for, rather than by the verb alone; it
+ * is turned into a sentence here so a page says why, not "failed (403)".
+ */
+
+import { i18n } from '@/i18n';
+
+export interface PermissionDenied {
+ verb?: string;
+ reason?: string;
+ layer?: string;
+}
+
+function str(v: unknown): string | undefined {
+ return typeof v === 'string' && v.length > 0 ? v : undefined;
+}
+
+export function permissionDeniedOf(status: number, body: unknown): PermissionDenied | null {
+ if (status !== 403 || !body || typeof body !== 'object') return null;
+ const o = body as Record<string, unknown>;
+ if (o.error !== 'permission_denied') return null;
+ return { verb: str(o.verb), reason: str(o.reason), layer: str(o.layer) };
+}
+
+/** Null for a refusal without a reason — the plain missing-verb 403, whose
+ * wording callers already have. */
+export function describeRefusal(d: PermissionDenied): string | null {
+ if (!d.reason) return null;
+ const t = i18n.global.t;
+ switch (d.reason) {
+ case 'service_required':
+ return t('Pick a service: you can read only some services of this layer, so a query across all of them is refused.');
+ case 'service_not_granted':
+ return t('You do not have access to this service.');
+ case 'layer_not_granted':
+ return d.layer
+ ? t('You do not have access to the {layer} layer.', { layer: d.layer.toUpperCase() })
+ : t('You do not have access to this layer.');
+ case 'id_names_no_service':
+ case 'segment_ids_name_no_service':
+ case 'schedule_ids_name_no_service':
+ case 'task_id_names_no_service':
+ case 'expression_names_no_service':
+ case 'not_attributable_to_a_service':
+ return t('This read does not name a service, and you can read only some services.');
+ case 'alarm_filter_unsupported':
+ return t('This OAP cannot filter alarms by service, and you can read only some services.');
+ case 'alarm_counts_are_deployment_wide':
+ return t('Alarm counts cover every service, and you can read only some services.');
+ case 'preview_needs_template_write':
+ return t('Previewing a draft template needs the layer-template:write permission.');
+ default:
+ return t('Access denied ({reason}).', { reason: d.reason });
+ }
+}
+
+function refusalOf(err: unknown): PermissionDenied | null {
+ if (!err || typeof err !== 'object' || !('status' in err) || !('body' in err)) return null;
+ const { status, body } = err as { status: unknown; body: unknown };
+ return typeof status === 'number' ? permissionDeniedOf(status, body) : null;
+}
+
+/** Any refusal, with or without a reason. */
+export function isPermissionDenied(err: unknown): boolean {
+ return refusalOf(err) !== null;
+}
+
+/** The sentence for a refused BFF read, or null when `err` is anything else. */
+export function permissionDeniedText(err: unknown): string | null {
+ const d = refusalOf(err);
+ return d ? describeRefusal(d) : null;
+}
+
+/** `String(err)` for everything but a refusal with a reason, which reads as
+ * its sentence instead of `BffApiError: …`. */
+export function errorText(err: unknown): string {
+ return permissionDeniedText(err) ?? String(err);
+}
diff --git a/apps/ui/src/api/queryClient.ts b/apps/ui/src/api/queryClient.ts
index 7a61488a..44af37a4 100644
--- a/apps/ui/src/api/queryClient.ts
+++ b/apps/ui/src/api/queryClient.ts
@@ -42,6 +42,9 @@ export const queryClient = new QueryClient({
* request the cancellation existed to stop, so the sixty-second cap would
* abort the fan-out and then immediately ask for it again.
*
+ * A refusal (403) is an answer too: the caller's grants will not change
+ * between the attempt and the retry.
+ *
* Matched by NAME rather than by class: importing the error here would
* close an import cycle back through the graph layer, and the name is
* what the class sets.
@@ -50,6 +53,7 @@ export const queryClient = new QueryClient({
if (err.name === 'GraphUnavailableError') return false;
if (err.name === 'AbortError') return false;
if ((err as { cancelled?: boolean }).cancelled === true) return false;
+ if (err.name === 'BffApiError' && (err as { status?: number }).status === 403) return false;
return count < 1;
},
},
diff --git a/apps/ui/src/features/admin/roles/RolesView.test.ts b/apps/ui/src/features/admin/roles/RolesView.test.ts
index 1ce8ed8b..0114020f 100644
--- a/apps/ui/src/features/admin/roles/RolesView.test.ts
+++ b/apps/ui/src/features/admin/roles/RolesView.test.ts
@@ -34,7 +34,10 @@ import RolesView from './RolesView.vue';
const RESERVED = 'user:write';
const ENFORCED = 'alarms:read';
-function fakeAuthStatus(): typeof fetch {
+function fakeAuthStatus(
+ roles: Record<string, string[]> = { viewer: [ENFORCED], operator: [ENFORCED, RESERVED] },
+ knownVerbs: string[] = [ENFORCED, RESERVED],
+): typeof fetch {
const body = {
configPath: '/etc/horizon.yaml',
configMtime: null,
@@ -47,9 +50,9 @@ function fakeAuthStatus(): typeof fetch {
breakGlass: { configured: false, armed: false, username: null },
rbac: {
enabled: true,
- roles: { viewer: [ENFORCED], operator: [ENFORCED, RESERVED] },
+ roles,
landingByRole: { viewer: '/' },
- knownVerbs: [ENFORCED, RESERVED],
+ knownVerbs,
reservedVerbs: [RESERVED],
},
};
@@ -108,3 +111,39 @@ describe('Roles board — reserved capabilities', () => {
expect(cells.map((c) => c.classes().includes('check-on'))).toEqual([false, true]);
});
});
+
+describe('Roles board — layer-qualified grants', () => {
+ const roles = {
+ viewer: ['metrics:read'],
+ payments: ['metrics:read@GENERAL[payments, -]', 'traces:read@general', 'cluster:read@GENERAL'],
+ };
+
+ it('lists each role\'s layer grants, and marks one that grants nothing', async () => {
+ vi.stubGlobal('fetch', fakeAuthStatus(roles, ['metrics:read', 'traces:read']));
+ const w = await mountRoles();
+
+ const card = w.findAll('.role-card').find((c) => c.text().includes('payments'))!;
+ const items = card.findAll('.role-layers-list li').map((li) => li.text());
+ expect(items).toEqual([
+ 'metrics:read on GENERAL[payments, no group]',
+ 'traces:read on GENERAL',
+ 'cluster:read on GENERALNo effect',
+ ]);
+ const viewer = w.findAll('.role-card').find((c) => c.text().includes('viewer'))!;
+ expect(viewer.find('.role-layers').exists()).toBe(false);
+ });
+
+ it('draws a partial mark, not a check, for a verb held only on some layers', async () => {
+ vi.stubGlobal('fetch', fakeAuthStatus(roles, ['metrics:read', 'traces:read']));
+ const w = await mountRoles();
+
+ // viewer · payments, in that column order.
+ const marks = (label: string) =>
+ w.findAll('.perm tbody tr')
+ .find((tr) => tr.text().includes(label))!
+ .findAll('.td-cell .check')
+ .map((c) => c.classes().find((k) => k.startsWith('check-')));
+ expect(marks('See metric dashboards')).toEqual(['check-on', 'check-part']);
+ expect(marks('See traces')).toEqual(['check-off', 'check-part']);
+ });
+});
diff --git a/apps/ui/src/features/admin/roles/RolesView.vue b/apps/ui/src/features/admin/roles/RolesView.vue
index d03b1642..5394f6e3 100644
--- a/apps/ui/src/features/admin/roles/RolesView.vue
+++ b/apps/ui/src/features/admin/roles/RolesView.vue
@@ -17,7 +17,7 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
-import { WILDCARD_EXEMPT_VERBS } from '@/state/wildcardExempt';
+import { LAYER_SCOPED_VERBS, layerGrantCovers, matchOne, parseLayerGrant, type LayerGrant } from '@/state/verbGrammar';
import { aliasesFor } from '@/state/verbAliases';
import { bff } from '@/api/client';
import type { AuthStatus } from '@/api/scopes/admin-auth';
@@ -47,27 +47,11 @@ async function load(): Promise<void> {
}
onMounted(load);
-/** Matcher mirroring the server's verb resolution. */
+/** Matcher mirroring the server's verb resolution. Raw policy grants, so
+ * retired names are expanded here the way `resolveVerbsForRoles` expands
+ * them server-side. */
function hasVerb(grants: readonly string[], required: string): boolean {
- // Raw policy grants, so retired names must be expanded here the way
- // `resolveVerbsForRoles` expands them server-side.
- for (const g of [...grants, ...grants.flatMap(aliasesFor)]) {
- if (g === '*' || g === 'admin') return true;
- if (g === required) return true;
- // Before the wildcard branches, exactly as the BFF places it — otherwise
- // this board draws a check mark for a grant the server denies, on the row
- // whose own hint says a wildcard does not include it.
- if (WILDCARD_EXEMPT_VERBS.has(required)) continue;
- // Both as the BFF: a fourth segment is malformed rather than truncated,
- // and `area:*` carries no sub-segment.
- if (g.split(':').length > 3) continue;
- const gp = g.split(':', 3);
- const rp = required.split(':', 3);
- if (gp[0] === rp[0] && gp[1] === '*' && gp[2] === undefined) return true;
- if (gp[0] === '*' && gp[1] === rp[1] && (gp[2] ?? '') === (rp[2] ?? '')) return true;
- if (gp[0] === rp[0] && gp[1] === rp[1] && (gp[2] ?? '') === (rp[2] ?? '')) return true;
- }
- return false;
+ return [...grants, ...grants.flatMap(aliasesFor)].some((g) => matchOne(g, required));
}
const roleNames = computed(() => Object.keys(status.value?.rbac.roles ?? {}).sort(rolePriority));
@@ -409,6 +393,34 @@ const groupedVerbs = computed<Array<VerbGroup & { items: string[] }>>(() => {
function grantsOf(role: string): string[] {
return status.value?.rbac.roles[role] ?? [];
}
+
+interface RoleLayerGrant {
+ raw: string;
+ /** Null when the qualifier is malformed. */
+ parsed: LayerGrant | null;
+ /** Covers at least one per-service read; otherwise the BFF grants nothing for it. */
+ effective: boolean;
+}
+/** A role's `verb@LAYER[groups]` grants. The grids cannot show them as check
+ * marks: a layer grant never confers the plain capability a row stands for. */
+function layerGrantsOf(role: string): RoleLayerGrant[] {
+ const out: RoleLayerGrant[] = [];
+ for (const raw of grantsOf(role)) {
+ if (!raw.includes('@')) continue;
+ const parsed = parseLayerGrant(raw);
+ const effective = parsed !== null && [...LAYER_SCOPED_VERBS].some((v) => layerGrantCovers(parsed, v));
+ out.push({ raw, parsed, effective });
+ }
+ return out;
+}
+function groupLabels(groups: readonly string[]): string {
+ return groups.map((g) => (g === '' ? t('no group') : g)).join(', ');
+}
+/** Held on some layers but not plainly — a partial mark rather than a dot. */
+function layerOnly(role: string, verb: string): boolean {
+ if (hasVerb(grantsOf(role), verb)) return false;
+ return layerGrantsOf(role).some((g) => g.parsed !== null && layerGrantCovers(g.parsed, verb));
+}
</script>
<template>
@@ -440,6 +452,24 @@ function grantsOf(role: string): string[] {
<div v-for="r in roleNames" :key="r" class="role-card">
<span class="pill" :class="rolePill(r)">{{ r }}</span>
<p class="role-blurb">{{ roleBlurb(r) }}</p>
+ <div v-if="layerGrantsOf(r).length > 0" class="role-layers">
+ <span class="role-layers-head">{{ t('Limited to layers') }}</span>
+ <ul class="role-layers-list">
+ <li v-for="g in layerGrantsOf(r)" :key="g.raw" :class="{ 'is-void': !g.effective }">
+ <i18n-t v-if="g.parsed" keypath="{verb} on {layer}" tag="span" scope="global">
+ <template #verb><code>{{ g.parsed.verb }}</code></template>
+ <template #layer><code>{{ g.parsed.layer }}</code></template>
+ </i18n-t>
+ <code v-else>{{ g.raw }}</code>
+ <span v-if="g.parsed?.groups" class="role-layers-groups">[{{ groupLabels(g.parsed.groups) }}]</span>
+ <span
+ v-if="!g.effective"
+ class="pill pill-muted"
+ :title="t('Grants nothing: the qualifier is malformed, or the verb is not a per-service read.')"
+ >{{ t('No effect') }}</span>
+ </li>
+ </ul>
+ </div>
</div>
</div>
</section>
@@ -534,6 +564,12 @@ function grantsOf(role: string): string[] {
</td>
<td v-for="r in roleNames" :key="r" class="td-cell">
<span v-if="hasVerb(grantsOf(r), v)" class="check check-on" :aria-label="t('allowed')">✓</span>
+ <span
+ v-else-if="layerOnly(r, v)"
+ class="check check-part"
+ :title="t('on some layers only')"
+ :aria-label="t('on some layers only')"
+ >◐</span>
<span v-else class="check check-off" :aria-label="t('not allowed')">·</span>
</td>
</tr>
@@ -606,6 +642,43 @@ function grantsOf(role: string): string[] {
color: var(--sw-fg-2);
line-height: var(--sw-lh-normal);
}
+.role-layers {
+ margin-top: 8px;
+ padding-top: 6px;
+ border-top: 1px dashed var(--sw-line);
+}
+.role-layers-head {
+ font-size: var(--sw-fs-xs);
+ font-weight: var(--sw-fw-bold);
+ text-transform: uppercase;
+ letter-spacing: var(--sw-ls-caps);
+ color: var(--sw-fg-3);
+}
+.role-layers-list {
+ list-style: none;
+ margin: 4px 0 0;
+ padding: 0;
+ font-size: var(--sw-fs-sm);
+ color: var(--sw-fg-1);
+}
+.role-layers-list li {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px;
+ line-height: var(--sw-lh-normal);
+}
+.role-layers-list code {
+ font-family: var(--sw-mono);
+ font-size: var(--sw-fs-xs);
+ color: var(--sw-fg-0);
+}
+.role-layers-groups {
+ font-family: var(--sw-mono);
+ font-size: var(--sw-fs-xs);
+ color: var(--sw-fg-2);
+}
+.role-layers-list li.is-void code { color: var(--sw-fg-3); text-decoration: line-through; }
.muted { color: var(--sw-fg-3); font-size: var(--sw-fs-sm); font-weight: var(--sw-fw-regular); }
.card-head h3 + .muted { margin-left: 6px; }
@@ -756,6 +829,10 @@ function grantsOf(role: string): string[] {
background: rgba(34, 197, 94, 0.16);
color: var(--sw-ok);
}
+.check-part {
+ background: var(--sw-warn-soft);
+ color: var(--sw-warn);
+}
.check-off {
color: var(--sw-fg-3);
background: transparent;
diff --git a/apps/ui/src/features/alarms/AlarmFilterRow.vue b/apps/ui/src/features/alarms/AlarmFilterRow.vue
index 7b84693f..08647f5b 100644
--- a/apps/ui/src/features/alarms/AlarmFilterRow.vue
+++ b/apps/ui/src/features/alarms/AlarmFilterRow.vue
@@ -26,7 +26,10 @@
-->
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
+import { computed } from 'vue';
import { useLayers } from '@/shell/useLayers';
+import { useAuthStore } from '@/state/auth';
+import { canonicalLayerKey } from '@/state/verbGrammar';
import type { AlarmFilters } from './useAlarmFilters';
const { t } = useI18n();
@@ -35,7 +38,22 @@ const f = props.filters;
const draft = f.draft;
const applied = f.applied;
-const { availableLayers } = useLayers();
+const { availableLayers, alarmLayers } = useLayers();
+const auth = useAuthStore();
+// A reader whose alarms:read is limited to some layers picks one of those, and
+// a service in it: the BFF answers such a reader only for a named service.
+const limitedLayers = computed(() => auth.layersFor('alarms:read'));
+const layerOptions = computed(() => {
+ // With layer grants the sidebar follows page permissions, not alarms:read,
+ // so the BFF lists the alarm layers on their own.
+ if (alarmLayers.value) return alarmLayers.value;
+ const limited = limitedLayers.value;
+ if (!limited) return availableLayers.value.map((L) => ({ key: L.key.toUpperCase(), name: L.name }));
+ return limited.map((key) => ({
+ key,
+ name: availableLayers.value.find((L) => canonicalLayerKey(L.key.split('~', 1)[0]!) === key)?.name ?? key,
+ }));
+});
</script>
<template>
@@ -43,15 +61,15 @@ const { availableLayers } = useLayers();
<label class="ax__filter">
<span>{{ t('Layer') }}</span>
<select v-model="draft.layer" @change="f.onLayerChange()">
- <option value="">{{ t('any layer') }}</option>
- <option v-for="L in availableLayers" :key="L.key" :value="L.key.toUpperCase()">{{ L.name }}</option>
+ <option value="">{{ limitedLayers ? t('pick a layer first') : t('any layer') }}</option>
+ <option v-for="L in layerOptions" :key="L.key" :value="L.key">{{ L.name }}</option>
</select>
</label>
<label class="ax__filter" :class="{ 'is-disabled': !draft.layer }">
<span>{{ t('Service') }}</span>
<select v-model="draft.service" :disabled="!draft.layer" @change="f.onServiceChange()">
<option value="">
- {{ !draft.layer ? t('pick a layer first') : f.servicesFetching.value ? t('loading…') : t('any service') }}
+ {{ !draft.layer ? t('pick a layer first') : f.servicesFetching.value ? t('loading…') : limitedLayers ? t('Pick a service') : t('any service') }}
</option>
<option v-for="s in f.serviceOptions.value" :key="`${s.name}/${s.normal}`" :value="s.name">{{ s.name }}</option>
</select>
diff --git a/apps/ui/src/features/alarms/AlarmsView.test.ts b/apps/ui/src/features/alarms/AlarmsView.test.ts
index db1b9876..6ec779de 100644
--- a/apps/ui/src/features/alarms/AlarmsView.test.ts
+++ b/apps/ui/src/features/alarms/AlarmsView.test.ts
@@ -31,6 +31,11 @@ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query';
import { i18n } from '@/i18n';
import AlarmsView from './AlarmsView.vue';
+// A plain alarms reader — the page as every deployment without layer grants sees it.
+vi.mock('@/state/auth', () => ({
+ useAuthStore: () => ({ hasVerb: () => true, layerLimited: () => false, layersFor: () => null }),
+}));
+
const LAYER = 'VIRTUAL_DATABASE';
/** A conjectural service and an agent-reporting one, on the same roster. */
const VIRTUAL = 'mysql-a';
diff --git a/apps/ui/src/features/alarms/AlarmsView.vue b/apps/ui/src/features/alarms/AlarmsView.vue
index 2766ea75..21e2934c 100644
--- a/apps/ui/src/features/alarms/AlarmsView.vue
+++ b/apps/ui/src/features/alarms/AlarmsView.vue
@@ -48,6 +48,7 @@ import {
type AlarmsResponse,
} from '@/api/client';
import { useOapInfo } from '@/shell/useOapInfo';
+import { useAuthStore } from '@/state/auth';
import AlarmsTimeline from '@/components/charts/AlarmsTimeline.vue';
import AlarmDetailPanel from './AlarmDetailPanel.vue';
import AlarmWindowPicker from './AlarmWindowPicker.vue';
@@ -136,7 +137,12 @@ function clearSelection(): void {
selectedRange.value = null;
}
+// A reader whose alarms:read is limited to some layers is answered only for a
+// named service, so nothing is read until one is applied.
+const auth = useAuthStore();
+const serviceNeeded = computed(() => auth.layerLimited('alarms:read') && !applied.value.service);
const alarmsQuery = useQuery({
+ enabled: computed(() => !serviceNeeded.value),
queryKey: computed(() => [
'alarms',
startTime.value,
@@ -508,7 +514,8 @@ async function onRefresh(): Promise<void> {
</button>
</div>
- <div v-if="alarmsQuery.isPending.value" class="ax__empty">{{ t('loading…') }}</div>
+ <div v-if="serviceNeeded" class="ax__empty">{{ t('Pick a layer and a service to see their alarms.') }}</div>
+ <div v-else-if="alarmsQuery.isPending.value" class="ax__empty">{{ t('loading…') }}</div>
<div v-else-if="filteredIncidents.length === 0" class="ax__empty">
{{ t('No alarms in the current window.') }}
</div>
diff --git a/apps/ui/src/i18n/locales/de.json b/apps/ui/src/i18n/locales/de.json
index 311e061e..7f303ab9 100644
--- a/apps/ui/src/i18n/locales/de.json
+++ b/apps/ui/src/i18n/locales/de.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "Ausführungsdatensatz",
"the record as the document carries it": "der Datensatz, wie ihn das Dokument enthält",
- "the call’s result as the document carries it": "das Ergebnis des Aufrufs, wie es das Dokument enthält"
+ "the call’s result as the document carries it": "das Ergebnis des Aufrufs, wie es das Dokument enthält",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "Wählen Sie einen Service: Sie dürfen nur einige Services dieser Ebene lesen, daher wird eine Abfrage über alle abgelehnt.",
+ "You do not have access to this service.": "Sie haben keinen Zugriff auf diesen Service.",
+ "You do not have access to the {layer} layer.": "Sie haben keinen Zugriff auf die Ebene {layer}.",
+ "You do not have access to this layer.": "Sie haben keinen Zugriff auf diese Ebene.",
+ "This read does not name a service, and you can read only some services.": "Diese Abfrage nennt keinen Service, und Sie dürfen nur einige Services lesen.",
+ "Alarm counts cover every service, and you can read only some services.": "Alarmzahlen umfassen alle Services, Sie dürfen aber nur einige Services lesen.",
+ "Previewing a draft template needs the layer-template:write permission.": "Die Vorschau eines Vorlagenentwurfs erfordert die Berechtigung layer-template:write.",
+ "Access denied ({reason}).": "Zugriff verweigert ({reason}).",
+ "No access to this layer": "Kein Zugriff auf diese Ebene",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "Ihre Rollen gewähren keinen Zugriff auf die Ebene {layer}. Wenden Sie sich an einen Administrator, falls Sie ihn benötigen.",
+ "Limited to layers": "Auf Ebenen beschränkt",
+ "{verb} on {layer}": "{verb} auf {layer}",
+ "no group": "ohne Gruppe",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "Gewährt nichts: Die Einschränkung ist fehlerhaft, oder das Verb ist kein servicebezogener Lesezugriff.",
+ "No effect": "Wirkungslos",
+ "on some layers only": "nur auf einigen Ebenen",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "Dieser OAP kann Alarme nicht nach Service filtern, und Sie dürfen nur einige Services lesen.",
+ "Pick a layer and a service to see their alarms.": "Wählen Sie eine Ebene und einen Service, um deren Alarme zu sehen."
}
diff --git a/apps/ui/src/i18n/locales/en.json b/apps/ui/src/i18n/locales/en.json
index a5fb81e7..a2ca37e0 100644
--- a/apps/ui/src/i18n/locales/en.json
+++ b/apps/ui/src/i18n/locales/en.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "execution record",
"the record as the document carries it": "the record as the document carries it",
- "the call’s result as the document carries it": "the call’s result as the document carries it"
+ "the call’s result as the document carries it": "the call’s result as the document carries it",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "Pick a service: you can read only some services of this layer, so a query across all of them is refused.",
+ "You do not have access to this service.": "You do not have access to this service.",
+ "You do not have access to the {layer} layer.": "You do not have access to the {layer} layer.",
+ "You do not have access to this layer.": "You do not have access to this layer.",
+ "This read does not name a service, and you can read only some services.": "This read does not name a service, and you can read only some services.",
+ "Alarm counts cover every service, and you can read only some services.": "Alarm counts cover every service, and you can read only some services.",
+ "Previewing a draft template needs the layer-template:write permission.": "Previewing a draft template needs the layer-template:write permission.",
+ "Access denied ({reason}).": "Access denied ({reason}).",
+ "No access to this layer": "No access to this layer",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.",
+ "Limited to layers": "Limited to layers",
+ "{verb} on {layer}": "{verb} on {layer}",
+ "no group": "no group",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.",
+ "No effect": "No effect",
+ "on some layers only": "on some layers only",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "This OAP cannot filter alarms by service, and you can read only some services.",
+ "Pick a layer and a service to see their alarms.": "Pick a layer and a service to see their alarms."
}
diff --git a/apps/ui/src/i18n/locales/es.json b/apps/ui/src/i18n/locales/es.json
index b317f143..511a8839 100644
--- a/apps/ui/src/i18n/locales/es.json
+++ b/apps/ui/src/i18n/locales/es.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "registro de ejecución",
"the record as the document carries it": "el registro tal como lo lleva el documento",
- "the call’s result as the document carries it": "el resultado de la llamada tal como lo lleva el documento"
+ "the call’s result as the document carries it": "el resultado de la llamada tal como lo lleva el documento",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "Elige un servicio: solo puedes leer algunos servicios de esta capa, así que se rechaza una consulta sobre todos ellos.",
+ "You do not have access to this service.": "No tienes acceso a este servicio.",
+ "You do not have access to the {layer} layer.": "No tienes acceso a la capa {layer}.",
+ "You do not have access to this layer.": "No tienes acceso a esta capa.",
+ "This read does not name a service, and you can read only some services.": "Esta lectura no indica ningún servicio, y solo puedes leer algunos servicios.",
+ "Alarm counts cover every service, and you can read only some services.": "Los recuentos de alarmas abarcan todos los servicios, y solo puedes leer algunos.",
+ "Previewing a draft template needs the layer-template:write permission.": "Previsualizar un borrador de plantilla requiere el permiso layer-template:write.",
+ "Access denied ({reason}).": "Acceso denegado ({reason}).",
+ "No access to this layer": "Sin acceso a esta capa",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "Tus roles no te dan acceso a la capa {layer}. Pídeselo a un administrador si lo necesitas.",
+ "Limited to layers": "Limitado a capas",
+ "{verb} on {layer}": "{verb} en {layer}",
+ "no group": "sin grupo",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "No concede nada: el calificador está mal formado o el verbo no es una lectura por servicio.",
+ "No effect": "Sin efecto",
+ "on some layers only": "solo en algunas capas",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "Este OAP no puede filtrar las alarmas por servicio, y solo puede leer algunos servicios.",
+ "Pick a layer and a service to see their alarms.": "Elija una capa y un servicio para ver sus alarmas."
}
diff --git a/apps/ui/src/i18n/locales/fr.json b/apps/ui/src/i18n/locales/fr.json
index 1d3c4d6c..ab272b29 100644
--- a/apps/ui/src/i18n/locales/fr.json
+++ b/apps/ui/src/i18n/locales/fr.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "enregistrement d’exécution",
"the record as the document carries it": "l’enregistrement tel que le document le porte",
- "the call’s result as the document carries it": "le résultat de l’appel tel que le document le porte"
+ "the call’s result as the document carries it": "le résultat de l’appel tel que le document le porte",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "Choisissez un service : vous ne pouvez lire que certains services de cette couche, une requête sur tous est donc refusée.",
+ "You do not have access to this service.": "Vous n’avez pas accès à ce service.",
+ "You do not have access to the {layer} layer.": "Vous n’avez pas accès à la couche {layer}.",
+ "You do not have access to this layer.": "Vous n’avez pas accès à cette couche.",
+ "This read does not name a service, and you can read only some services.": "Cette lecture ne désigne aucun service, et vous ne pouvez lire que certains services.",
+ "Alarm counts cover every service, and you can read only some services.": "Les décomptes d’alarmes couvrent tous les services, et vous ne pouvez lire que certains services.",
+ "Previewing a draft template needs the layer-template:write permission.": "Prévisualiser un brouillon de modèle nécessite la permission layer-template:write.",
+ "Access denied ({reason}).": "Accès refusé ({reason}).",
+ "No access to this layer": "Aucun accès à cette couche",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "Vos rôles ne vous donnent pas accès à la couche {layer}. Demandez-le à un administrateur si vous en avez besoin.",
+ "Limited to layers": "Limité à des couches",
+ "{verb} on {layer}": "{verb} sur {layer}",
+ "no group": "sans groupe",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "N’accorde rien : le qualificatif est mal formé, ou le verbe n’est pas une lecture par service.",
+ "No effect": "Sans effet",
+ "on some layers only": "sur certaines couches seulement",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "Cet OAP ne peut pas filtrer les alarmes par service, et vous ne pouvez lire que certains services.",
+ "Pick a layer and a service to see their alarms.": "Choisissez une couche et un service pour voir leurs alarmes."
}
diff --git a/apps/ui/src/i18n/locales/ja.json b/apps/ui/src/i18n/locales/ja.json
index 2ca04fd5..33e5ca5b 100644
--- a/apps/ui/src/i18n/locales/ja.json
+++ b/apps/ui/src/i18n/locales/ja.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "実行レコード",
"the record as the document carries it": "ドキュメントが運ぶままのレコード",
- "the call’s result as the document carries it": "ドキュメントが運ぶままの呼び出しの結果"
+ "the call’s result as the document carries it": "ドキュメントが運ぶままの呼び出しの結果",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "サービスを選択してください。このレイヤーで読み取れるのは一部のサービスのみのため、全サービスを対象とするクエリは拒否されます。",
+ "You do not have access to this service.": "このサービスへのアクセス権がありません。",
+ "You do not have access to the {layer} layer.": "レイヤー {layer} へのアクセス権がありません。",
+ "You do not have access to this layer.": "このレイヤーへのアクセス権がありません。",
+ "This read does not name a service, and you can read only some services.": "この読み取りはサービスを指定していませんが、あなたが読み取れるのは一部のサービスのみです。",
+ "Alarm counts cover every service, and you can read only some services.": "アラーム件数はすべてのサービスを対象としますが、あなたが読み取れるのは一部のサービスのみです。",
+ "Previewing a draft template needs the layer-template:write permission.": "テンプレートの下書きをプレビューするには layer-template:write 権限が必要です。",
+ "Access denied ({reason}).": "アクセスが拒否されました({reason})。",
+ "No access to this layer": "このレイヤーへのアクセス権がありません",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "あなたのロールではレイヤー {layer} にアクセスできません。必要な場合は管理者に依頼してください。",
+ "Limited to layers": "レイヤー限定",
+ "{verb} on {layer}": "{layer} で {verb}",
+ "no group": "グループなし",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "何も付与しません。修飾子の形式が不正か、その動詞がサービス単位の読み取りではありません。",
+ "No effect": "効果なし",
+ "on some layers only": "一部のレイヤーのみ",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "この OAP はアラームをサービスで絞り込めません。また、閲覧できるのは一部のサービスだけです。",
+ "Pick a layer and a service to see their alarms.": "レイヤーとサービスを選ぶと、そのアラームが表示されます。"
}
diff --git a/apps/ui/src/i18n/locales/ko.json b/apps/ui/src/i18n/locales/ko.json
index 94589090..458b96a2 100644
--- a/apps/ui/src/i18n/locales/ko.json
+++ b/apps/ui/src/i18n/locales/ko.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "실행 레코드",
"the record as the document carries it": "문서가 담고 있는 그대로의 레코드",
- "the call’s result as the document carries it": "문서가 담고 있는 그대로의 호출 결과"
+ "the call’s result as the document carries it": "문서가 담고 있는 그대로의 호출 결과",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "서비스를 선택하세요. 이 레이어에서 일부 서비스만 읽을 수 있으므로 모든 서비스를 대상으로 하는 쿼리는 거부됩니다.",
+ "You do not have access to this service.": "이 서비스에 대한 접근 권한이 없습니다.",
+ "You do not have access to the {layer} layer.": "{layer} 레이어에 대한 접근 권한이 없습니다.",
+ "You do not have access to this layer.": "이 레이어에 대한 접근 권한이 없습니다.",
+ "This read does not name a service, and you can read only some services.": "이 조회는 서비스를 지정하지 않지만, 읽을 수 있는 서비스는 일부뿐입니다.",
+ "Alarm counts cover every service, and you can read only some services.": "알람 개수는 모든 서비스를 대상으로 하지만, 읽을 수 있는 서비스는 일부뿐입니다.",
+ "Previewing a draft template needs the layer-template:write permission.": "템플릿 초안을 미리 보려면 layer-template:write 권한이 필요합니다.",
+ "Access denied ({reason}).": "접근이 거부되었습니다({reason}).",
+ "No access to this layer": "이 레이어에 대한 접근 권한 없음",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "현재 역할로는 {layer} 레이어에 접근할 수 없습니다. 필요하면 관리자에게 요청하세요.",
+ "Limited to layers": "레이어로 제한됨",
+ "{verb} on {layer}": "{layer}에서 {verb}",
+ "no group": "그룹 없음",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "아무것도 부여하지 않습니다. 한정자 형식이 잘못되었거나 해당 권한이 서비스 단위 읽기가 아닙니다.",
+ "No effect": "효과 없음",
+ "on some layers only": "일부 레이어에서만",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "이 OAP는 서비스별로 알람을 필터링할 수 없으며, 일부 서비스만 읽을 수 있습니다.",
+ "Pick a layer and a service to see their alarms.": "레이어와 서비스를 선택하면 해당 알람이 표시됩니다."
}
diff --git a/apps/ui/src/i18n/locales/pt.json b/apps/ui/src/i18n/locales/pt.json
index 9e539ee2..a588d1eb 100644
--- a/apps/ui/src/i18n/locales/pt.json
+++ b/apps/ui/src/i18n/locales/pt.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "registro de execução",
"the record as the document carries it": "o registro como o documento o carrega",
- "the call’s result as the document carries it": "o resultado da chamada como o documento o carrega"
+ "the call’s result as the document carries it": "o resultado da chamada como o documento o carrega",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "Escolha um serviço: você só pode ler alguns serviços desta camada, então uma consulta sobre todos eles é recusada.",
+ "You do not have access to this service.": "Você não tem acesso a este serviço.",
+ "You do not have access to the {layer} layer.": "Você não tem acesso à camada {layer}.",
+ "You do not have access to this layer.": "Você não tem acesso a esta camada.",
+ "This read does not name a service, and you can read only some services.": "Esta leitura não indica nenhum serviço, e você só pode ler alguns serviços.",
+ "Alarm counts cover every service, and you can read only some services.": "As contagens de alarmes abrangem todos os serviços, e você só pode ler alguns.",
+ "Previewing a draft template needs the layer-template:write permission.": "Pré-visualizar um rascunho de template exige a permissão layer-template:write.",
+ "Access denied ({reason}).": "Acesso negado ({reason}).",
+ "No access to this layer": "Sem acesso a esta camada",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "Seus papéis não dão acesso à camada {layer}. Peça a um administrador se precisar.",
+ "Limited to layers": "Limitado a camadas",
+ "{verb} on {layer}": "{verb} em {layer}",
+ "no group": "sem grupo",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "Não concede nada: o qualificador está malformado ou o verbo não é uma leitura por serviço.",
+ "No effect": "Sem efeito",
+ "on some layers only": "apenas em algumas camadas",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "Este OAP não consegue filtrar alarmes por serviço, e você só pode ler alguns serviços.",
+ "Pick a layer and a service to see their alarms.": "Escolha uma camada e um serviço para ver os alarmes deles."
}
diff --git a/apps/ui/src/i18n/locales/zh-CN.json b/apps/ui/src/i18n/locales/zh-CN.json
index cca4dec4..637fc119 100644
--- a/apps/ui/src/i18n/locales/zh-CN.json
+++ b/apps/ui/src/i18n/locales/zh-CN.json
@@ -3436,5 +3436,23 @@
"{bytes} B · SHA-256 {digest}": "{bytes} B · SHA-256 {digest}",
"execution record": "执行记录",
"the record as the document carries it": "文档所携带的记录",
- "the call’s result as the document carries it": "文档所携带的调用结果"
+ "the call’s result as the document carries it": "文档所携带的调用结果",
+ "Pick a service: you can read only some services of this layer, so a query across all of them is refused.": "请选择一个服务:你只能读取该 layer 中的部分服务,因此跨所有服务的查询会被拒绝。",
+ "You do not have access to this service.": "你无权访问该服务。",
+ "You do not have access to the {layer} layer.": "你无权访问 {layer} layer。",
+ "You do not have access to this layer.": "你无权访问该 layer。",
+ "This read does not name a service, and you can read only some services.": "此次读取未指定服务,而你只能读取部分服务。",
+ "Alarm counts cover every service, and you can read only some services.": "告警计数覆盖所有服务,而你只能读取部分服务。",
+ "Previewing a draft template needs the layer-template:write permission.": "预览模板草稿需要 layer-template:write 权限。",
+ "Access denied ({reason}).": "访问被拒绝({reason})。",
+ "No access to this layer": "无权访问该 layer",
+ "Your roles do not give you access to the {layer} layer. Ask an administrator if you need it.": "你的角色无权访问 {layer} layer。如有需要,请联系管理员。",
+ "Limited to layers": "仅限指定 layer",
+ "{verb} on {layer}": "{layer} 上的 {verb}",
+ "no group": "无分组",
+ "Grants nothing: the qualifier is malformed, or the verb is not a per-service read.": "不授予任何权限:限定符格式错误,或该权限不是按服务的读取权限。",
+ "No effect": "无效",
+ "on some layers only": "仅部分 layer",
+ "This OAP cannot filter alarms by service, and you can read only some services.": "此 OAP 无法按服务过滤告警,而您只能读取部分服务。",
+ "Pick a layer and a service to see their alarms.": "选择一个 layer 和一个服务,查看它们的告警。"
}
diff --git a/apps/ui/src/layer/LayerShell.vue b/apps/ui/src/layer/LayerShell.vue
index 1cd296fa..1fc87edb 100644
--- a/apps/ui/src/layer/LayerShell.vue
+++ b/apps/ui/src/layer/LayerShell.vue
@@ -32,6 +32,7 @@ import { useQuery } from '@tanstack/vue-query';
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router';
import type { LayerDef, LandingServiceRow } from '@skywalking-horizon-ui/api-client';
import { bffClient } from '@/api/client';
+import { isPermissionDenied } from '@/api/permissionDenied';
import { useAuthStore } from '@/state/auth';
import { useEventsPopout } from '@/features/events/useEventsPopout';
import Icon from '@/components/icons/Icon.vue';
@@ -153,13 +154,23 @@ const previewLayer = computed<LayerDef | null>(() => {
});
const layer = computed<LayerDef | null>(() => menuLayer.value ?? previewLayer.value);
+// Full service roster (the layer's REAL catalog, independent of landing's
+// top-N sample which misses low-traffic services / anything beyond the
+// landingServiceCap). A URL `?service=` is validated against THIS, not the
+// sample, and `selectedRow` resolves an off-sample selection from it.
+//
+// The menu omits a layer the caller may not open, and this read for the same
+// key is refused — which is what tells "no access" apart from an unknown
+// layer. It also settles a menu that is empty because nothing is granted.
+const { services: fullRoster, isLoading: rosterLoading, error: rosterError } = useLayerServices(layerKey);
+const layerDenied = computed<boolean>(() => !menuLayer.value && isPermissionDenied(rosterError.value));
// Distinguishes "still loading" from "truly absent" so the "Layer
// not found" card doesn't flash during a login → layer-URL redirect
// (the menu fetch is in-flight and `layers.value` is briefly []).
// We treat the layer as missing only after the menu request has
// settled AND — in preview mode — the template fetch has settled too.
const menuStillLoading = computed<boolean>(
- () => !menuLayer.value && (layersLoading.value || layers.value.length === 0),
+ () => !menuLayer.value && !layerDenied.value && (layersLoading.value || layers.value.length === 0),
);
const layerMissing = computed<boolean>(() => {
if (layer.value) return false;
@@ -179,6 +190,14 @@ const missingReason = computed<LayerMissingReason>(() =>
// The duplicate is resolved on the template admin page; link there only for
// operators who may open it (the route itself requires `layer-template:read`).
const canOpenLayerTemplates = computed<boolean>(() => auth.hasVerb('layer-template:read'));
+// Held back until the roster answers, so a layer the caller may not open never
+// flashes "Layer not found" before the refusal lands.
+const accessPending = computed<boolean>(
+ () => layerMissing.value && missingReason.value !== 'duplicated' && rosterLoading.value,
+);
+const canReadEvents = computed<boolean>(
+ () => !!layer.value && auth.hasVerbOnLayer('events:read', layer.value.key, layer.value.visibility === 'operate'),
+);
// Auto-redirect when the URL targets a sub-route the layer doesn't
// support — e.g. `/layer/mesh_dp/service` on a layer with
@@ -378,11 +397,6 @@ const aggregates = computed(() =>
const { selectedId, setSelected, lockedServiceIds, toggleLockService } = useSelectedService();
const sampledServices = computed(() => landing.data.value?.sampledRows ?? landing.rows.value ?? []);
const selectorColumns = computed(() => safeCfg.value.columns);
-// Full service roster (the layer's REAL catalog, independent of landing's
-// top-N sample which misses low-traffic services / anything beyond the
-// landingServiceCap). A URL `?service=` is validated against THIS, not the
-// sample, and `selectedRow` resolves an off-sample selection from it.
-const { services: fullRoster, isLoading: rosterLoading } = useLayerServices(layerKey);
const selectedRow = computed<LandingServiceRow | null>(() => {
const id = selectedId.value;
if (id) {
@@ -744,7 +758,7 @@ const serviceKpis = computed<HeaderKpi[]>(() => {
Passes the FULL OAP service NAME (events filter on the literal
`<group>::<base>` name, not the group-stripped display label). -->
<button
- v-if="auth.hasVerb('events:read') && selectedRow?.serviceName"
+ v-if="canReadEvents && selectedRow?.serviceName"
class="sw-btn ghost svc-events"
type="button"
:title="t('View events for {name}', { name: selectedName })"
@@ -794,7 +808,7 @@ const serviceKpis = computed<HeaderKpi[]>(() => {
<!-- Loading state for the menu fetch — appears in the login →
layer-URL redirect window where the menu is still in flight
and we can't yet tell whether the layer exists. -->
- <div v-if="menuStillLoading || previewLoading" class="missing">
+ <div v-if="menuStillLoading || previewLoading || accessPending" class="missing">
<div class="sw-card missing-card">
<Icon name="event" :size="18" />
<div>
@@ -824,6 +838,18 @@ const serviceKpis = computed<HeaderKpi[]>(() => {
</p>
</div>
</div>
+ <div v-else-if="layerDenied" class="sw-card missing-card">
+ <Icon name="alert" :size="18" />
+ <div>
+ <h2>{{ t('No access to this layer') }}</h2>
+ <p>
+ <i18n-t keypath="Your roles do not give you access to the {layer} layer. Ask an administrator if you need it." scope="global">
+ <template #layer><code>{{ layerKey }}</code></template>
+ </i18n-t>
+ <RouterLink to="/">{{ t('Back to Overview') }}</RouterLink>.
+ </p>
+ </div>
+ </div>
<div v-else class="sw-card missing-card">
<Icon name="alert" :size="18" />
<div>
diff --git a/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.test.ts b/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.test.ts
index b043915f..aecfeec1 100644
--- a/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.test.ts
+++ b/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.test.ts
@@ -38,8 +38,11 @@ vi.mock('@/layer/traces/useResultTracePopout', () => ({
useResultTracePopout: () => ({ openResultTrace: api.openTrace }),
}));
vi.mock('@/controls/useAutoRefreshSubscribe', () => ({ useAutoRefreshSubscribe: () => {} }));
-const authState = vi.hoisted(() => ({ verbs: null as Set<string> | null }));
-vi.mock('@/state/auth', () => ({ useAuthStore: () => ({ hasVerb: (verb: string) => (authState.verbs ? authState.verbs.has(verb) : true) }) }));
+const authState = vi.hoisted(() => ({ verbs: null as Set<string> | null, layerLimited: new Set<string>() }));
+vi.mock('@/state/auth', () => ({ useAuthStore: () => {
+ const hasVerb = (verb: string) => (authState.verbs ? authState.verbs.has(verb) : true);
+ return { hasVerb, hasVerbOnSomeLayer: hasVerb, layerLimited: (verb: string) => authState.layerLimited.has(verb) };
+} }));
let wrapper: VueWrapper;
let router: Router;
@@ -60,6 +63,7 @@ beforeEach(() => {
});
afterEach(() => {
authState.verbs = null;
+ authState.layerLimited = new Set();
wrapper?.unmount();
client?.clear();
document.body.innerHTML = '';
diff --git a/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.vue b/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.vue
index 04ce4073..b73f69a8 100644
--- a/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.vue
+++ b/apps/ui/src/layer/evaluation-record/LayerEvaluationRecordView.vue
@@ -29,6 +29,7 @@ import { useRoute, useRouter } from 'vue-router';
import { useQuery } from '@tanstack/vue-query';
import { useI18n } from 'vue-i18n';
import { bffClient } from '@/api/client';
+import { errorText } from '@/api/permissionDenied';
import {
type GenAIEvaluationRecordStreamRow,
useLayerEvaluationRecord,
@@ -81,7 +82,7 @@ const callerServicesLoading = computed(() => callerServicesQuery.isLoading.value
// it is reported where the prompt would otherwise ask for a provider that
// cannot be picked.
const catalogFailure = computed<string | null>(() => {
- if (callerServicesQuery.error.value) return String(callerServicesQuery.error.value);
+ if (callerServicesQuery.error.value) return errorText(callerServicesQuery.error.value);
const answer = callerServicesQuery.data.value;
return answer && answer.reachable === false ? (answer.error || t('Backend unreachable.')) : null;
});
@@ -790,7 +791,7 @@ watch([drillArmed, providerReady], ([armed, ready]) => {
</label>
<!-- Reading a trace needs traces:read, as the row links do; the
address can still be typed without it. -->
- <label v-if="auth.hasVerb('traces:read')" class="cf cf-action">
+ <label v-if="auth.hasVerbOnSomeLayer('traces:read')" class="cf cf-action">
<span> </span>
<button class="sw-btn small cf-pick-span" type="button" @click="openSpanPicker">{{ t('Pick span…') }}</button>
</label>
diff --git a/apps/ui/src/layer/logs/useLayerLogs.ts b/apps/ui/src/layer/logs/useLayerLogs.ts
index b1743be4..559989b6 100644
--- a/apps/ui/src/layer/logs/useLayerLogs.ts
+++ b/apps/ui/src/layer/logs/useLayerLogs.ts
@@ -18,6 +18,7 @@
import { computed, type Ref } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import { bffClient } from '@/api/client';
+import { errorText } from '@/api/permissionDenied';
import { serviceRefFields, type ServiceRef } from '@/utils/serviceRef';
import type { LogFacetsResponse, LogsResponse, LogTagFilter } from '@/api/client';
@@ -96,7 +97,7 @@ export function useLayerLogs(layerKey: Ref<string>, params: LogListParams) {
// failure replays as a failure instead of an innocent "no logs" empty state.
const reachable = computed<boolean>(() => data.value?.reachable ?? true);
const error = computed<string | null>(() => {
- if (!replay.value && q.error.value) return String(q.error.value);
+ if (!replay.value && q.error.value) return errorText(q.error.value);
return data.value && !data.value.reachable ? (data.value.error ?? null) : null;
});
return {
diff --git a/apps/ui/src/layer/serviceScope.test.ts b/apps/ui/src/layer/serviceScope.test.ts
index 7e2046f2..8705be1d 100644
--- a/apps/ui/src/layer/serviceScope.test.ts
+++ b/apps/ui/src/layer/serviceScope.test.ts
@@ -39,6 +39,7 @@ import { resolveLayerServiceName, tabServiceScope } from './useLayerServiceName'
import LayerTracesView from './traces/LayerTracesView.vue';
import LayerLogsView from './logs/LayerLogsView.vue';
import LayerBrowserErrorsView from './browser-errors/LayerBrowserErrorsView.vue';
+import { useAuthStore } from '@/state/auth';
const SERVICE_ID = 'bWVzaC1zdnI6OnNvbmdz.1';
const SERVICE_NAME = 'songs';
@@ -295,6 +296,9 @@ async function fireRunQuery(w: VueWrapper, selector: string): Promise<void> {
beforeEach(async () => {
pinia = createPinia();
setActivePinia(pinia);
+ // Signed in with every permission: the tab reads its landing rows, as it
+ // does for any session that holds metrics:read on the layer.
+ useAuthStore().user = { username: 'op', roles: ['admin'], verbs: ['*'] };
router = createRouter({
history: createMemoryHistory(),
routes: [{ path: '/:pathMatch(.*)*', component: { template: '<div />' } }],
diff --git a/apps/ui/src/layer/traceql/useTraceQL.ts b/apps/ui/src/layer/traceql/useTraceQL.ts
index 6333935f..c5aaa9bd 100644
--- a/apps/ui/src/layer/traceql/useTraceQL.ts
+++ b/apps/ui/src/layer/traceql/useTraceQL.ts
@@ -35,6 +35,7 @@ import type {
} from '@skywalking-horizon-ui/api-client';
import { traceOutcome } from '@skywalking-horizon-ui/api-client';
import { bffClient } from '@/api/client';
+import { errorText } from '@/api/permissionDenied';
import { usePreviewLayerBlock } from '@/controls/previewConfig';
/** Adapt a TraceQL row onto the shared list/scatter row — a presentation
@@ -122,7 +123,7 @@ export function useTraceQLSearch(input: TraceQLSearchInput) {
// Reading only the payload's own flag turned a failed fetch into an empty
// list, which reads as "no traces matched" — the wrong conclusion.
reachable: computed(() => (q.error.value ? false : (q.data.value?.reachable ?? true))),
- error: computed(() => q.data.value?.error ?? (q.error.value ? String(q.error.value) : null)),
+ error: computed(() => q.data.value?.error ?? (q.error.value ? errorText(q.error.value) : null)),
/** True once a run has produced an answer of any kind. */
answered: computed(() => q.data.value !== undefined || q.error.value != null),
isFetching: q.isFetching,
diff --git a/apps/ui/src/layer/traces/LayerTracesView.vue b/apps/ui/src/layer/traces/LayerTracesView.vue
index 79d0aa8a..90af955a 100644
--- a/apps/ui/src/layer/traces/LayerTracesView.vue
+++ b/apps/ui/src/layer/traces/LayerTracesView.vue
@@ -67,6 +67,7 @@ import {
SLOW_RECORD_RANGE_HOURS,
} from '@/utils/recordTimeRange';
import { useSetupStore } from '@/state/setup';
+import { permissionDeniedText } from '@/api/permissionDenied';
import { useColdStageStore } from '@/controls/coldStage';
import TraceListPanel from '@/render/widgets/TraceListPanel.vue';
import TagInput from '@/components/primitives/TagInput.vue';
@@ -313,7 +314,7 @@ watch([serviceKey], () => {
// lookup by trace id, which reads no service.
const queryEnabled = computed(() => hasQueried.value && (cTraceIdFilter.value !== null || serviceReady.value));
-const { native, isFetching, refetch } = useLayerTraces(layerKey, {
+const { native, isFetching, refetch, error: listError } = useLayerTraces(layerKey, {
source: NATIVE_SOURCE,
service: cService,
instanceId: cInstanceId,
@@ -343,6 +344,7 @@ const { native, isFetching, refetch } = useLayerTraces(layerKey, {
const isSegmentList = computed(() => native.value?.api === 'queryBasicTraces');
const traceApiLabel = computed(() => (native.value?.api === 'queryTraces' ? 'v2' : 'v1'));
const showApiBanner = computed(() => hasQueried.value && !!native.value?.reachable);
+const listRefusal = computed(() => (hasQueried.value ? permissionDeniedText(listError.value) : null));
// Declared ahead of runQuery, which resets them: the drill watch below runs
// during setup and can reach runQuery before the rest of this script has run.
@@ -782,6 +784,7 @@ useEscapeToClose(() => selectedTraceId.value !== null, closeDetail);
<div v-else-if="isFetching && (!native || native.traces.length === 0)" class="tr-empty">
{{ t('Reading data…') }}
</div>
+ <div v-else-if="listRefusal" class="tr-empty">{{ listRefusal }}</div>
<div v-else-if="!native || (native.reachable && native.traces.length === 0)" class="tr-empty">
<template v-if="cTraceIdFilter">
{{ t('No trace found for this ID.') }}
diff --git a/apps/ui/src/layer/traces/useZipkinTraces.ts b/apps/ui/src/layer/traces/useZipkinTraces.ts
index f821fa40..11c56899 100644
--- a/apps/ui/src/layer/traces/useZipkinTraces.ts
+++ b/apps/ui/src/layer/traces/useZipkinTraces.ts
@@ -34,6 +34,7 @@ import type {
ZipkinTraceListResponse,
} from '@skywalking-horizon-ui/api-client';
import { bffClient, type ZipkinTraceQuery } from '@/api/client';
+import { errorText } from '@/api/permissionDenied';
export interface ZipkinTracesParams {
serviceName: Ref<string | null>;
@@ -117,7 +118,7 @@ export function useLayerZipkinTraces(params: ZipkinTracesParams) {
// failure replays as a failure instead of an innocent empty window.
const reachable = computed<boolean>(() => data.value?.reachable ?? true);
const error = computed<string | null>(() => {
- if (!replay.value && q.error.value) return String(q.error.value);
+ if (!replay.value && q.error.value) return errorText(q.error.value);
return data.value && !data.value.reachable ? (data.value.error ?? null) : null;
});
return {
diff --git a/apps/ui/src/layer/useLayerLanding.ts b/apps/ui/src/layer/useLayerLanding.ts
index b22058d0..578a934a 100644
--- a/apps/ui/src/layer/useLayerLanding.ts
+++ b/apps/ui/src/layer/useLayerLanding.ts
@@ -19,9 +19,12 @@ import { computed, type Ref } from 'vue';
import { useQuery } from '@tanstack/vue-query';
import type { LandingConfig, LandingResponse, LayerDef } from '@skywalking-horizon-ui/api-client';
import { bffClient } from '@/api/client';
+import { errorText } from '@/api/permissionDenied';
import { fetchDrawable, GraphUnavailableError, useTimeIdentity } from '@/layer/graphQuery';
import { useAutoRefreshSubscribe } from '@/controls/useAutoRefreshSubscribe';
import { useRefreshErrorReport } from '@/controls/errorCenter';
+import { useAuthStore } from '@/state/auth';
+import { useLayerServices } from '@/layer/useLayerServices';
/**
* Live top-N service rollup for one Overview landing card. Polls every
@@ -90,7 +93,33 @@ export function useLayerLanding(
// 2. The manual refresh button in LayerShell — `q.refetch()`.
// No silent vue-query-driven refetch under the operator, so the
// service list never moves on its own between operator actions.
- const isEnabled = computed(() => !(replay?.value ?? false));
+ // The rows are metric reads. A role that opens this layer's other pages
+ // without `metrics:read` on it still picks a service on them, so the roster —
+ // which answers any layer-page permission — stands in, unmeasured. A role
+ // whose metrics grant reaches only some of the groups its page grants do
+ // gets the roster's other services added to the sample the pickers read.
+ const auth = useAuthStore();
+ const operate = computed(() => layer.value.visibility === 'operate');
+ const readsMetrics = computed(() => auth.hasVerbOnLayer('metrics:read', layerKey.value, operate.value));
+ const partialMetrics = computed(() => readsMetrics.value && auth.layerLimited('metrics:read'));
+ const roster = useLayerServices(layerKey, {
+ rideTicker: false,
+ replay: computed(() => (replay?.value ?? false) || (readsMetrics.value && !partialMetrics.value)),
+ });
+ const unmeasured = (s: { id: string; name: string; group?: string | null }) => ({
+ serviceId: s.id,
+ serviceName: s.name,
+ group: s.group ?? undefined,
+ metrics: {},
+ });
+ const beyondMetrics = computed(() => {
+ if (!partialMetrics.value) return [];
+ const base = layerKey.value.split('~', 1)[0];
+ return roster.services.value
+ .filter((s) => !auth.hasVerbOnLayer('metrics:read', `${base}~${s.group ?? ''}`, operate.value))
+ .map(unmeasured);
+ });
+ const isEnabled = computed(() => !(replay?.value ?? false) && readsMetrics.value);
const q = useQuery({
queryKey: ['layer-landing', layerKey, cfgHash, rangeKey],
// Wrapped for the same reason the graphs are: the route answers HTTP 200
@@ -126,8 +155,12 @@ export function useLayerLanding(
// `data` is the last roster worth showing — an unreadable answer never
// becomes it, so a failed read leaves the previous services on screen.
- const data = computed<LandingResponse | null>(() => q.data.value ?? null);
- const rows = computed(() => data.value?.rows ?? []);
+ const data = computed<LandingResponse | null>(() => {
+ const d = q.data.value ?? null;
+ if (!d || beyondMetrics.value.length === 0) return d;
+ return { ...d, sampledRows: [...(d.sampledRows ?? d.rows), ...beyondMetrics.value] };
+ });
+ const rows = computed(() => (readsMetrics.value ? (data.value?.rows ?? []) : roster.services.value.map(unmeasured)));
/**
* Reachable describes the LATEST ATTEMPT, not the rows above.
*
@@ -139,18 +172,29 @@ export function useLayerLanding(
const failed = computed(() =>
q.error.value instanceof GraphUnavailableError ? (q.error.value.response as LandingResponse) : null,
);
- const reachable = computed(() => (failed.value ? false : (data.value?.reachable ?? false)));
- const error = computed(
- () => failed.value?.error ?? data.value?.error ?? (q.error.value ? String(q.error.value) : undefined),
+ const reachable = computed(() => {
+ if (!readsMetrics.value) return !roster.isError.value;
+ return failed.value ? false : (data.value?.reachable ?? false);
+ });
+ const error = computed(() => {
+ if (!readsMetrics.value) return roster.error.value ? errorText(roster.error.value) : undefined;
+ return failed.value?.error ?? data.value?.error ?? (q.error.value ? errorText(q.error.value) : undefined);
+ });
+ /** An answer is in hand, or the read failed: nothing more is coming. */
+ const settled = computed(() =>
+ readsMetrics.value ? data.value !== null || q.error.value !== null : roster.data.value !== null || roster.isError.value,
);
return {
- isLoading: q.isLoading,
- isFetching: q.isFetching,
+ isLoading: computed(() => (readsMetrics.value ? q.isLoading.value : roster.isLoading.value)),
+ isFetching: computed(() => (readsMetrics.value ? q.isFetching.value : roster.isFetching.value)),
data,
rows,
reachable,
error,
- refetch: q.refetch,
+ settled,
+ // Refresh whichever list the page is showing: a role without metrics:read
+ // here would otherwise refire the refused metrics read.
+ refetch: () => (readsMetrics.value ? q.refetch() : roster.refetch()),
};
}
diff --git a/apps/ui/src/layer/useLayerServiceName.ts b/apps/ui/src/layer/useLayerServiceName.ts
index 3f4f624f..6774b0f3 100644
--- a/apps/ui/src/layer/useLayerServiceName.ts
+++ b/apps/ui/src/layer/useLayerServiceName.ts
@@ -148,7 +148,7 @@ export function useLayerServiceName(
resolveLayerServiceName({
selectedId: selectedId.value,
landingRows: landing.data.value?.sampledRows ?? landing.rows.value ?? [],
- landingSettled: landing.data.value !== null || Boolean(landing.error.value),
+ landingSettled: landing.settled.value,
roster: roster.value,
rosterSettled: rosterData.value !== null || rosterFailed.value,
}),
diff --git a/apps/ui/src/layer/useLayerServices.ts b/apps/ui/src/layer/useLayerServices.ts
index cbf1d461..10c1f7aa 100644
--- a/apps/ui/src/layer/useLayerServices.ts
+++ b/apps/ui/src/layer/useLayerServices.ts
@@ -104,5 +104,7 @@ export function useLayerServices(
/** The roster read failed. A caller resolving an id against it treats this
* as settled-with-nothing: there is no further answer coming. */
isError: q.isError,
+ error: q.error,
+ refetch: q.refetch,
};
}
diff --git a/apps/ui/src/render/layer-dashboard/LayerDashboardsView.vue b/apps/ui/src/render/layer-dashboard/LayerDashboardsView.vue
index cff9ea36..ea37621a 100644
--- a/apps/ui/src/render/layer-dashboard/LayerDashboardsView.vue
+++ b/apps/ui/src/render/layer-dashboard/LayerDashboardsView.vue
@@ -554,7 +554,7 @@ function evaluationRecordDrillEnabled(w: DashboardWidget): boolean {
return (
layerKey.value.toUpperCase() === 'VIRTUAL_GENAI' &&
layer.value?.caps?.evaluationRecord === true &&
- auth.hasVerb('logs:read') &&
+ auth.hasVerbOnLayer('logs:read', layerKey.value) &&
scope.value === 'instance' &&
w.type === 'line' &&
w.id === 'evaluation score' &&
diff --git a/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.test.ts b/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.test.ts
index 56a1fa7a..fd1cce95 100644
--- a/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.test.ts
+++ b/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.test.ts
@@ -21,7 +21,7 @@ import { createPinia } from 'pinia';
import { i18n } from '@/i18n';
import EvaluationRecordDetailPopout from './EvaluationRecordDetailPopout.vue';
-vi.mock('@/state/auth', () => ({ useAuthStore: () => ({ hasVerb: () => true }) }));
+vi.mock('@/state/auth', () => ({ useAuthStore: () => ({ hasVerb: () => true, hasVerbOnSomeLayer: () => true }) }));
function row(valueType: string, content: string) {
return {
diff --git a/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.vue b/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.vue
index 99f69703..f51d0e3d 100644
--- a/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.vue
+++ b/apps/ui/src/render/widgets/EvaluationRecordDetailPopout.vue
@@ -138,7 +138,7 @@ function onJumpTrace(): void {
</div>
<div class="ld-ctrls">
<button class="sw-btn small" :class="{ 'is-copied': copied }" type="button" @click="copyContent">{{ copied ? t('Copied') : t('Copy') }}</button>
- <button v-if="row.traceId && auth.hasVerb('traces:read')" class="sw-btn small" type="button" @click="onJumpTrace">↗ {{ t('trace') }}</button>
+ <button v-if="row.traceId && auth.hasVerbOnSomeLayer('traces:read')" class="sw-btn small" type="button" @click="onJumpTrace">↗ {{ t('trace') }}</button>
</div>
</div>
<div class="ld-meta">
diff --git a/apps/ui/src/render/widgets/EvaluationRecordStreamPanel.vue b/apps/ui/src/render/widgets/EvaluationRecordStreamPanel.vue
index a647d441..b7f5ca86 100644
--- a/apps/ui/src/render/widgets/EvaluationRecordStreamPanel.vue
+++ b/apps/ui/src/render/widgets/EvaluationRecordStreamPanel.vue
@@ -104,7 +104,7 @@ function keyOf(r: GenAIEvaluationRecordStreamRow, idx: number): string {
<span class="lg-task mono dim" :title="r.taskName ?? '-'">{{ r.taskName ?? '-' }}</span>
<span class="lg-lvl" :style="{ color: LEVEL_COLOR[levelOf(r)] }">{{ levelOf(r) }}</span>
<span
- v-if="r.traceId && auth.hasVerb('traces:read')"
+ v-if="r.traceId && auth.hasVerbOnSomeLayer('traces:read')"
class="lg-trace mono"
@click.stop="emit('jump-trace', { traceId: r.traceId, traceType: r.traceType, traceSegmentId: r.traceSegmentId, traceSpanIndex: r.traceSpanIndex, traceSpanId: r.traceSpanId, ts: r.timestamp })"
>trace</span>
diff --git a/apps/ui/src/shell/AppSidebar.vue b/apps/ui/src/shell/AppSidebar.vue
index bb8243f0..5ff469b9 100644
--- a/apps/ui/src/shell/AppSidebar.vue
+++ b/apps/ui/src/shell/AppSidebar.vue
@@ -150,7 +150,7 @@ function isLayerDiverged(key: string): boolean {
</RouterLink>
</template>
<RouterLink
- v-if="auth.hasVerb('alarms:read')"
+ v-if="auth.hasVerbOnSomeLayer('alarms:read')"
to="/alarms"
class="sw-nav-item"
:class="{ 'is-active': isActive('/alarms') }"
@@ -235,10 +235,10 @@ function isLayerDiverged(key: string): boolean {
<!-- Platform monitoring — OAP self-observability under one header:
backend diagnostics (cluster status, data retention, runtime
config) on top, then the per-layer so11y_* agent dashboards.
- Maintainer tier: diagnostics rows are verb-gated individually;
- the layer dashboards gate on `cluster:read` (granted to
- maintainer / operator / admin, not viewer). -->
- <template v-if="platformSection || (operateLayers.length > 0 && auth.hasVerb('cluster:read'))">
+ Diagnostics rows are verb-gated individually. The menu already
+ carries only the operate layers the caller may open — `cluster:read`
+ with a plain read verb, or an explicit `verb@LAYER` grant. -->
+ <template v-if="platformSection || operateLayers.length > 0">
<div class="sw-nav-section sw-nav-section--icon">
<Icon :name="sectionIcon('Platform monitoring')" />
<span>{{ t('Platform monitoring') }}</span>
@@ -254,7 +254,7 @@ function isLayerDiverged(key: string): boolean {
<Icon :name="row.icon" /><span>{{ row.label }}</span>
</RouterLink>
</template>
- <template v-if="operateLayers.length > 0 && auth.hasVerb('cluster:read')">
+ <template v-if="operateLayers.length > 0">
<template v-for="L in operateLayers" :key="`op:${L.key}`">
<SidebarLayerRow
:layer="L"
diff --git a/apps/ui/src/shell/SidebarLayerChildren.vue b/apps/ui/src/shell/SidebarLayerChildren.vue
index 094cf500..9af04d11 100644
--- a/apps/ui/src/shell/SidebarLayerChildren.vue
+++ b/apps/ui/src/shell/SidebarLayerChildren.vue
@@ -42,6 +42,7 @@ const { route, isActive, isActiveExact } = useRouteActive();
const auth = useAuthStore();
const L = computed(() => props.layer);
+const canReadLogs = computed(() => auth.hasVerbOnLayer('logs:read', L.value.key, L.value.visibility === 'operate'));
function labelFor(path: string): string {
const slots = L.value.slots;
@@ -74,7 +75,9 @@ function labelFor(path: string): string {
}
const rows = computed(() =>
- layerMenuRows(L.value).filter((r) => r.path !== 'evaluation-record' || auth.hasVerb('logs:read')).map((r) => ({
+ layerMenuRows(L.value)
+ .filter((r) => r.path !== 'evaluation-record' || canReadLogs.value)
+ .map((r) => ({
...r,
to: `/layer/${L.value.key}/${r.path}`,
// The page's own name when it has one; otherwise the component's
diff --git a/apps/ui/src/shell/router/index.ts b/apps/ui/src/shell/router/index.ts
index 03872c84..253fa7b9 100644
--- a/apps/ui/src/shell/router/index.ts
+++ b/apps/ui/src/shell/router/index.ts
@@ -437,7 +437,10 @@ router.beforeEach(async (to) => {
// OAP chip (where the page's data comes from shared `auth` endpoints
// the BFF can't gate per-page).
const requiredVerb = to.meta.verb as string | undefined;
- if (requiredVerb && auth.isAuthenticated && !auth.hasVerb(requiredVerb)) {
+ // A layer sub-page asks on its own layer, so a `verb@LAYER` grant opens it.
+ const layerKey = typeof to.params.layerKey === 'string' ? to.params.layerKey : null;
+ const allowed = !requiredVerb || (layerKey ? auth.hasVerbOnLayer(requiredVerb, layerKey) : auth.hasVerb(requiredVerb));
+ if (auth.isAuthenticated && !allowed) {
return { path: '/' };
}
});
diff --git a/apps/ui/src/shell/useLayers.ts b/apps/ui/src/shell/useLayers.ts
index 901f4de2..c2e65176 100644
--- a/apps/ui/src/shell/useLayers.ts
+++ b/apps/ui/src/shell/useLayers.ts
@@ -117,6 +117,7 @@ export function useLayers() {
const availableLayers = computed<LayerDef[]>(() =>
layers.value.filter((L) => L.serviceCount > 0),
);
+ const alarmLayers = computed(() => q.data.value?.alarmLayers ?? null);
const oapReachable = computed<boolean>(() => q.data.value?.oap.reachable ?? false);
const oapError = computed<string | undefined>(() => q.data.value?.oap.error);
@@ -140,6 +141,7 @@ export function useLayers() {
layers,
activeLayers,
availableLayers,
+ alarmLayers,
oapReachable,
oapError,
findLayer,
diff --git a/apps/ui/src/state/auth.test.ts b/apps/ui/src/state/auth.test.ts
index da2e706f..49e615c2 100644
--- a/apps/ui/src/state/auth.test.ts
+++ b/apps/ui/src/state/auth.test.ts
@@ -106,10 +106,10 @@ describe('auth store — no cached data survives an identity change', () => {
/**
* The same table `apps/bff/src/rbac/verbs.test.ts` asserts, run through the
- * UI's copy of the matcher. Three copies of it exist — this store, the Roles
- * board, and the BFF — and they diverged together once: a malformed grant
- * (`rule:*:typo`) read as the area wildcard on all three, so the sidebar
- * offered pages the server would have allowed too. Pin them to one answer.
+ * UI's copy of the matcher (`verbGrammar.ts`, which the Roles board shares).
+ * The copies diverged together once: a malformed grant (`rule:*:typo`) read as
+ * the area wildcard on every side, so the sidebar offered pages the server
+ * would have allowed too. Pin them to one answer.
*/
const MATCHER_CASES: ReadonlyArray<[string, string, boolean]> = [
['rule:*:typo', 'rule:delete', false],
@@ -140,3 +140,92 @@ describe('the auth store answers the verb grammar exactly as the BFF does', () =
expect(auth.hasVerb(required)).toBe(expected);
});
});
+
+/**
+ * `verb@LAYER[groups]` grants, answered as the BFF's `SessionAccess` answers
+ * them (`apps/bff/src/rbac/layer-grants.test.ts`). A session with none must
+ * see exactly what it saw before layer grants existed.
+ */
+describe('the auth store answers layer-qualified grants as the BFF does', () => {
+ beforeEach(() => setActivePinia(createPinia()));
+
+ function signIn(verbs: string[], verbCap?: string[]) {
+ const auth = useAuthStore();
+ auth.user = { username: 'u', roles: ['r'], verbs, ...(verbCap ? { verbCap } : {}) };
+ return auth;
+ }
+
+ it('never lets a layer grant answer a plain question', () => {
+ for (const g of ['metrics:read@GENERAL', '*:read@GENERAL', '*@GENERAL', 'metrics:*@GENERAL']) {
+ const auth = signIn([g]);
+ expect(auth.hasVerb('metrics:read'), g).toBe(false);
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL'), g).toBe(true);
+ expect(auth.hasVerbOnSomeLayer('metrics:read'), g).toBe(true);
+ expect(auth.layerLimited('metrics:read'), g).toBe(true);
+ expect(auth.hasVerb('overview:read'), g).toBe(false);
+ }
+ });
+
+ it('reaches exactly the named layer, with case and OAP aliases folded', () => {
+ const auth = signIn(['traces:read@general', 'logs:read@DATABASE']);
+ expect(auth.hasVerbOnLayer('traces:read', 'GENERAL')).toBe(true);
+ expect(auth.hasVerbOnLayer('traces:read', 'general')).toBe(true);
+ expect(auth.hasVerbOnLayer('traces:read', 'MESH')).toBe(false);
+ expect(auth.hasVerbOnLayer('logs:read', 'VIRTUAL_DATABASE')).toBe(true);
+ expect(auth.hasVerbOnLayer('logs:read', 'virtual_database')).toBe(true);
+ });
+
+ it('reads a split sidebar entry by its layer and its group', () => {
+ const auth = signIn(['metrics:read@GENERAL[payments]', 'logs:read@GENERAL[-]', 'traces:read@GENERAL']);
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL~payments')).toBe(true);
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL~risk')).toBe(false);
+ expect(auth.hasVerbOnLayer('metrics:read', 'MESH~payments')).toBe(false);
+ // `[-]` is the ungrouped services, whose entry key ends in a bare `~`.
+ expect(auth.hasVerbOnLayer('logs:read', 'GENERAL~')).toBe(true);
+ expect(auth.hasVerbOnLayer('logs:read', 'GENERAL~payments')).toBe(false);
+ expect(auth.hasVerbOnLayer('traces:read', 'GENERAL~risk')).toBe(true);
+ // On the whole layer, the group limit is the BFF's to apply.
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL')).toBe(true);
+ });
+
+ it('keeps a plain grant off the operate layers without cluster:read', () => {
+ expect(signIn(['metrics:read']).hasVerbOnLayer('metrics:read', 'BANYANDB', true)).toBe(false);
+ expect(signIn(['metrics:read', 'cluster:read']).hasVerbOnLayer('metrics:read', 'BANYANDB', true)).toBe(true);
+ expect(signIn(['metrics:read@BANYANDB']).hasVerbOnLayer('metrics:read', 'BANYANDB', true)).toBe(true);
+ });
+
+ it('grants nothing through a malformed qualifier, admin, or a verb with no layer', () => {
+ for (const g of ['metrics:read@', 'metrics:read@GENERAL[]', 'metrics:read@GENERAL[a,,b]', 'admin@GENERAL']) {
+ const auth = signIn([g]);
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL'), g).toBe(false);
+ expect(auth.layerLimited('metrics:read'), g).toBe(false);
+ }
+ const auth = signIn(['cluster:read@GENERAL', '*@GENERAL']);
+ expect(auth.hasVerbOnLayer('cluster:read', 'GENERAL')).toBe(false);
+ expect(auth.hasVerbOnSomeLayer('audit:read')).toBe(false);
+ });
+
+ it('decides layer-limited per verb', () => {
+ const auth = signIn(['alarms:read', 'metrics:read@GENERAL']);
+ expect(auth.layerLimited('metrics:read')).toBe(true);
+ expect(auth.layerLimited('alarms:read')).toBe(false);
+ expect(auth.layerLimited('traces:read')).toBe(false);
+ });
+
+ it('answers every layer question plainly for a session with no layer grant', () => {
+ const auth = signIn(['*:read']);
+ for (const v of ['metrics:read', 'traces:read', 'logs:read', 'events:read']) {
+ expect(auth.hasVerbOnLayer(v, 'GENERAL')).toBe(auth.hasVerb(v));
+ expect(auth.hasVerbOnSomeLayer(v)).toBe(auth.hasVerb(v));
+ expect(auth.layerLimited(v)).toBe(false);
+ }
+ });
+
+ it('narrows by the OAuth scope cap, by verb and never by layer', () => {
+ const auth = signIn(['metrics:*@GENERAL', 'profile:enable', 'rule:write'], ['*:read']);
+ expect(auth.hasVerbOnLayer('metrics:read', 'GENERAL')).toBe(true);
+ expect(auth.hasVerbOnLayer('profile:enable', 'GENERAL')).toBe(false);
+ expect(auth.hasVerb('profile:enable')).toBe(false);
+ expect(auth.hasVerb('rule:write')).toBe(false);
+ });
+});
diff --git a/apps/ui/src/state/auth.ts b/apps/ui/src/state/auth.ts
index 1371a25f..e49166d9 100644
--- a/apps/ui/src/state/auth.ts
+++ b/apps/ui/src/state/auth.ts
@@ -21,7 +21,7 @@ import { BffApiError, bffClient, type MeResponse } from '@/api/client';
import { useTemplatePreference } from '@/controls/templatePreference';
import { resetSessionState } from '@/state/sessionReset';
import { i18n } from '@/i18n';
-import { WILDCARD_EXEMPT_VERBS } from './wildcardExempt';
+import { canonicalLayerKey, hasPlainVerb, layerGrantCovers, parseLayerGrant, type LayerGrant } from './verbGrammar';
export const useAuthStore = defineStore('auth', () => {
const user = ref<MeResponse | null>(null);
@@ -96,28 +96,64 @@ export const useAuthStore = defineStore('auth', () => {
resetSessionState();
}
- // Mirrors the BFF's matchOne (apps/bff/src/rbac/verbs.ts) exactly. This UI gate
- // is advisory — the BFF enforces — but it must agree, or it hides custom `admin`
- // grants and shows three-segment controls (e.g. rule:write:structural) that a
- // two-segment grant like `*:write` does not actually carry and the BFF denies.
+ // The BFF's `SessionAccess`, advisory here — the BFF enforces, but this gate
+ // must agree with it, or it hides controls the server allows and shows ones
+ // it denies. An OAuth credential's `verbCap` narrows by verb, never by layer.
+ function capAllows(verb: string): boolean {
+ const cap = user.value?.verbCap;
+ return cap ? hasPlainVerb(cap, verb) : true;
+ }
+
+ /** The plain question: a grant written with `@` never answers it. */
function hasVerb(verb: string): boolean {
- const grants = user.value?.verbs ?? [];
- for (const g of grants) {
- if (g === '*' || g === 'admin' || g === verb) return true;
- // Same placement as the BFF: after the exact/`*`/`admin` grants and
- // BEFORE both wildcard branches, so `*:read` and `audit:*` are equally
- // denied.
- if (WILDCARD_EXEMPT_VERBS.has(verb)) continue;
- // Both as the BFF: a fourth segment is malformed rather than truncated,
- // and `area:*` carries no sub-segment.
- if (g.split(':').length > 3) continue;
- const [ga, gact, gsub] = g.split(':', 3);
- const [ra, ract, rsub] = verb.split(':', 3);
- if (ga === ra && gact === '*' && gsub === undefined) return true;
- if (ga === '*' && gact === ract && (gsub ?? '') === (rsub ?? '')) return true;
- if (ga === ra && gact === ract && (gsub ?? '') === (rsub ?? '')) return true;
+ return capAllows(verb) && hasPlainVerb(user.value?.verbs ?? [], verb);
+ }
+
+ function layerGrantsFor(verb: string): LayerGrant[] {
+ if (!capAllows(verb)) return [];
+ const out: LayerGrant[] = [];
+ for (const g of user.value?.verbs ?? []) {
+ const parsed = g.includes('@') ? parseLayerGrant(g) : null;
+ if (parsed && layerGrantCovers(parsed, verb)) out.push(parsed);
}
- return false;
+ return out;
+ }
+
+ /**
+ * May the session use `verb` on this layer's pages? A plain grant reaches
+ * every layer except an operate one (Platform monitoring), which also needs
+ * `cluster:read`; a `verb@LAYER` grant reaches exactly its layer. `layerKey`
+ * may be a sidebar entry's `<layer>~<group>` key, and then the grant must
+ * also reach that group. On a whole layer, group limits are left to the BFF,
+ * which drops the roster rows they exclude.
+ */
+ function hasVerbOnLayer(verb: string, layerKey: string, operate = false): boolean {
+ if (hasVerb(verb) && (!operate || hasVerb('cluster:read'))) return true;
+ const cut = layerKey.indexOf('~');
+ const key = canonicalLayerKey(cut < 0 ? layerKey : layerKey.slice(0, cut));
+ const group = cut < 0 ? undefined : layerKey.slice(cut + 1);
+ return layerGrantsFor(verb).some(
+ (g) => canonicalLayerKey(g.layer) === key && (group === undefined || !g.groups || g.groups.includes(group)),
+ );
+ }
+
+ /** Held plainly or on at least one layer — for a read whose layer is only
+ * known to the BFF (a trace opened by id). */
+ function hasVerbOnSomeLayer(verb: string): boolean {
+ return hasVerb(verb) || layerGrantsFor(verb).length > 0;
+ }
+
+ /** The layers a layer-limited verb reaches; null when it is held plainly,
+ * which reaches them all. */
+ function layersFor(verb: string): string[] | null {
+ if (hasVerb(verb)) return null;
+ return [...new Set(layerGrantsFor(verb).map((g) => canonicalLayerKey(g.layer)))];
+ }
+
+ /** Held only through layer grants: the BFF refuses such a caller any read
+ * that names no service, so pickers must not offer "all services". */
+ function layerLimited(verb: string): boolean {
+ return !hasVerb(verb) && layerGrantsFor(verb).length > 0;
}
return {
@@ -130,5 +166,9 @@ export const useAuthStore = defineStore('auth', () => {
logout,
endSession,
hasVerb,
+ hasVerbOnLayer,
+ hasVerbOnSomeLayer,
+ layerLimited,
+ layersFor,
};
});
diff --git a/apps/ui/src/state/verbGrammar.test.ts b/apps/ui/src/state/verbGrammar.test.ts
new file mode 100644
index 00000000..fabc5009
--- /dev/null
+++ b/apps/ui/src/state/verbGrammar.test.ts
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Drift gate for the UI's copy of the layer-grant grammar. A copy that falls
+ * behind the BFF shows a layer tab the server refuses, or hides one it allows.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { LAYER_ALIAS, LAYER_SCOPED_VERBS, canonicalLayerKey, layerGrantCovers, parseLayerGrant } from './verbGrammar';
+
+// Vitest runs with `--root src/`, so this resolves from the process cwd (apps/ui).
+const BFF = resolve(process.cwd(), '../bff/src');
+
+describe('the layer-grant grammar', () => {
+ it('names the same layer-scoped verbs as the BFF', () => {
+ const src = readFileSync(resolve(BFF, 'rbac/verbs.ts'), 'utf8');
+ const block = /LAYER_SCOPED_VERBS[^=]*=\s*new Set<Verb>\(\[([^\]]*)\]\)/.exec(src);
+ expect(block, 'could not find LAYER_SCOPED_VERBS in the BFF — did it move?').not.toBeNull();
+ const bff = [...(block?.[1] ?? '').matchAll(/'([^']+)'/g)].map((m) => m[1]).sort();
+ expect([...LAYER_SCOPED_VERBS].sort()).toEqual(bff);
+ });
+
+ it('folds the same OAP layer aliases as the BFF', () => {
+ const src = readFileSync(resolve(BFF, 'logic/templates/identity.ts'), 'utf8');
+ const block = /const LAYER_ALIAS[^=]*=\s*\{([^}]*)\}/.exec(src);
+ expect(block, 'could not find LAYER_ALIAS in the BFF — did it move?').not.toBeNull();
+ const bff = Object.fromEntries([...(block?.[1] ?? '').matchAll(/(\w+):\s*'([^']+)'/g)].map((m) => [m[1], m[2]]));
+ expect({ ...LAYER_ALIAS }).toEqual(bff);
+ expect(canonicalLayerKey('database')).toBe('VIRTUAL_DATABASE');
+ expect(canonicalLayerKey('general')).toBe('GENERAL');
+ });
+
+ it('parses a layer and its groups, `-` being the ungrouped services', () => {
+ expect(parseLayerGrant('metrics:read@general')).toEqual({ verb: 'metrics:read', layer: 'GENERAL' });
+ expect(parseLayerGrant('metrics:read@GENERAL[payments, risk]')).toEqual({
+ verb: 'metrics:read',
+ layer: 'GENERAL',
+ groups: ['payments', 'risk'],
+ });
+ expect(parseLayerGrant('logs:read@GENERAL[-]')?.groups).toEqual(['']);
+ expect(parseLayerGrant('metrics:read')).toBeNull();
+ });
+
+ it('refuses a malformed qualifier rather than widening it', () => {
+ for (const bad of ['metrics:read@', '@GENERAL', 'metrics:read@GENERAL[]', 'metrics:read@GENERAL[a,,b]', 'metrics:read@GENERAL[a]x']) {
+ expect(parseLayerGrant(bad), bad).toBeNull();
+ }
+ });
+
+ it('covers only per-service reads, and nothing through admin', () => {
+ const cover = (g: string, v: string) => {
+ const parsed = parseLayerGrant(g);
+ return parsed !== null && layerGrantCovers(parsed, v);
+ };
+ expect(cover('*@GENERAL', 'traces:read')).toBe(true);
+ expect(cover('*:read@GENERAL', 'logs:read')).toBe(true);
+ expect(cover('*@GENERAL', 'audit:read')).toBe(false);
+ expect(cover('*:read@GENERAL', 'cluster:read')).toBe(false);
+ expect(cover('cluster:read@GENERAL', 'cluster:read')).toBe(false);
+ expect(cover('admin@GENERAL', 'metrics:read')).toBe(false);
+ });
+});
diff --git a/apps/ui/src/state/verbGrammar.ts b/apps/ui/src/state/verbGrammar.ts
new file mode 100644
index 00000000..f5f12f00
--- /dev/null
+++ b/apps/ui/src/state/verbGrammar.ts
@@ -0,0 +1,118 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * The UI's copy of the BFF's verb grammar (`apps/bff/src/rbac/verbs.ts`, plus
+ * the layer-key fold from `logic/templates/identity.ts`). The BFF is the source
+ * of truth and the only side that enforces. The auth store's gate and the Roles
+ * board both answer through this module, so they cannot disagree with each
+ * other; `verbGrammar.test.ts` fails if the lists here drift from the BFF's.
+ */
+
+import { WILDCARD_EXEMPT_VERBS } from './wildcardExempt';
+
+/**
+ * Does one PLAIN grant cover `required`? A layer-limited grant never answers a
+ * question that has no layer in it: `metrics:read@GENERAL` must not open the
+ * overview or the 3D map.
+ */
+export function matchOne(grant: string, required: string): boolean {
+ if (grant.includes('@')) return false;
+ if (grant === '*' || grant === 'admin' || grant === required) return true;
+ // After the exact / `*` / `admin` grants and BEFORE both wildcard branches,
+ // so `*:read` and `audit:*` are equally denied.
+ if (WILDCARD_EXEMPT_VERBS.has(required)) return false;
+ // A fourth segment is malformed rather than truncated, and `area:*` carries
+ // no sub-segment.
+ if (grant.split(':').length > 3) return false;
+ const [ga, gact, gsub] = grant.split(':', 3);
+ const [ra, ract, rsub] = required.split(':', 3);
+ if (ga === ra && gact === '*' && gsub === undefined) return true;
+ if (ga === '*' && gact === ract && (gsub ?? '') === (rsub ?? '')) return true;
+ return ga === ra && gact === ract && (gsub ?? '') === (rsub ?? '');
+}
+
+export function hasPlainVerb(grants: readonly string[], required: string): boolean {
+ return grants.some((g) => matchOne(g, required));
+}
+
+/** The verbs a layer qualifier means something on. Any other verb written with
+ * `@` grants nothing. */
+export const LAYER_SCOPED_VERBS: ReadonlySet<string> = new Set([
+ 'metrics:read',
+ 'traces:read',
+ 'logs:read',
+ 'browser-errors:read',
+ 'ai-conversation:read',
+ 'events:read',
+ 'alarms:read',
+ 'topology:read',
+ 'profile:read',
+ 'profile:enable',
+]);
+
+/** How a grant spells "the services with no OAP group". */
+export const UNGROUPED_GRANT = '-';
+
+export interface LayerGrant {
+ verb: string;
+ /** Upper-cased as written; compare through {@link canonicalLayerKey}. */
+ layer: string;
+ /** Absent = the whole layer. `''` is the ungrouped services. */
+ groups?: readonly string[];
+}
+
+const QUALIFIER = /^([A-Za-z0-9_]+)(?:\[([^\]]*)\])?$/;
+
+/**
+ * Split `<verb>@<LAYER>[group,…]`. `null` for a plain grant AND for a malformed
+ * qualifier (`metrics:read@`, `@GENERAL[]`, `@GENERAL[a,,b]`), which grants
+ * nothing — a typo must not confer the whole layer.
+ */
+export function parseLayerGrant(grant: string): LayerGrant | null {
+ const at = grant.indexOf('@');
+ if (at < 0) return null;
+ const verb = grant.slice(0, at);
+ const m = QUALIFIER.exec(grant.slice(at + 1));
+ if (!verb || !m) return null;
+ const layer = m[1].toUpperCase();
+ if (m[2] === undefined) return { verb, layer };
+ const groups = m[2].split(',').map((g) => g.trim());
+ if (groups.some((g) => g === '')) return null;
+ return { verb, layer, groups: groups.map((g) => (g === UNGROUPED_GRANT ? '' : g)) };
+}
+
+/** Does a layer grant's VERB part cover `required`? `*@X` covers every
+ * layer-scoped verb on X; `admin@X` covers nothing, since the sentinel means
+ * everything and everything has no layer. */
+export function layerGrantCovers(grant: LayerGrant, required: string): boolean {
+ if (grant.verb === 'admin' || !LAYER_SCOPED_VERBS.has(required)) return false;
+ return grant.verb === '*' || matchOne(grant.verb, required);
+}
+
+/** Legacy layer enum values OAP keeps; a grant may name either spelling. */
+export const LAYER_ALIAS: Readonly<Record<string, string>> = {
+ CACHE: 'VIRTUAL_CACHE',
+ DATABASE: 'VIRTUAL_DATABASE',
+ MQ: 'VIRTUAL_MQ',
+ GENAI: 'VIRTUAL_GENAI',
+};
+
+export function canonicalLayerKey(key: string): string {
+ const upper = key.toUpperCase();
+ return LAYER_ALIAS[upper] ?? upper;
+}
diff --git a/apps/ui/src/state/wildcardExempt.ts b/apps/ui/src/state/wildcardExempt.ts
index 00258145..61880e42 100644
--- a/apps/ui/src/state/wildcardExempt.ts
+++ b/apps/ui/src/state/wildcardExempt.ts
@@ -20,12 +20,12 @@
* `WILDCARD_EXEMPT_VERBS` (`apps/bff/src/rbac/verbs.ts`), which is the source
* of truth and the only side that enforces.
*
- * There are two verb matchers on this side (the auth store's gate and the
- * Roles board's) and they must both consult this, or the two surfaces
- * contradict the server in opposite directions: the sidebar offers a page that
- * 403s, and the Roles board draws a check mark for a grant the BFF denies —
- * on the same row whose hint says a wildcard does not include it. That board
- * is what an administrator plans access around.
+ * The UI's matcher (`verbGrammar.ts`, which both the auth store's gate and the
+ * Roles board answer through) consults this. Without it the two surfaces
+ * contradict the server: the sidebar offers a page that 403s, and the Roles
+ * board draws a check mark for a grant the BFF denies — on the same row whose
+ * hint says a wildcard does not include it. That board is what an
+ * administrator plans access around.
*
* `wildcardExemptVerbs.test.ts` fails if this drifts from the BFF's set.
*/
diff --git a/docs/access-control/rbac.md b/docs/access-control/rbac.md
index 1c847fb9..ae411d51 100644
--- a/docs/access-control/rbac.md
+++ b/docs/access-control/rbac.md
@@ -67,7 +67,7 @@ None of these is granted to `viewer` or `maintainer`. Those roles read the dashb
| Verb | Gates |
|---|---|
-| `cluster:read` | Cluster Status page (`/operate/cluster`). |
+| `cluster:read` | Cluster Status page (`/operate/cluster`), and the **Platform monitoring layers** — the OAP, BanyanDB, agent and Satellite self-observability dashboards, and any other layer whose template sets `visibility: operate`. A role that reads layer data (`metrics:read`, `traces:read`, …) without `cluster:read` does not see those layers and cannot read their services, by page, by URL or through the AI assistant, and their services' rows are left out of the all-services Logs and [...]
| `ttl:read` | Data Retention page (`/operate/ttl`). |
| `config:read` | OAP Configuration page (`/operate/config`). |
@@ -108,6 +108,51 @@ A user's grant string is matched against a required verb using these rules:
Effective verbs for a session are the **union** of all grants from all roles.
+## Limiting a verb to layers and service groups
+
+A data verb can carry the layer it applies to, and optionally one or more of the layer's OAP service groups:
+
+```
+<verb>@<LAYER> # every service of the layer
+<verb>@<LAYER>[<group1>, <group2>, …] # only the services of these groups
+```
+
+The role then reads those services only, and the sidebar shows that layer only:
+
+| Grant | Reaches |
+|---|---|
+| `metrics:read@GENERAL` | Every service of the GENERAL layer. |
+| `metrics:read@GENERAL[payments]` | The GENERAL services whose OAP service group is `payments` — the `payments::` prefix of the service name. |
+| `metrics:read@GENERAL[payments,risk]` | Both groups. |
+| `metrics:read@GENERAL[-]` | The GENERAL services that have no group. |
+| `"*:read@GENERAL[payments]"` | Every read that can carry a layer, on those services. Quote a grant that starts with `*`. |
+| `metrics:read` (no `@`) | What it has always meant: every layer, except the Platform monitoring layers, which also need `cluster:read`. |
+
+Layer keys are the ones the sidebar and the layer templates use (`GENERAL`, `K8S_SERVICE`, `VIRTUAL_DATABASE`, …), in any case. A group is OAP's own service group, so a layer that is [split by service group](../customization/layer-templates.md) shows one sidebar entry per group, and each entry can be granted to a different role.
+
+Only verbs whose data belongs to a service can carry a layer: `metrics:read`, `traces:read`, `logs:read`, `browser-errors:read`, `ai-conversation:read`, `events:read`, `alarms:read`, `topology:read`, `profile:read` and `profile:enable`. Any other verb written with `@` grants nothing, and Horizon names it in a startup warning.
+
+**What the role sees.** The sidebar lists the layers, and the group entries, that the role's layer grants reach — each with all of its pages, as for any role; a page whose data the role cannot read answers with a refusal. The Zipkin and TraceQL pages have no per-service control of their own and follow the layer's visibility. Every request is checked on its own: a page, an API call, and every read the AI assistant or an MCP agent makes on the role's behalf must name a service the grant co [...]
+
+**What the role still sees of other services.** Links between services are navigation, not access: the page a link opens is checked like any other. The views that draw relationships still show what OAP returns for the role's own service — the topology map shows its neighbours in other layers or groups with their names and headline metrics, the hierarchy view names the same workload's services in other layers, and an instance map or a network-profiling edge between two services opens when [...]
+
+**Traces cross layers.** A trace follows a request through services of any layer, so Horizon does not narrow traces by layer. A role with `traces:read` on a layer reads that layer's trace tabs — the SkyWalking trace list for the service picked on the page, and the Zipkin and TraceQL stores the layer lists — and opens any trace by its id, every span included.
+
+**Alarms.** With `alarms:read` limited to layers, the Alarms page lists the granted layers; pick one and a service in it, and the page shows that service's alarms. The alarm count in the top bar and the page's all-services view need `alarms:read` without a layer.
+
+**Evaluation records.** They belong to a call from an application service to a GenAI provider and are read on the VIRTUAL_GENAI layer, so the role needs that layer granted: add `logs:read@VIRTUAL_GENAI`. With it, a record is readable when the role reads either the provider or the calling service.
+
+**What needs the verb without a layer.** A query that would read every service cannot be narrowed, so a layer-limited role cannot use it:
+
+- the SkyWalking trace list, the Logs tab and the Browser Logs tab need a service picked (there is no "all services" choice);
+- totals across a whole layer — the overview KPI tiles computed across a layer;
+- log tag autocomplete, source maps, the alarm counts and the unfiltered alarm list, and any alarm list from an OAP older than the `queryAlarms` API, which cannot filter alarms by service;
+- profiling results looked up by segment or schedule id, and keeping a network-profiling task alive.
+
+**Combining roles.** Grants from all of a user's roles are pooled, and a verb without a layer in ANY role lifts the limit for that verb: a user who also holds the built-in `viewer` role reads every layer. An OAuth scope narrows by verb and keeps the layer: `horizon:read` over `metrics:*@GENERAL` leaves `metrics:read@GENERAL`.
+
+A role with no `@` grant is unaffected by any of this: it sees the menu and the data it always has.
+
## Built-in roles
Default definitions (used when `rbac.roles` is not overridden):
@@ -178,7 +223,7 @@ When a user has multiple roles, the **first role on the user** wins. Order matte
## Enforcement
-Access is enforced server-side, not in the browser. Every protected request is checked for a valid session (an unauthenticated request is rejected with `401`) and then for the verb that request requires (a session lacking the verb is rejected with `403`). The UI hides controls a session cannot use, but a forged UI cannot bypass these checks.
+Access is enforced server-side, not in the browser. Every protected request is checked for a valid session (an unauthenticated request is rejected with `401`), then for the verb that request requires, and then — for a request that reads a layer or a service — for the layer and every service it names (a session lacking any of these is rejected with `403`). The UI hides controls a session cannot use, but a forged UI cannot bypass these checks.
Enforcement is fail-safe: a request with no explicit verb still requires a valid session, so a misconfiguration cannot accidentally expose a protected endpoint to anonymous callers.
@@ -215,6 +260,22 @@ landingByRole:
on-call: /alarms # land on the alarm board
```
+### A team that sees only its own services
+
+```yaml
+roles:
+ payments-viewer:
+ - "metrics:read@GENERAL[payments]"
+ - "traces:read@GENERAL[payments]"
+ - "logs:read@GENERAL[payments]"
+ - "topology:read@GENERAL[payments]"
+ - "alarms:read@GENERAL[payments]"
+ - "metrics:read@K8S_SERVICE" # the team's Kubernetes services, if K8S_SERVICE holds only theirs
+ - ai:read # the assistant reads what the grants above allow, no more
+```
+
+Service groups come from the service name (`payments::checkout`), so this works when every service the team runs carries the prefix. Kubernetes service names carry a namespace rather than a group; grant the whole `K8S_SERVICE` layer only when it holds the team's services alone.
+
### Lockdown for an external auditor
```yaml
diff --git a/docs/changelog/1.1.0.md b/docs/changelog/1.1.0.md
index e0422b37..b2fc1f97 100644
--- a/docs/changelog/1.1.0.md
+++ b/docs/changelog/1.1.0.md
@@ -46,6 +46,10 @@
### Features
+**A role can be limited to layers, and to service groups within a layer.** A data permission can now name the layer it applies to — `metrics:read@GENERAL`, or `metrics:read@GENERAL[payments,risk]` for the services whose OAP service group is `payments` or `risk` — so one Horizon can serve several teams that each see only their own services. The sidebar follows the grant: such a role sees the layers, and the per-group entries of a layer split by service group, that its grants reach, with s [...]
+
+**Any permission that opens a layer page can fill its pickers.** The service picker at the top of a layer, and the instance and endpoint pickers on its tabs, used to need `metrics:read` (the instance list also took `logs:read`), so a role granted only `traces:read` or `logs:read` could not pick what its own tab was about. They now open for any of the layer-page permissions — and the instance and endpoint pickers also for `alarms:read`, since the Alarms page narrows by them — and list onl [...]
+
**A custom role can now be added without restating the built-in ones.** Naming `rbac.roles` has always replaced the block outright, so adding one role meant copying `viewer`, `maintainer`, `operator` and `admin` into your config and keeping those copies current forever. Set `builtinRoles: keep` and the built-ins become the base instead: a role name you list overrides that one role, a new name is added, and everything you did not mention stays as it shipped — `landingByRole` merges the sa [...]
**The Dashboard setup pages open read-only when you may look but not publish.** Each page — Overview templates, Layer dashboards, Translations, Alert page, 3D Infra Map, Global defaults — is reached with its own read permission and published with its own write permission. Granting the read half alone shows the page in the sidebar and opens it with the whole configuration visible, every editing control disabled, and a banner naming the permission publishing needs; granting the write half [...]
@@ -54,6 +58,12 @@
### Fixes
+**The Platform monitoring layers are now closed to a role without `cluster:read`.** The OAP, BanyanDB, agent and Satellite self-observability layers have always been listed in the sidebar only for `cluster:read`, and the Roles page lists them under it, but the layers' dashboards, instances and metrics answered any role with `metrics:read`: by opening the layer's address directly, by naming one of their services under another layer's address, or through a self-aggregating column on any la [...]
+
+**A draft template preview now needs `layer-template:write`.** The topology, deployment, instance map, API dependency, process relation and trace routes evaluated a draft template sent with the request for any role that could read the page — the preview is the layer dashboard editor's, and now takes the editor's permission, as the TraceQL preview already did.
+
+**A layer-wide total is computed only from an expression a stored overview declares.** The self-aggregating columns of a layer's service list, which read a metric across every service with no service in the query, evaluated whatever expression the request carried. They now run only the expressions the stored overview templates, or the layer's own header, declare; anything else is left out of the answer.
+
**A malformed permission no longer grants more than it says.** A grant is at most three segments, but a longer one used to be silently truncated to its first three — so `rule:*:typo` was read as `rule:*` and handed over every rule permission, and `rule:write:structural:extra` matched `rule:write:structural`. Anything outside the documented forms now matches nothing and is named in the startup warning alongside other unrecognised grants.
**The BanyanDB audit configuration is only what a deployment actually differs on** — where the server is, how to authenticate to it, a namespace prefix, and how long to keep records. The groups' layout is bundled rather than exposed: one shard, which a sign-in rate never outgrows. That is also the safe default, because BanyanDB fixes a group's shard count at creation and does not move data when it changes — a shard count edited after records exist would route new ones away from the old o [...]
@@ -134,10 +144,12 @@ The **3D Infra Map** opens framed on the tiers that hold services. A deployment
**A template published elsewhere reaches an open browser on its own.** Horizon re-reads the template store on a slow cycle of its own, so a dashboard pushed from another Horizon, from `swctl`, or from anything else writing the same OAP store appears within about a minute — without anyone reloading the page.
-**Every MQE field in the layer template editor can now be run where you type it.** A run button beside each expression opens a panel that picks a service (and, where the metric needs one, an instance, endpoint or process), picks a time range with the same precision-tabbed picker the top of the page uses (custom ranges included), fires the expression against your OAP and shows exactly what came back — a graph of the series it returned, aligned on one time axis with a legend per label, the [...]
+**Every MQE field in the layer template editor can now be run where you type it.** A run button beside each expression opens a panel that picks a service (and, where the metric needs one, an instance, endpoint or process), picks a time range with the same precision-tabbed picker the top of the page uses (custom ranges included), fires the expression against your OAP and shows exactly what came back — a graph of the series it returned, aligned on one time axis with a legend per label, the [...]
### Fixes
+**A layer whose stored template names its entity terms under `aliases` opens again.** A layer template pushed to OAP with `aliases` (the documented spelling) and no `slots` left the sidebar entry without entity names, and opening that layer showed a blank page; the entry now takes the names from `aliases`.
+
**A template store that could not be read emptied every dashboard, overview and map.** They are rendered from the last successful read now, so a brief outage of OAP's admin port leaves the console up, with the banner saying how stale it is. Horizon still never substitutes the templates bundled in the release — showing shipped defaults in place of your own configuration would misrepresent what is on screen — so a Horizon that has never read the store still blocks those pages rather than i [...]
**The unreachable banner never cleared once the store came back.** Nothing re-read the store's status after the page had loaded, so the warning stayed up — and the pages behind it stayed blocked — however healthy OAP had become. Both recover on their own now.
diff --git a/docs/customization/layer-templates.md b/docs/customization/layer-templates.md
index 85bcbc9d..28a7be5d 100644
--- a/docs/customization/layer-templates.md
+++ b/docs/customization/layer-templates.md
@@ -45,7 +45,7 @@ Every field is optional except `key`. Defaults are baked in for the rest.
|---|---|---|---|
| `key` | string (UPPER_SNAKE) | **required** | Matches the OAP layer enum. The filename is the lowercased key. |
| `alias` | string | OAP-reported name | Display name in the sidebar and page headers. |
-| `splitByServiceGroup` | boolean | `false` | Split this layer into one sidebar entry per OAP service group (the `<group>::` prefix), each scoped to that group. Off keeps a single combined entry. Toggled in the admin right after **Alias**. |
+| `splitByServiceGroup` | boolean | `false` | Split this layer into one sidebar entry per OAP service group (the `<group>::` prefix), each scoped to that group. Off keeps a single combined entry. Toggled in the admin right after **Alias**. Splitting only arranges the sidebar; to limit who reads a group, grant it — see [Limiting a verb to layers and service groups](../access-control/rbac.md#limiting-a-verb-to-layers-and-service-groups). |
| `group` | string | — | Sidebar grouping label. Layers sharing a `group` collapse together. |
| `visibility` | `public` \| `operate` | `public` | Section placement. `operate` puts the layer under the Operate group. |
| `color` | string | `var(--sw-accent)` | Hex or CSS variable for the layer's accent. |
diff --git a/docs/setup/rbac.md b/docs/setup/rbac.md
index 4ed3469d..40424d6b 100644
--- a/docs/setup/rbac.md
+++ b/docs/setup/rbac.md
@@ -42,6 +42,8 @@ rbac:
`rbac.roles` is an open map — the four built-ins have no special status, and you can define as many roles as you like beside them.
+A data verb can be limited to one layer, and to service groups in it — `metrics:read@GENERAL[payments]` — so a team reads only its own services and its sidebar lists only its own layers. A grant without `@` means what it always has. See [Limiting a verb to layers and service groups](../access-control/rbac.md#limiting-a-verb-to-layers-and-service-groups).
+
By default, **naming `roles` replaces the block entirely**: the roles that exist are exactly the ones you listed, and a user whose every role has disappeared holds no verbs and is refused everywhere. Set `builtinRoles: keep` to treat the built-ins as a base instead — then a name you list overrides that one role wholesale, a new name is appended, and everything you did not mention stays as it shipped.
A common addition is a **read-only template viewer** — someone who inspects how the dashboards are configured, and reviews translations, without being able to publish anything. Grant the read half of each Dashboard-setup pair and none of the write half:
diff --git a/packages/api-client/src/menu.ts b/packages/api-client/src/menu.ts
index 2b99c719..c80cd9f3 100644
--- a/packages/api-client/src/menu.ts
+++ b/packages/api-client/src/menu.ts
@@ -273,6 +273,10 @@ export interface LogConfig {
export interface MenuResponse {
layers: LayerDef[];
+ /** Only for a session with layer grants, whose sidebar follows its page
+ * permissions: the layers whose alarms it reads, for the Alarms page's
+ * layer filter. Absent, that filter offers the sidebar's layers. */
+ alarmLayers?: Array<{ key: string; name: string }>;
generatedAt: number;
/** Best-effort status of the upstream OAP query host. */
oap: { reachable: boolean; queryUrl: string; error?: string };