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 <noreply@anthropic.com>
This commit is contained in:
Виталий Чефанов
2026-09-25 01:03:50 +03:00
co-authored by Claude Opus 5.5
parent ce6dad9a58
commit c50020e420
27 changed files with 791 additions and 26 deletions
@@ -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 {
@@ -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
}
@@ -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())
}
}
@@ -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:
@@ -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 == "":
@@ -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/<name> 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
}
@@ -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/<ns>/<kind>/<name>) 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
}
@@ -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)
}
}
@@ -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
}
@@ -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")
}
}
@@ -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
}
@@ -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)
}
}
+6
View File
@@ -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(() => {});
@@ -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, где ваша роль может смотреть поды; соседи из остальных показаны скрытыми.',
},
};