From c50020e420b204112f8a8f8204f912e938307cc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=92=D0=B8=D1=82=D0=B0=D0=BB=D0=B8=D0=B9=20=D0=A7=D0=B5?= =?UTF-8?q?=D1=84=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Fri, 25 Sep 2026 01:03:50 +0300 Subject: [PATCH] v0.10.0: each viewer sees what their own RBAC allows Until now anyone admitted through Dex saw every namespace and every log, read with the module's service account. auth.visibility: ViewerRBAC (the default) asks the API server as the viewer, with the token the DexAuthenticator forwards: list pods in all namespaces means the whole cluster; otherwise the namespaces where they can list pods. Logs also need get pods/log, node cards list nodes, cluster-wide alerts are for cluster-wide viewers. Traffic to a hidden namespace keeps its counts with the peer shown as hidden. One minute cache per token hash, SSARs in parallel (8), a cluster-wide viewer costs two. Verified against the live cluster with two real tokens: a service account with view in one namespace got that namespace only (0 nodes, 403 on another namespace's YAML and logs, 403 on node usage); the module's own account, cluster-wide, got all 56 namespaces and 6 nodes; no token, 401. auth.visibility: Everything keeps the old behaviour. The DexAuthenticator now forwards the token when either actions or ViewerRBAC need it (templates/_helpers.tpl). Co-Authored-By: Claude Opus 5.5 --- Chart.yaml | 2 +- README.md | 7 +- changelog.yaml | 3 + docs/README.md | 10 +- docs/README_RU.md | 10 +- .../cluster-map/src/cmd/cluster-map/main.go | 4 +- .../cluster-map/src/internal/access/access.go | 184 ++++++++++++++++++ .../src/internal/access/access_test.go | 76 ++++++++ .../cluster-map/src/internal/config/config.go | 12 ++ .../src/internal/server/actions.go | 15 ++ .../src/internal/server/inspect.go | 26 ++- .../cluster-map/src/internal/server/server.go | 113 ++++++++++- .../src/internal/server/visibility_test.go | 104 ++++++++++ .../src/internal/topology/filter.go | 50 +++++ .../src/internal/topology/filter_test.go | 54 +++++ .../src/internal/traffic/collector.go | 59 ++++++ .../src/internal/traffic/collector_test.go | 27 +++ images/cluster-map/src/web/static/app.js | 6 + images/cluster-map/src/web/static/i18n.js | 8 + openapi/config-values.yaml | 13 +- openapi/doc-ru-config-values.yaml | 10 +- templates/_helpers.tpl | 6 + templates/deployment.yaml | 2 + templates/dex-authenticator.yaml | 11 +- templates/httproute.yaml | 2 +- templates/ingress.yaml | 2 +- tests/values/default.yaml | 1 + 27 files changed, 791 insertions(+), 26 deletions(-) create mode 100644 images/cluster-map/src/internal/access/access.go create mode 100644 images/cluster-map/src/internal/access/access_test.go create mode 100644 images/cluster-map/src/internal/server/visibility_test.go create mode 100644 images/cluster-map/src/internal/topology/filter.go create mode 100644 images/cluster-map/src/internal/topology/filter_test.go create mode 100644 templates/_helpers.tpl diff --git a/Chart.yaml b/Chart.yaml index a8e1a45..25d9198 100644 --- a/Chart.yaml +++ b/Chart.yaml @@ -1,5 +1,5 @@ name: cluster-map -version: 0.9.0 +version: 0.10.0 dependencies: - name: deckhouse_lib_helm version: 1.72.24 diff --git a/README.md b/README.md index 08b4dbe..b681c57 100644 --- a/README.md +++ b/README.md @@ -28,13 +28,14 @@ The module follows [deckhouse/modules-template](https://github.com/deckhouse/mod | `internal/topology` | the graph: workloads, Services, Ingresses, nodes, the pod-owner rules shared with traffic, and the problems attached to cards | | `internal/traffic` | Hubble follow stream, per-minute buckets of distinct connections | | `internal/actions` | restart, scale, run, suspend, delete pod, cordon — as the viewer | +| `internal/access` | what each viewer may see: SelfSubjectAccessReviews as the viewer, cached per token | | `internal/server` | HTTP API, CSP headers, request metrics | | `internal/metrics` | Prometheus metrics | | `web/` | the frontend, embedded into the binary: plain JS, Cytoscape.js, elkjs, English and Russian | API: `/api/graph` (with problems), `/api/flows?namespaces=a,b&window=`, `/api/resource?kind=&namespace=&name=`, `/api/pods?id=&namespace=`, `/api/logs?namespace=&pod=&container=`, `/api/events?id=`, `/api/usage?id=`, `/api/me`, `/api/permissions?kind=&namespace=&name=`, `POST /api/action`, `/healthz`, `/readyz`; metrics on `:9090/metrics`. -`/api/me`, `/api/permissions` and `/api/action` use the viewer's bearer token from the `Authorization` header (the DexAuthenticator adds it when `actions.enabled`), never the module's service account. +`/api/me`, `/api/permissions` and `/api/action` use the viewer's bearer token from the `Authorization` header (the DexAuthenticator adds it when `actions.enabled` or `auth.visibility: ViewerRBAC`), never the module's service account. With `ViewerRBAC` every read endpoint also filters by the viewer's scope and answers 401 without a token. To run the binary on a workstation, point `KUBECONFIG` at a kubeconfig; without it the in-cluster service account is used. @@ -54,8 +55,8 @@ Base images come from the `base_images.yml` Deckhouse publishes for its own modu ```shell docker login git.project-chimera.ru -make publish VERSION=v0.8.0 # build, push bundle and release, register, channel alpha -make release VERSION=v0.8.0 CHANNEL=stable +make publish VERSION=v0.10.0 # build, push bundle and release, register, channel alpha +make release VERSION=v0.10.0 CHANNEL=stable ``` The registry layout matches [deckhouse/modules-actions](https://github.com/deckhouse/modules-actions): diff --git a/changelog.yaml b/changelog.yaml index 1aef669..1ea846b 100644 --- a/changelog.yaml +++ b/changelog.yaml @@ -1,3 +1,6 @@ +v0.10.0: + features: + - "Per-user visibility (auth.visibility: ViewerRBAC, the default): each viewer sees the namespaces where their own RBAC lets them list pods, or the whole cluster if they can list pods everywhere. Logs also need get pods/log, node cards list nodes; traffic peers in hidden namespaces are shown as hidden. Checked with SelfSubjectAccessReviews as the viewer, cached for a minute. auth.visibility: Everything keeps the previous behaviour." v0.9.0: features: - "Vulnerabilities from operator-trivy: a red shield with the number of CRITICAL CVEs on each card, and in the details every CRITICAL and HIGH CVE with its packages, installed and fixed versions and a link. A CVE counts once per card." diff --git a/docs/README.md b/docs/README.md index a159b6d..fd9d556 100644 --- a/docs/README.md +++ b/docs/README.md @@ -83,7 +83,13 @@ History is kept in memory: after a pod restart the windows fill again. The statu The web interface reads the cluster through the module's own service account (`d8:cluster-map` ClusterRole): `get`, `list`, `watch` on namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses, Deckhouse `clusteralerts` and operator-trivy `vulnerabilityreports`, `get` and `list` on `metrics.k8s.io` pods and nodes, and `get` on `pods/log`. It never reads Secrets or ConfigMaps and has no write verbs. Changes go through [actions](#actions), which use the viewer's own identity. -This means **anyone admitted to the web interface sees every namespace and can read container logs**, whatever their own RBAC permissions are; what they can change is limited by their own RBAC. Restrict access with `auth.allowedUserGroups` (and optionally `auth.allowedUserEmails` and `auth.whitelistSourceRanges`). +**What a viewer sees follows the viewer's own RBAC** (`auth.visibility: ViewerRBAC`, the default). With every request the DexAuthenticator passes the user's token; the module asks the API server with that token (`SelfSubjectAccessReview`) and caches the answer for a minute: + +- `list pods` in all namespaces — the whole cluster; +- otherwise only the namespaces where the user can `list pods`; cards, YAML, events, load and vulnerabilities of other namespaces are not returned, and a traffic peer there is shown as a hidden peer, with its connections but without its name; +- container logs additionally need `get pods/log` in that namespace, node cards and the node view `list nodes`; cluster-wide alerts are shown to cluster-wide viewers only. + +With `auth.visibility: Everything`, anyone admitted to the web interface sees every namespace and can read container logs, whatever their own RBAC is. In both modes restrict who is admitted with `auth.allowedUserGroups` (and optionally `auth.allowedUserEmails` and `auth.whitelistSourceRanges`); what a user can change always follows their own RBAC. The frontend is served with a strict Content Security Policy: only its own scripts, styles and API, no inline code, no framing. @@ -99,6 +105,6 @@ The pod exposes Prometheus metrics on port `9090` (`cluster_map_*`: Hubble strea ## Limitations - One replica: traffic history lives in the process. A second replica would keep its own history and double the load on hubble-relay. -- Reading is all-or-nothing, as described in [Security](#security). Showing each user only what their RBAC allows to read is planned; actions already follow the user's RBAC. +- Visibility is by namespace: a user who can list pods in a namespace sees all its cards, including the manifests of its Deployments and Services, even if their role would not let them read those objects one by one. - Alerts need the `prometheus` module, which creates `ClusterAlert` objects. Without it the map shows problems from object state and events only. - Traffic is L3/L4. HTTP-level details (paths, status codes) need Cilium L7 visibility and are not shown yet. diff --git a/docs/README_RU.md b/docs/README_RU.md index c20a32e..b7ca731 100644 --- a/docs/README_RU.md +++ b/docs/README_RU.md @@ -83,7 +83,13 @@ Workload'ы под нестандартными контроллерами то Веб-интерфейс читает кластер через собственную учётку модуля (ClusterRole `d8:cluster-map`): `get`, `list`, `watch` на namespaces, pods, services, nodes, events, deployments, statefulsets, daemonsets, cronjobs, ingresses, `clusteralerts` Deckhouse и `vulnerabilityreports` operator-trivy, `get` и `list` на pods и nodes из `metrics.k8s.io` и `get` на `pods/log`. Secret и ConfigMap он не читает, прав на запись нет. Изменения идут через [действия](#действия), которые выполняются от имени пользователя. -Отсюда следует: **любой, кого пустили в веб-интерфейс, видит все namespace и может читать логи контейнеров** — независимо от собственных прав RBAC; изменить он может только то, что разрешает его RBAC. Ограничивайте доступ через `auth.allowedUserGroups` (а также `auth.allowedUserEmails` и `auth.whitelistSourceRanges`). +**Что видит пользователь, определяет его собственный RBAC** (`auth.visibility: ViewerRBAC`, по умолчанию). С каждым запросом DexAuthenticator передаёт токен пользователя; модуль спрашивает API-сервер от его имени (`SelfSubjectAccessReview`) и кеширует ответ на минуту: + +- `list pods` во всех namespace — виден весь кластер; +- иначе — только namespace, где пользователь может `list pods`; карточки, YAML, события, нагрузка и уязвимости остальных namespace не отдаются, а сосед по трафику оттуда показывается скрытым — с соединениями, но без имени; +- для логов контейнеров нужно ещё `get pods/log` в этом namespace, для карточек нод и вида по нодам — `list nodes`; общекластерные алерты видны только пользователям с доступом ко всему кластеру. + +При `auth.visibility: Everything` любой, кого пустили в веб-интерфейс, видит все namespace и может читать логи контейнеров независимо от своего RBAC. В обоих режимах ограничивайте круг допущенных через `auth.allowedUserGroups` (а также `auth.allowedUserEmails` и `auth.whitelistSourceRanges`); изменить пользователь всегда может только то, что разрешает его RBAC. Фронтенд отдаётся со строгой Content Security Policy: только собственные скрипты, стили и API, без inline-кода, без встраивания во фреймы. @@ -99,6 +105,6 @@ Workload'ы под нестандартными контроллерами то ## Ограничения - Одна реплика: история трафика живёт в процессе. Вторая реплика держала бы свою историю и удвоила бы нагрузку на hubble-relay. -- Чтение по принципу «всё или ничего», см. раздел [Безопасность](#безопасность). Показ каждому пользователю только того, что его RBAC разрешает читать, — в планах; действия уже следуют RBAC пользователя. +- Видимость — по namespace: пользователь, который может смотреть поды в namespace, видит все его карточки, включая манифесты Deployment и Service, даже если его роль не дала бы прочитать эти объекты по отдельности. - Для алертов нужен модуль `prometheus`, он создаёт объекты `ClusterAlert`. Без него карта показывает проблемы только по состоянию объектов и событиям. - Трафик на уровне L3/L4. Подробности HTTP (пути, коды ответа) требуют L7-видимости Cilium и пока не показываются. diff --git a/images/cluster-map/src/cmd/cluster-map/main.go b/images/cluster-map/src/cmd/cluster-map/main.go index 5468888..451bd01 100644 --- a/images/cluster-map/src/cmd/cluster-map/main.go +++ b/images/cluster-map/src/cmd/cluster-map/main.go @@ -71,7 +71,7 @@ func run() error { return err } var asViewer actions.ClientFactory - if cfg.ActionsEnabled { + if cfg.ActionsEnabled || cfg.ViewerVisibility { asViewer = actions.NewClientFactory(restCfg) } srv := server.New(cfg, web.Static(), asViewer) @@ -85,7 +85,7 @@ func run() error { } }() } - slog.Info("listening", "api", cfg.ListenAddr, "metrics", cfg.MetricsAddr, "traffic", cfg.TrafficMode, "actions", cfg.ActionsEnabled) + slog.Info("listening", "api", cfg.ListenAddr, "metrics", cfg.MetricsAddr, "traffic", cfg.TrafficMode, "actions", cfg.ActionsEnabled, "viewerVisibility", cfg.ViewerVisibility) client, err := kubernetes.NewForConfig(restCfg) if err != nil { diff --git a/images/cluster-map/src/internal/access/access.go b/images/cluster-map/src/internal/access/access.go new file mode 100644 index 0000000..be2ddc2 --- /dev/null +++ b/images/cluster-map/src/internal/access/access.go @@ -0,0 +1,184 @@ +/* +Copyright 2026 The cluster-map Authors + +Licensed 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. +*/ + +// Package access decides what a viewer may see on the map, from the +// viewer's own RBAC. +// +// The map reads the cluster with the module's service account, which can +// read everything it shows. Without this package anyone admitted to the web +// interface would see every namespace and every log. With it, each request +// carries the viewer's token (the DexAuthenticator's Authorization header), +// and the API server answers SelfSubjectAccessReviews for that viewer: +// "list pods in all namespaces" means the whole cluster, otherwise the +// namespaces where the viewer can list pods. The answer is cached per token +// for a minute, so a page load costs one round of reviews, not one per call. +package access + +import ( + "context" + "crypto/sha256" + "errors" + "sync" + "time" + + authzv1 "k8s.io/api/authorization/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" +) + +// Scope is what one viewer may see. +type Scope struct { + // All: the viewer can list pods in every namespace; nothing is hidden. + All bool + // Namespaces the viewer can list pods in, when not All. + Namespaces map[string]bool + // Nodes: the viewer can list nodes (node cards, node view, node usage). + Nodes bool +} + +// Everything is the scope when filtering is off. +var Everything = &Scope{All: true, Nodes: true} + +// Namespace reports whether objects in ns are visible. +func (s *Scope) Namespace(ns string) bool { + return s.All || s.Namespaces[ns] +} + +// ClientFactory returns a clientset authenticated as the viewer. +type ClientFactory func(token string) (kubernetes.Interface, error) + +// ErrNoToken is returned when the request has no viewer token. +var ErrNoToken = errors.New("no user token in the request: per-user visibility needs the DexAuthenticator to send the Authorization header") + +// Checker computes and caches scopes. +type Checker struct { + asViewer ClientFactory + namespaces func() []string // namespaces to check when the viewer is not cluster-wide + ttl time.Duration + now func() time.Time + + mu sync.Mutex + cache map[[32]byte]entry +} + +type entry struct { + scope *Scope + at time.Time +} + +const maxEntries = 512 + +// NewChecker returns a checker; namespaces lists the cluster's namespaces (from the cache). +func NewChecker(asViewer ClientFactory, namespaces func() []string) *Checker { + return &Checker{asViewer: asViewer, namespaces: namespaces, ttl: time.Minute, now: time.Now, cache: map[[32]byte]entry{}} +} + +// For returns the viewer's scope. +func (c *Checker) For(ctx context.Context, token string) (*Scope, error) { + if token == "" { + return nil, ErrNoToken + } + key := sha256.Sum256([]byte(token)) + c.mu.Lock() + if e, ok := c.cache[key]; ok && c.now().Sub(e.at) < c.ttl { + c.mu.Unlock() + return e.scope, nil + } + c.mu.Unlock() + + client, err := c.asViewer(token) + if err != nil { + return nil, err + } + scope, err := c.compute(ctx, client) + if err != nil { + return nil, err + } + c.mu.Lock() + if len(c.cache) >= maxEntries { + for k, e := range c.cache { + if c.now().Sub(e.at) >= c.ttl { + delete(c.cache, k) + } + } + if len(c.cache) >= maxEntries { + c.cache = map[[32]byte]entry{} + } + } + c.cache[key] = entry{scope, c.now()} + c.mu.Unlock() + return scope, nil +} + +func (c *Checker) compute(ctx context.Context, client kubernetes.Interface) (*Scope, error) { + all, err := Can(ctx, client, "", "pods", "", "list", "") + if err != nil { + return nil, err + } + nodes, err := Can(ctx, client, "", "nodes", "", "list", "") + if err != nil { + return nil, err + } + s := &Scope{All: all, Nodes: nodes} + if all { + return s, nil + } + s.Namespaces = map[string]bool{} + type result struct { + ns string + ok bool + err error + } + names := c.namespaces() + results := make(chan result, len(names)) + sem := make(chan struct{}, 8) + var wg sync.WaitGroup + for _, ns := range names { + wg.Add(1) + go func() { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + ok, err := Can(ctx, client, "", "pods", "", "list", ns) + results <- result{ns, ok, err} + }() + } + wg.Wait() + close(results) + for r := range results { + if r.err != nil { + return nil, r.err + } + if r.ok { + s.Namespaces[r.ns] = true + } + } + return s, nil +} + +// Can asks the API server whether the viewer behind client may perform the +// verb; namespace "" means cluster-wide (or all namespaces). +func Can(ctx context.Context, client kubernetes.Interface, group, resource, subresource, verb, namespace string) (bool, error) { + r, err := client.AuthorizationV1().SelfSubjectAccessReviews().Create(ctx, &authzv1.SelfSubjectAccessReview{ + Spec: authzv1.SelfSubjectAccessReviewSpec{ResourceAttributes: &authzv1.ResourceAttributes{ + Group: group, Resource: resource, Subresource: subresource, Verb: verb, Namespace: namespace, + }}, + }, metav1.CreateOptions{}) + if err != nil { + return false, err + } + return r.Status.Allowed, nil +} diff --git a/images/cluster-map/src/internal/access/access_test.go b/images/cluster-map/src/internal/access/access_test.go new file mode 100644 index 0000000..56886b0 --- /dev/null +++ b/images/cluster-map/src/internal/access/access_test.go @@ -0,0 +1,76 @@ +/* +Copyright 2026 The cluster-map Authors + +Licensed 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. +*/ + +package access + +import ( + "context" + "errors" + "sync/atomic" + "testing" + + authzv1 "k8s.io/api/authorization/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +// viewer may list pods in "shop" only, and not nodes. +func factory(calls *atomic.Int32, allowAll bool) ClientFactory { + return func(string) (kubernetes.Interface, error) { + c := fake.NewSimpleClientset() + c.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) { + calls.Add(1) + r := a.(k8stesting.CreateAction).GetObject().(*authzv1.SelfSubjectAccessReview) + at := r.Spec.ResourceAttributes + r.Status.Allowed = allowAll || (at.Resource == "pods" && at.Namespace == "shop") + return true, r, nil + }) + return c, nil + } +} + +func TestScopeAndCache(t *testing.T) { + var calls atomic.Int32 + c := NewChecker(factory(&calls, false), func() []string { return []string{"shop", "bank", "d8-system"} }) + s, err := c.For(context.Background(), "tok") + if err != nil { + t.Fatal(err) + } + if s.All || s.Nodes || !s.Namespace("shop") || s.Namespace("bank") { + t.Errorf("scope: %+v", s) + } + first := calls.Load() + if _, err := c.For(context.Background(), "tok"); err != nil || calls.Load() != first { + t.Errorf("second request within the TTL asked the API server again (%d -> %d)", first, calls.Load()) + } + if _, err := c.For(context.Background(), ""); !errors.Is(err, ErrNoToken) { + t.Errorf("no token: %v", err) + } +} + +func TestClusterWideViewerSkipsNamespaceChecks(t *testing.T) { + var calls atomic.Int32 + c := NewChecker(factory(&calls, true), func() []string { return []string{"a", "b", "c"} }) + s, err := c.For(context.Background(), "admin") + if err != nil || !s.All || !s.Nodes { + t.Fatalf("scope %+v, %v", s, err) + } + if calls.Load() != 2 { // pods cluster-wide and nodes + t.Errorf("cluster-wide viewer needed %d reviews, want 2", calls.Load()) + } +} diff --git a/images/cluster-map/src/internal/config/config.go b/images/cluster-map/src/internal/config/config.go index a916b36..98f238c 100644 --- a/images/cluster-map/src/internal/config/config.go +++ b/images/cluster-map/src/internal/config/config.go @@ -62,6 +62,11 @@ type Config struct { // with the viewer's own token (the Authorization header the // DexAuthenticator adds), never with the module's service account. ActionsEnabled bool + + // ViewerVisibility limits what each viewer sees to what the viewer's + // own RBAC can read (namespaces where they can list pods). Off, anyone + // admitted to the web interface sees the whole cluster. + ViewerVisibility bool } // Load reads and validates the configuration from the environment. @@ -91,6 +96,13 @@ func Load() (Config, error) { if c.ActionsEnabled, err = strconv.ParseBool(env("ACTIONS_ENABLED", "false")); err != nil { return c, fmt.Errorf("ACTIONS_ENABLED: %w", err) } + switch v := env("VISIBILITY", "ViewerRBAC"); v { + case "ViewerRBAC": + c.ViewerVisibility = true + case "Everything": + default: + return c, fmt.Errorf("VISIBILITY: %q is not one of ViewerRBAC, Everything", v) + } switch c.TrafficMode { case TrafficContinuous, TrafficOnDemand, TrafficDisabled: default: diff --git a/images/cluster-map/src/internal/server/actions.go b/images/cluster-map/src/internal/server/actions.go index 0afe5ae..f0e1ec9 100644 --- a/images/cluster-map/src/internal/server/actions.go +++ b/images/cluster-map/src/internal/server/actions.go @@ -67,12 +67,27 @@ type Me struct { ActionsEnabled bool `json:"actionsEnabled"` User string `json:"user,omitempty"` Reason string `json:"reason,omitempty"` // why actions are unavailable: disabled | noToken | rejected + // Visibility: "all" (the whole cluster), "namespaces" (Namespaces of + // them, by the viewer's RBAC) or "" when it could not be determined. + Visibility string `json:"visibility,omitempty"` + Namespaces int `json:"namespaces,omitempty"` } func (s *Server) handleMe(w http.ResponseWriter, r *http.Request) { me := Me{ActionsEnabled: s.cfg.ActionsEnabled && s.asViewer != nil} token := viewerToken(r) switch { + case s.access == nil: + me.Visibility = "all" + case token != "": + if sc, err := s.access.For(r.Context(), token); err == nil { + me.Visibility, me.Namespaces = "namespaces", len(sc.Namespaces) + if sc.All { + me.Visibility, me.Namespaces = "all", 0 + } + } + } + switch { case !me.ActionsEnabled: me.Reason = "disabled" case token == "": diff --git a/images/cluster-map/src/internal/server/inspect.go b/images/cluster-map/src/internal/server/inspect.go index d71725f..dc30291 100644 --- a/images/cluster-map/src/internal/server/inspect.go +++ b/images/cluster-map/src/internal/server/inspect.go @@ -51,6 +51,9 @@ func (s *Server) handleEvents(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") parts := strings.Split(id, "/") ctx := r.Context() + if !s.cardVisible(w, r, parts) { + return + } var list *corev1.EventList var err error match := func(corev1.ObjectReference) bool { return true } @@ -184,6 +187,9 @@ func ptr(v int64) *int64 { return &v } func (s *Server) handleUsage(w http.ResponseWriter, r *http.Request) { id := r.URL.Query().Get("id") parts := strings.Split(id, "/") + if !s.cardVisible(w, r, parts) { + return + } var pods []corev1.Pod u := Usage{Pods: []PodUsage{}} switch { @@ -324,10 +330,28 @@ func (s *Server) handleVulns(w http.ResponseWriter, r *http.Request) { http.Error(w, "id must be a workload (wl/...)", http.StatusBadRequest) return } - ns := strings.SplitN(id, "/", 3)[1] + parts := strings.Split(id, "/") + if !s.cardVisible(w, r, parts) { + return + } + ns := parts[1] pods, _ := kube.List[corev1.Pod](s.cache.Pods.Pods(ns)) writeJSON(w, map[string]any{ "available": s.cache.VulnReports != nil, "vulns": topology.VulnsFor(s.cache.VulnReportList(), pods, id, maxVulns), }) } + +// cardVisible checks a card ID (split on "/") against the viewer's scope: +// node/ needs node access, anything else its namespace. +func (s *Server) cardVisible(w http.ResponseWriter, r *http.Request, parts []string) bool { + sc, ok := s.scope(w, r) + if !ok { + return false + } + visible := len(parts) >= 2 && ((parts[0] == "node" && sc.Nodes) || (parts[0] != "node" && sc.Namespace(parts[1]))) + if !visible { + hidden(w) + } + return visible +} diff --git a/images/cluster-map/src/internal/server/server.go b/images/cluster-map/src/internal/server/server.go index e22fb33..6d607b2 100644 --- a/images/cluster-map/src/internal/server/server.go +++ b/images/cluster-map/src/internal/server/server.go @@ -37,6 +37,7 @@ import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "sigs.k8s.io/yaml" + "git.project-chimera.ru/fanchji/cluster-map/internal/access" "git.project-chimera.ru/fanchji/cluster-map/internal/actions" "git.project-chimera.ru/fanchji/cluster-map/internal/config" "git.project-chimera.ru/fanchji/cluster-map/internal/kube" @@ -52,14 +53,52 @@ type Server struct { traffic *traffic.Collector static fs.FS etags map[string]string - asViewer actions.ClientFactory // nil when actions are off + asViewer actions.ClientFactory // nil when neither actions nor viewer visibility is on + access *access.Checker // nil when everyone sees everything ready atomic.Bool } // New returns a server that answers 503 on the API until SetReady. -// asViewer builds clients from the viewer's token; nil disables actions. +// asViewer builds clients from the viewer's token; nil disables actions +// and per-viewer visibility. func New(cfg config.Config, static fs.FS, asViewer actions.ClientFactory) *Server { - return &Server{cfg: cfg, static: static, etags: etags(static), asViewer: asViewer} + s := &Server{cfg: cfg, static: static, etags: etags(static), asViewer: asViewer} + if cfg.ViewerVisibility && asViewer != nil { + s.access = access.NewChecker(access.ClientFactory(asViewer), s.namespaceNames) + } + return s +} + +func (s *Server) namespaceNames() []string { + nss, _ := kube.List[corev1.Namespace](s.cache.Namespaces) + out := make([]string, len(nss)) + for i, n := range nss { + out[i] = n.Name + } + return out +} + +// scope is what the viewer of this request may see, or it writes why +// nothing can be shown. +func (s *Server) scope(w http.ResponseWriter, r *http.Request) (*access.Scope, bool) { + if s.access == nil { + return access.Everything, true + } + sc, err := s.access.For(r.Context(), viewerToken(r)) + switch { + case err == nil: + return sc, true + case errors.Is(err, access.ErrNoToken), apierrors.IsUnauthorized(err): + http.Error(w, err.Error(), http.StatusUnauthorized) + default: + http.Error(w, "checking the viewer's permissions: "+err.Error(), http.StatusBadGateway) + } + return nil, false +} + +// hidden answers 403 for an object outside the viewer's scope. +func hidden(w http.ResponseWriter) { + http.Error(w, "not visible with your permissions", http.StatusForbidden) } // etags hashes the embedded files once: they cannot change while the @@ -175,16 +214,24 @@ func writeJSON(w http.ResponseWriter, v any) { } } -func (s *Server) handleGraph(w http.ResponseWriter, _ *http.Request) { +func (s *Server) handleGraph(w http.ResponseWriter, r *http.Request) { + sc, ok := s.scope(w, r) + if !ok { + return + } g, err := topology.Build(s.cache, s.cfg.IsSystemNamespace) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } - writeJSON(w, g) + writeJSON(w, topology.Filter(g, sc.All, sc.Nodes, sc.Namespace)) } func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) { + sc, ok := s.scope(w, r) + if !ok { + return + } if s.cfg.TrafficMode == config.TrafficDisabled { writeJSON(w, traffic.Result{Mode: config.TrafficDisabled}) return @@ -203,7 +250,16 @@ func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) { if err != nil || window <= 0 { window = 5 * time.Minute } - writeJSON(w, s.traffic.Query(namespaces, window)) + for ns := range namespaces { + if !sc.Namespace(ns) { + delete(namespaces, ns) + } + } + res := s.traffic.Query(namespaces, window) + if !sc.All { + res = traffic.Restrict(res, sc.Namespace) + } + writeJSON(w, res) } // handleResource returns the live object as YAML. It reads through the API @@ -211,6 +267,14 @@ func (s *Server) handleFlows(w http.ResponseWriter, r *http.Request) { func (s *Server) handleResource(w http.ResponseWriter, r *http.Request) { q := r.URL.Query() kind, ns, name := q.Get("kind"), q.Get("namespace"), q.Get("name") + sc, ok := s.scope(w, r) + if !ok { + return + } + if (kind == "node" && !sc.Nodes) || (kind == "namespace" && !sc.Namespace(name)) || (kind != "node" && kind != "namespace" && !sc.Namespace(ns)) { + hidden(w) + return + } ctx := r.Context() c := s.cache.Client var obj metav1.Object @@ -276,6 +340,12 @@ func (s *Server) handlePods(w http.ResponseWriter, r *http.Request) { http.Error(w, "namespace and a workload id (wl///) are required", http.StatusBadRequest) return } + if sc, ok := s.scope(w, r); !ok { + return + } else if !sc.Namespace(ns) { + hidden(w) + return + } pods, err := kube.List[corev1.Pod](s.cache.Pods.Pods(ns)) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -305,6 +375,9 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) { http.Error(w, "namespace and pod are required", http.StatusBadRequest) return } + if !s.canReadLogs(w, r, ns) { + return + } tail := s.cfg.LogTailLines opts := &corev1.PodLogOptions{TailLines: &tail, Container: container} stream, err := s.cache.Client.CoreV1().Pods(ns).GetLogs(pod, opts).Stream(r.Context()) @@ -318,3 +391,31 @@ func (s *Server) handleLogs(w http.ResponseWriter, r *http.Request) { slog.Debug("streaming logs", "err", err) } } + +// canReadLogs: logs are the most sensitive thing the map shows, so beyond +// the namespace scope the viewer must be allowed pods/log there. +func (s *Server) canReadLogs(w http.ResponseWriter, r *http.Request, ns string) bool { + sc, ok := s.scope(w, r) + if !ok { + return false + } + if !sc.Namespace(ns) { + hidden(w) + return false + } + if s.access == nil || sc.All { + return true + } + c, err := s.asViewer(viewerToken(r)) + if err == nil { + ok, err = access.Can(r.Context(), c, "", "pods", "log", "get", ns) + } + if err != nil { + http.Error(w, "checking the viewer's permissions: "+err.Error(), http.StatusBadGateway) + return false + } + if !ok { + hidden(w) + } + return ok +} diff --git a/images/cluster-map/src/internal/server/visibility_test.go b/images/cluster-map/src/internal/server/visibility_test.go new file mode 100644 index 0000000..683a5bc --- /dev/null +++ b/images/cluster-map/src/internal/server/visibility_test.go @@ -0,0 +1,104 @@ +/* +Copyright 2026 The cluster-map Authors + +Licensed 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. +*/ + +package server + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "testing/fstest" + "time" + + authzv1 "k8s.io/api/authorization/v1" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" + + "git.project-chimera.ru/fanchji/cluster-map/internal/config" + "git.project-chimera.ru/fanchji/cluster-map/internal/kube" + "git.project-chimera.ru/fanchji/cluster-map/internal/topology" + "git.project-chimera.ru/fanchji/cluster-map/internal/traffic" +) + +// The viewer "shop-dev" may list pods in shop and nothing else. +func visibilityServer(t *testing.T) http.Handler { + t.Helper() + cluster := fake.NewSimpleClientset( + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "shop"}}, + &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{Name: "bank"}}, + &corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "web", Namespace: "shop"}}, + &corev1.Service{ObjectMeta: metav1.ObjectMeta{Name: "core", Namespace: "bank"}}, + ) + ctx := t.Context() + cache, err := kube.Start(ctx, cluster, nil, 10*time.Second) + if err != nil { + t.Fatal(err) + } + factory := func(token string) (kubernetes.Interface, error) { + c := fake.NewSimpleClientset() + c.PrependReactor("create", "selfsubjectaccessreviews", func(a k8stesting.Action) (bool, runtime.Object, error) { + r := a.(k8stesting.CreateAction).GetObject().(*authzv1.SelfSubjectAccessReview) + r.Status.Allowed = token == "shop-dev" && r.Spec.ResourceAttributes.Namespace == "shop" + return true, r, nil + }) + return c, nil + } + cfg := config.Config{TrafficMode: config.TrafficDisabled, Retention: time.Hour, ViewerVisibility: true} + s := New(cfg, fstest.MapFS{"index.html": {Data: []byte("x")}}, factory) + s.SetReady(cache, traffic.NewCollector(cfg, nil, nil)) + return s.Handler() +} + +func getAs(h http.Handler, path, token string) *httptest.ResponseRecorder { + req := httptest.NewRequest(http.MethodGet, path, nil) + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + return rec +} + +func TestGraphFollowsViewerRBAC(t *testing.T) { + h := visibilityServer(t) + if code := getAs(h, "/api/graph", "").Code; code != http.StatusUnauthorized { + t.Errorf("no token: %d", code) + } + rec := getAs(h, "/api/graph", "shop-dev") + var g topology.Graph + if err := json.Unmarshal(rec.Body.Bytes(), &g); err != nil { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + for _, n := range g.Nodes { + if n.Namespace == "bank" || n.ID == "ns/bank" { + t.Errorf("bank visible to shop-dev: %s", n.ID) + } + } + if code := getAs(h, "/api/resource?kind=service&namespace=bank&name=core", "shop-dev").Code; code != http.StatusForbidden { + t.Errorf("YAML from a hidden namespace: %d", code) + } + if code := getAs(h, "/api/logs?namespace=bank&pod=core-0", "shop-dev").Code; code != http.StatusForbidden { + t.Errorf("logs from a hidden namespace: %d", code) + } + if code := getAs(h, "/api/events?id=node/a", "shop-dev").Code; code != http.StatusForbidden { + t.Errorf("node events without node access: %d", code) + } +} diff --git a/images/cluster-map/src/internal/topology/filter.go b/images/cluster-map/src/internal/topology/filter.go new file mode 100644 index 0000000..62c50d8 --- /dev/null +++ b/images/cluster-map/src/internal/topology/filter.go @@ -0,0 +1,50 @@ +/* +Copyright 2026 The cluster-map Authors + +Licensed 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. +*/ + +package topology + +// Filter returns the part of the graph a viewer may see: namespaced cards +// in visible namespaces, node cards only with node access, edges whose both +// ends stay. Cluster-wide problems (alerts about the cluster itself) are +// for cluster-wide viewers only. all short-circuits to the graph as is. +func Filter(g *Graph, all, nodes bool, namespace func(string) bool) *Graph { + if all { + return g + } + out := &Graph{Nodes: []Node{}, Edges: []Edge{}, ClusterProblems: []Problem{}, AlertsAvailable: g.AlertsAvailable, VulnsAvailable: g.VulnsAvailable} + kept := make(map[string]bool, len(g.Nodes)) + for _, n := range g.Nodes { + var ok bool + switch n.Kind { + case "node": + ok = nodes + case "namespace": + ok = namespace(n.Label) + default: + ok = namespace(n.Namespace) + } + if ok { + out.Nodes = append(out.Nodes, n) + kept[n.ID] = true + } + } + for _, e := range g.Edges { + if kept[e.Source] && kept[e.Target] { + out.Edges = append(out.Edges, e) + } + } + return out +} diff --git a/images/cluster-map/src/internal/topology/filter_test.go b/images/cluster-map/src/internal/topology/filter_test.go new file mode 100644 index 0000000..8a87464 --- /dev/null +++ b/images/cluster-map/src/internal/topology/filter_test.go @@ -0,0 +1,54 @@ +/* +Copyright 2026 The cluster-map Authors + +Licensed 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. +*/ + +package topology + +import "testing" + +func TestFilter(t *testing.T) { + g := &Graph{ + Nodes: []Node{ + {ID: "ns/shop", Kind: "namespace", Label: "shop"}, {ID: "ns/bank", Kind: "namespace", Label: "bank"}, + {ID: "wl/shop/deployment/web", Kind: "deployment", Namespace: "shop"}, {ID: "wl/bank/deployment/core", Kind: "deployment", Namespace: "bank"}, + {ID: "node/a", Kind: "node", Label: "a"}, + }, + Edges: []Edge{ + {ID: "e1", Source: "wl/shop/deployment/web", Target: "node/a"}, + {ID: "e2", Source: "wl/bank/deployment/core", Target: "node/a"}, + }, + ClusterProblems: []Problem{{Reason: "ClusterWide"}}, + } + out := Filter(g, false, true, func(ns string) bool { return ns == "shop" }) + ids := map[string]bool{} + for _, n := range out.Nodes { + ids[n.ID] = true + } + if len(ids) != 3 || !ids["ns/shop"] || !ids["wl/shop/deployment/web"] || !ids["node/a"] { + t.Errorf("nodes: %v", ids) + } + if len(out.Edges) != 1 || out.Edges[0].ID != "e1" { + t.Errorf("edges: %+v", out.Edges) + } + if len(out.ClusterProblems) != 0 { + t.Error("cluster-wide problems shown to a namespaced viewer") + } + if noNodes := Filter(g, false, false, func(ns string) bool { return ns == "shop" }); len(noNodes.Edges) != 0 { + t.Error("placement edge to a hidden node kept") + } + if Filter(g, true, true, nil) != g { + t.Error("cluster-wide viewer must get the graph as is") + } +} diff --git a/images/cluster-map/src/internal/traffic/collector.go b/images/cluster-map/src/internal/traffic/collector.go index a39f17a..f6ab293 100644 --- a/images/cluster-map/src/internal/traffic/collector.go +++ b/images/cluster-map/src/internal/traffic/collector.go @@ -467,3 +467,62 @@ func l4Info(f *flowpb.Flow) (port, tuple string, syn bool) { } return "?", "?", false } + +// Restricted stands for every peer in a namespace the viewer cannot see: +// the connection is shown, the workload behind it is not. +var Restricted = Endpoint{ID: "ext/restricted", Label: "restricted", Kind: "external"} + +// Restrict hides peers outside the visible namespaces. Edges between two +// hidden endpoints are dropped (Query already returns only edges touching +// a requested namespace, so this is defence in depth); edges to a hidden +// peer keep their counts with the peer replaced by Restricted and merged. +func Restrict(res Result, visible func(string) bool) Result { + hide := map[string]bool{} + eps := []Endpoint{} + for _, e := range res.Endpoints { + if e.Namespace != "" && !visible(e.Namespace) { + hide[e.ID] = true + continue + } + eps = append(eps, e) + } + if len(hide) == 0 { + return res + } + type key struct{ src, dst, port string } + merged := map[key]*Edge{} + var order []key + for _, e := range res.Edges { + if hide[e.Source] && hide[e.Target] { + continue + } + if hide[e.Source] { + e.Source = Restricted.ID + } + if hide[e.Target] { + e.Target = Restricted.ID + } + k := key{e.Source, e.Target, e.Port} + if m := merged[k]; m != nil { + m.Connections += e.Connections + m.New += e.New + m.Dropped += e.Dropped + m.Last = max(m.Last, e.Last) + continue + } + c := e + merged[k] = &c + order = append(order, k) + } + res.Edges = make([]Edge, 0, len(order)) + usedRestricted := false + for _, k := range order { + res.Edges = append(res.Edges, *merged[k]) + usedRestricted = usedRestricted || k.src == Restricted.ID || k.dst == Restricted.ID + } + if usedRestricted { + eps = append(eps, Restricted) + } + res.Endpoints = eps + return res +} diff --git a/images/cluster-map/src/internal/traffic/collector_test.go b/images/cluster-map/src/internal/traffic/collector_test.go index afbd7ba..0fad0a7 100644 --- a/images/cluster-map/src/internal/traffic/collector_test.go +++ b/images/cluster-map/src/internal/traffic/collector_test.go @@ -181,3 +181,30 @@ func TestEmptyWindowEncodesEmptyLists(t *testing.T) { } } } + +func TestRestrictHidesForeignPeers(t *testing.T) { + res := Result{ + Endpoints: []Endpoint{ + {ID: "wl/shop/deployment/web", Namespace: "shop"}, {ID: "wl/bank/deployment/core", Namespace: "bank"}, + {ID: "wl/bank/deployment/ledger", Namespace: "bank"}, {ID: "ext/world"}, + }, + Edges: []Edge{ + {Source: "wl/shop/deployment/web", Target: "wl/bank/deployment/core", Port: "443/TCP", Connections: 2}, + {Source: "wl/shop/deployment/web", Target: "wl/bank/deployment/ledger", Port: "443/TCP", Connections: 3}, + {Source: "wl/bank/deployment/core", Target: "wl/bank/deployment/ledger", Port: "5432/TCP", Connections: 9}, + {Source: "wl/shop/deployment/web", Target: "ext/world", Port: "443/TCP", Connections: 1}, + }, + } + out := Restrict(res, func(ns string) bool { return ns == "shop" }) + for _, e := range out.Endpoints { + if e.Namespace == "bank" { + t.Fatalf("hidden endpoint leaked: %+v", e) + } + } + if len(out.Edges) != 2 { + t.Fatalf("edges: %+v", out.Edges) + } + if e := out.Edges[0]; e.Target != Restricted.ID || e.Connections != 5 { + t.Errorf("two hidden peers on one port merge into one restricted edge: %+v", e) + } +} diff --git a/images/cluster-map/src/web/static/app.js b/images/cluster-map/src/web/static/app.js index a72f6e5..4689098 100644 --- a/images/cluster-map/src/web/static/app.js +++ b/images/cluster-map/src/web/static/app.js @@ -1635,6 +1635,7 @@ matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { async function load() { setStatus(t('status.loadingGraph')); const r = await fetch('/api/graph'); + if (r.status === 401) { setStatus(t('status.noViewerToken'), true); return; } if (!r.ok) { setStatus(t('status.graphFailed', { code: r.status }), true); return; } indexGraph(await r.json()); podsFor = null; @@ -1671,6 +1672,11 @@ applyLock(); fetch('/api/me').then((r) => (r.ok ? r.json() : null)).then((m) => { me = m; if (me?.user) $('#whoami').textContent = me.user; + if (me?.visibility === 'namespaces') { + const w = $('#whoami'); + w.textContent = (me.user ? me.user + ' · ' : '') + t('plural.visibleNs', { n: me.namespaces }); + w.title = t('visibility.namespaces'); + } const n = detailsId && G.byId.get(detailsId); if (n) renderActions(n); }).catch(() => {}); diff --git a/images/cluster-map/src/web/static/i18n.js b/images/cluster-map/src/web/static/i18n.js index afdfefe..ff4c82f 100644 --- a/images/cluster-map/src/web/static/i18n.js +++ b/images/cluster-map/src/web/static/i18n.js @@ -117,6 +117,10 @@ const I18N = { 'plural.critical_cve': { one: '{n} critical', other: '{n} critical' }, 'plural.high_cve': { one: '{n} high', other: '{n} high' }, 'legend.vulns': 'critical vulnerabilities in the images (trivy)', + 'ext.restricted': 'hidden by your permissions', + 'status.noViewerToken': 'The map shows what your own permissions allow, but the request carries no user token. Sign in again; if it repeats, the DexAuthenticator does not pass the Authorization header.', + 'plural.visibleNs': { one: '{n} namespace visible', other: '{n} namespaces visible' }, + 'visibility.namespaces': 'You see the namespaces where your role can list pods; peers elsewhere are shown as hidden.', }, ru: { 'kind.pod': 'Контроллер', 'kind.external': 'Внешний', 'folder.pod': 'Другие контроллеры', @@ -231,6 +235,10 @@ const I18N = { 'plural.critical_cve': { one: '{n} критическая', few: '{n} критические', many: '{n} критических', other: '{n} критической' }, 'plural.high_cve': { one: '{n} высокая', few: '{n} высокие', many: '{n} высоких', other: '{n} высокой' }, 'legend.vulns': 'критические уязвимости в образах (trivy)', + 'ext.restricted': 'скрыто вашими правами', + 'status.noViewerToken': 'Карта показывает то, что разрешают ваши права, но в запросе нет токена пользователя. Войдите заново; если повторится — DexAuthenticator не передаёт заголовок Authorization.', + 'plural.visibleNs': { one: 'виден {n} namespace', few: 'видны {n} namespace', many: 'видно {n} namespace', other: 'видны {n} namespace' }, + 'visibility.namespaces': 'Видны namespace, где ваша роль может смотреть поды; соседи из остальных показаны скрытыми.', }, }; diff --git a/openapi/config-values.yaml b/openapi/config-values.yaml index 27597c3..f3ebe70 100644 --- a/openapi/config-values.yaml +++ b/openapi/config-values.yaml @@ -109,8 +109,19 @@ properties: description: | Access to the web interface. - Anyone admitted here sees every namespace, the manifests of workloads, Services and Ingresses (never Secrets) and container logs, through the module's own read-only service account. Restrict access with `allowedUserGroups`. + With `visibility: ViewerRBAC` (the default) each viewer sees only the namespaces their own RBAC lets them list pods in; with `Everything`, anyone admitted here sees every namespace, the manifests of workloads, Services and Ingresses (never Secrets) and container logs. Either way, restrict who is admitted with `allowedUserGroups`. properties: + visibility: + type: string + default: ViewerRBAC + enum: ["ViewerRBAC", "Everything"] + description: | + What a viewer sees. + + - `ViewerRBAC` — what the viewer's own permissions allow: the whole cluster for a viewer who can list pods in all namespaces, otherwise only the namespaces where they can list pods. Container logs additionally need `get pods/log`, node cards `list nodes`. Traffic to a hidden namespace is shown as coming from or going to a hidden peer. Checked with SelfSubjectAccessReviews as the viewer and cached for a minute. + - `Everything` — every admitted viewer sees the whole cluster, read with the module's service account. + + `ViewerRBAC` needs the viewer's token: the `user-authn` module, or an `externalAuthentication` that puts a token the API server accepts into the `Authorization` header. externalAuthentication: type: object description: | diff --git a/openapi/doc-ru-config-values.yaml b/openapi/doc-ru-config-values.yaml index 3ea5185..08db2b6 100644 --- a/openapi/doc-ru-config-values.yaml +++ b/openapi/doc-ru-config-values.yaml @@ -58,8 +58,16 @@ properties: description: | Доступ к веб-интерфейсу. - Любой, кого сюда пустили, видит все namespace, манифесты workload'ов, Service и Ingress (Secret — никогда) и логи контейнеров — через собственную read-only-учётку модуля. Ограничивайте доступ через `allowedUserGroups`. + При `visibility: ViewerRBAC` (по умолчанию) каждый видит только namespace, где его собственный RBAC разрешает смотреть поды; при `Everything` любой, кого сюда пустили, видит все namespace, манифесты workload'ов, Service и Ingress (Secret — никогда) и логи контейнеров. В обоих случаях ограничивайте круг допущенных через `allowedUserGroups`. properties: + visibility: + description: | + Что видит пользователь. + + - `ViewerRBAC` — то, что разрешают его собственные права: весь кластер, если он может смотреть поды во всех namespace, иначе только namespace, где он может смотреть поды. Для логов контейнеров нужно ещё `get pods/log`, для карточек нод — `list nodes`. Трафик в скрытый namespace показывается как соединение со скрытым соседом. Проверяется через SelfSubjectAccessReview от имени пользователя, ответ кешируется на минуту. + - `Everything` — каждый допущенный пользователь видит весь кластер, чтение идёт сервисным аккаунтом модуля. + + Для `ViewerRBAC` нужен токен пользователя: модуль `user-authn` или `externalAuthentication`, который кладёт в заголовок `Authorization` токен, принимаемый API-сервером. externalAuthentication: description: | Параметры для подключения внешней аутентификации на основе механизма Ingress NGINX [external-auth](https://kubernetes.github.io/ingress-nginx/examples/auth/external-auth/). diff --git a/templates/_helpers.tpl b/templates/_helpers.tpl new file mode 100644 index 0000000..5a8a5d6 --- /dev/null +++ b/templates/_helpers.tpl @@ -0,0 +1,6 @@ +{{- /* "true" when the module needs the viewer's own token in each request: + for actions (they run as the viewer) and for ViewerRBAC visibility + (what the viewer may see is asked as the viewer). */}} +{{- define "cluster_map_viewer_token" -}} +{{- or .Values.clusterMap.actions.enabled (eq .Values.clusterMap.auth.visibility "ViewerRBAC") -}} +{{- end -}} diff --git a/templates/deployment.yaml b/templates/deployment.yaml index 99acb4e..d7279ef 100644 --- a/templates/deployment.yaml +++ b/templates/deployment.yaml @@ -98,6 +98,8 @@ spec: value: /etc/hubble-ca/ca.crt - name: ACTIONS_ENABLED value: {{ .Values.clusterMap.actions.enabled | quote }} + - name: VISIBILITY + value: {{ .Values.clusterMap.auth.visibility | quote }} - name: LOG_TAIL_LINES value: {{ .Values.clusterMap.logs.tailLines | quote }} - name: SYSTEM_NAMESPACE_PREFIXES diff --git a/templates/dex-authenticator.yaml b/templates/dex-authenticator.yaml index 4a7663e..0fde9c3 100644 --- a/templates/dex-authenticator.yaml +++ b/templates/dex-authenticator.yaml @@ -10,10 +10,11 @@ metadata: name: cluster-map namespace: d8-cluster-map {{- include "helm_lib_module_labels" (list . (dict "app" "dex-authenticator" "name" "cluster-map")) | nindent 2 }} - {{- if .Values.clusterMap.actions.enabled }} + {{- if eq (include "cluster_map_viewer_token" .) "true" }} annotations: # user-authn then asks Dex for a token with the kubernetes audience, - # which the API server accepts: actions run with it (as the console does) + # which the API server accepts: actions and ViewerRBAC visibility use it + # (as the console does) dexauthenticator.deckhouse.io/allow-access-to-kubernetes: "true" {{- end }} spec: @@ -26,9 +27,9 @@ spec: applicationHTTPRouteListenerSetName: cluster-map {{- end }} applicationIngressClassName: {{ include "helm_lib_module_ingress_class" . | quote }} - {{- if .Values.clusterMap.actions.enabled }} - # actions run as the viewer: the user's token goes to the module in the - # Authorization header + {{- if eq (include "cluster_map_viewer_token" .) "true" }} + # actions and visibility run as the viewer: the user's token goes to the + # module in the Authorization header sendAuthorizationHeader: true {{- end }} {{- with .Values.clusterMap.auth.allowedUserEmails }} diff --git a/templates/httproute.yaml b/templates/httproute.yaml index db3a3b5..6aa9158 100644 --- a/templates/httproute.yaml +++ b/templates/httproute.yaml @@ -59,7 +59,7 @@ metadata: {{- if and (ne (include "helm_lib_module_https_mode" .) "Disabled") .Values.clusterMap.auth.externalAuthentication }} alb.network.deckhouse.io/auth-signin: {{ replace "$host" (include "helm_lib_module_public_domain" (list . "cluster-map")) .Values.clusterMap.auth.externalAuthentication.authSignInURL | quote }} alb.network.deckhouse.io/auth-url: {{ .Values.clusterMap.auth.externalAuthentication.authURL | quote }} - alb.network.deckhouse.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" .Values.clusterMap.actions.enabled | quote }} + alb.network.deckhouse.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" (eq (include "cluster_map_viewer_token" .) "true") | quote }} {{- end }} {{- if .Values.clusterMap.auth.whitelistSourceRanges }} alb.network.deckhouse.io/whitelist-source-range: {{ .Values.clusterMap.auth.whitelistSourceRanges | join "," | quote }} diff --git a/templates/ingress.yaml b/templates/ingress.yaml index 1013d9c..3b84893 100644 --- a/templates/ingress.yaml +++ b/templates/ingress.yaml @@ -15,7 +15,7 @@ metadata: {{- if and (ne (include "helm_lib_module_https_mode" .) "Disabled") .Values.clusterMap.auth.externalAuthentication }} nginx.ingress.kubernetes.io/auth-signin: {{ .Values.clusterMap.auth.externalAuthentication.authSignInURL | quote }} nginx.ingress.kubernetes.io/auth-url: {{ .Values.clusterMap.auth.externalAuthentication.authURL | quote }} - nginx.ingress.kubernetes.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" .Values.clusterMap.actions.enabled | quote }} + nginx.ingress.kubernetes.io/auth-response-headers: {{ ternary "X-Auth-Request-User,X-Auth-Request-Email,Authorization" "X-Auth-Request-User,X-Auth-Request-Email" (eq (include "cluster_map_viewer_token" .) "true") | quote }} {{- end }} {{- if .Values.clusterMap.auth.whitelistSourceRanges }} nginx.ingress.kubernetes.io/whitelist-source-range: {{ .Values.clusterMap.auth.whitelistSourceRanges | join "," | quote }} diff --git a/tests/values/default.yaml b/tests/values/default.yaml index c4083fd..ad54746 100644 --- a/tests/values/default.yaml +++ b/tests/values/default.yaml @@ -34,6 +34,7 @@ clusterMap: tailLines: 500 systemNamespacePrefixes: ["d8-", "kube-"] auth: + visibility: ViewerRBAC allowedUserGroups: ["admins"] externalAuthentication: authURL: https://cluster-map-dex-authenticator.d8-cluster-map.svc.cluster.local/dex-authenticator/auth