From 0905af157ba8aac692947e546c19898183a9ea2f Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Mon, 23 Nov 2026 15:22:58 +0100 Subject: [PATCH 1/5] webui: let the members of a NACM group share a home page WEBUI_HOME names the users that get a page of their own, but the image is built before the users exist. An operator account added in the field is not in the list and lands on the regular pages. Take @group=/path as well, for all members of a NACM group, so the factory configuration can ship the group and its rules: WEBUI_HOME=operator=/panel/ @guest=/stats/ A user entry wins over a group, and of several groups the first in the list. A group never applies to an admin, who could otherwise not get back to the regular pages to leave it. Only an admin may read the NACM data over RESTCONF, so the groups are read with sysrepocfg at login and the home is kept in the session. A login is refused when they cannot be read. Signed-off-by: Joachim Wiberg --- src/webui/README.md | 19 +++-- src/webui/internal/auth/home.go | 63 ++++++++++++++++ src/webui/internal/auth/home_test.go | 75 ++++++++++++++++++++ src/webui/internal/auth/login.go | 17 +++-- src/webui/internal/auth/store.go | 40 ++++++----- src/webui/internal/auth/store_test.go | 8 +-- src/webui/internal/handlers/nacm.go | 37 ++++++++++ src/webui/internal/handlers/nacm_test.go | 24 +++++++ src/webui/internal/server/middleware.go | 20 +++--- src/webui/internal/server/middleware_test.go | 35 +++++---- src/webui/internal/server/server.go | 4 +- src/webui/main.go | 21 +----- src/webui/main_test.go | 13 ---- 13 files changed, 283 insertions(+), 93 deletions(-) create mode 100644 src/webui/internal/auth/home.go create mode 100644 src/webui/internal/auth/home_test.go create mode 100644 src/webui/internal/handlers/nacm_test.go diff --git a/src/webui/README.md b/src/webui/README.md index 33cf80293f..90a5708a3f 100644 --- a/src/webui/README.md +++ b/src/webui/README.md @@ -67,12 +67,23 @@ serves the page as plain files, from a snippet in `/etc/nginx/app/`, and `/etc/default/webui` says who gets it: ```sh -WEBUI_HOME=operator=/panel/ service=/service/ +WEBUI_HOME=operator=/panel/ @guest=/stats/ @service=/service/ ``` -A user listed there lands on their page after login and cannot leave -it. Everyone else gets the regular pages. The page uses the same -login as the WebUI, and two endpoints: +An entry is `user=/path`, or `@group=/path` for all members of a NACM +group. Anyone listed lands on their page after login and cannot leave +it. Everyone else gets the regular pages. A group suits users that +are created after the image is built: the factory configuration ships +the group and its NACM rules, and every user added to it later gets +the page. + +An entry for a user wins over one for a group. A user in more than one +listed group gets the page of the group that comes first in the list. +A group entry never applies to an administrator, i.e. a user allowed to +read the NACM configuration. Group membership is read at login, so a +change takes effect the next time the user logs in. + +The page uses the same login as the WebUI, and two endpoints: | **Endpoint** | **Use** | |------------------------|------------------------------------------------------------| diff --git a/src/webui/internal/auth/home.go b/src/webui/internal/auth/home.go new file mode 100644 index 0000000000..a8e0217d39 --- /dev/null +++ b/src/webui/internal/auth/home.go @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: MIT + +package auth + +import ( + "context" + "log" + "slices" + "strings" +) + +type groupHome struct { + group, path string +} + +// Homes is WEBUI_HOME: who lands on a page of their own after login +// instead of the dashboard. nginx serves the page, not this binary. +type Homes struct { + users map[string]string + groups []groupHome +} + +// ParseHomes reads WEBUI_HOME, a space separated list of user=path and +// @group=path, the latter for the members of a NACM group. +func ParseHomes(v string) Homes { + h := Homes{users: make(map[string]string)} + for _, f := range strings.Fields(v) { + name, path, ok := strings.Cut(f, "=") + // A browser takes //host and /\host for another host + if !ok || name == "" || name == "@" || path == "/" || !strings.HasPrefix(path, "/") || + strings.HasPrefix(path, "//") || strings.Contains(path, "\\") { + log.Printf("WEBUI_HOME: ignoring %q, want user=/path or @group=/path", f) + continue + } + if group, ok := strings.CutPrefix(name, "@"); ok { + h.groups = append(h.groups, groupHome{group, path}) + } else { + h.users[name] = path + } + } + return h +} + +// Resolve returns the home of user, empty for the dashboard. The +// groups of the user are only looked up when a group entry can apply. +// It never does for an admin, who could not get back to the regular +// pages to leave the group. +func (h Homes) Resolve(ctx context.Context, user string, admin bool, + lookup func(context.Context, string) ([]string, error)) (string, error) { + if home := h.users[user]; home != "" || admin || len(h.groups) == 0 { + return home, nil + } + groups, err := lookup(ctx, user) + if err != nil { + return "", err + } + for _, g := range h.groups { + if slices.Contains(groups, g.group) { + return g.path, nil + } + } + return "", nil +} diff --git a/src/webui/internal/auth/home_test.go b/src/webui/internal/auth/home_test.go new file mode 100644 index 0000000000..3e47294bdc --- /dev/null +++ b/src/webui/internal/auth/home_test.go @@ -0,0 +1,75 @@ +// SPDX-License-Identifier: MIT + +package auth + +import ( + "context" + "errors" + "testing" +) + +func TestParseHomes(t *testing.T) { + h := ParseHomes("guest=/stats/ bad nopath= rel=stats host=//evil.example/ bs=/\\evil.example/ root=/ op=/op/" + + " @=/x/ @evil=//evil.example/ @service=/service/ @guest=/panel/") + + if len(h.users) != 2 || h.users["guest"] != "/stats/" || h.users["op"] != "/op/" { + t.Errorf("users: got %v", h.users) + } + want := []groupHome{{"service", "/service/"}, {"guest", "/panel/"}} + if len(h.groups) != len(want) || h.groups[0] != want[0] || h.groups[1] != want[1] { + t.Errorf("groups: got %v, want %v", h.groups, want) + } +} + +func TestHomesResolve(t *testing.T) { + members := map[string][]string{ + "jane": {"guest"}, + "joe": {"guest", "service"}, + "olle": {"operator"}, + "service": {"guest"}, + "op": {"guest"}, + "admin": {"admin", "guest"}, + } + lookups := 0 + lookup := func(_ context.Context, user string) ([]string, error) { + lookups++ + if user == "broken" { + return nil, errors.New("no sysrepo") + } + return members[user], nil + } + h := ParseHomes("op=/op/ @service=/service/ @guest=/panel/") + + for _, tc := range []struct { + user string + admin bool + want string + lookups int + }{ + {"jane", false, "/panel/", 1}, + {"joe", false, "/service/", 1}, + {"olle", false, "", 1}, + {"guest", false, "", 1}, + {"service", false, "/panel/", 1}, + {"op", false, "/op/", 0}, + {"op", true, "/op/", 0}, + {"admin", true, "", 0}, + } { + lookups = 0 + got, err := h.Resolve(context.Background(), tc.user, tc.admin, lookup) + if err != nil || got != tc.want || lookups != tc.lookups { + t.Errorf("%s: got %q, %v after %d lookups, want %q after %d", + tc.user, got, err, lookups, tc.want, tc.lookups) + } + } + + if _, err := h.Resolve(context.Background(), "broken", false, lookup); err == nil { + t.Error("failed group lookup: no error") + } + + lookups = 0 + got, err := ParseHomes("op=/op/").Resolve(context.Background(), "jane", false, lookup) + if err != nil || got != "" || lookups != 0 { + t.Errorf("no group homes: got %q, %v after %d lookups", got, err, lookups) + } +} diff --git a/src/webui/internal/auth/login.go b/src/webui/internal/auth/login.go index 757e6e40e0..e8b25e0d49 100644 --- a/src/webui/internal/auth/login.go +++ b/src/webui/internal/auth/login.go @@ -28,9 +28,7 @@ type LoginHandler struct { // foreground, so implementations should start their own goroutines for // slow work. May be nil. OnLogin func(ctx context.Context) - // Homes maps a username to the page it lands on after login, for - // users that should not get the dashboard. May be nil. - Homes map[string]string + Homes Homes } type loginData struct { @@ -90,14 +88,22 @@ func (h *LoginHandler) DoLogin(w http.ResponseWriter, r *http.Request) { // The User's Guide is bundled at build time (a filesystem check, not // config); gate the Help entry on its presence. caps.Features()["docs"] = handlers.DetectDocs() - caps.Features()["nacm"] = handlers.DetectNACMAccess(ctx, h.RC) + admin := handlers.DetectNACMAccess(ctx, h.RC) + caps.Features()["nacm"] = admin + + home, err := h.Homes.Resolve(ctx, username, admin, handlers.NACMGroups) + if err != nil { + log.Printf("login refused for %q, cannot read NACM groups: %v", username, err) + h.renderLogin(w, r, "Unable to reach the device. Please try again later.") + return + } // Trigger any post-login hooks (e.g. schema sync) with full credentials. if h.OnLogin != nil { h.OnLogin(ctx) } - token, csrfToken, err := h.Store.Create(username, password, caps.Features()) + token, csrfToken, err := h.Store.Create(username, password, caps.Features(), home) if err != nil { log.Printf("session create error: %v", err) http.Error(w, "Internal server error", http.StatusInternalServerError) @@ -114,7 +120,6 @@ func (h *LoginHandler) DoLogin(w http.ResponseWriter, r *http.Request) { }) security.EnsureToken(w, r, csrfToken) - home := h.Homes[username] if home == "" { home = "/" } diff --git a/src/webui/internal/auth/store.go b/src/webui/internal/auth/store.go index 8987518596..4df87be8a0 100644 --- a/src/webui/internal/auth/store.go +++ b/src/webui/internal/auth/store.go @@ -16,15 +16,21 @@ const sessionTimeout = 1 * time.Hour // its idle timeout, "Off" included. const sessionLifetime = 24 * time.Hour +// Session is what the store hands out about a live session. +type Session struct { + Username string + Password string + CSRF string + Features map[string]bool + Home string // page the user is kept on, empty for none +} + // sessionEntry is the in-memory state of a single authenticated // session. The user's password is kept alongside the token so the // webui can re-authenticate to RESTCONF on the user's behalf on each // request; it is never written to disk or surfaced over the wire. type sessionEntry struct { - username string - password string - csrfToken string - features map[string]bool + Session createdAt time.Time lastSeenAt time.Time timeout time.Duration // idle timeout; 0 = never expire ("Off") @@ -61,7 +67,7 @@ func NewSessionStore() *SessionStore { // Create issues a session for the given credentials, returning the // session token (cookie value) and a freshly minted CSRF token. -func (s *SessionStore) Create(username, password string, features map[string]bool) (string, string, error) { +func (s *SessionStore) Create(username, password string, features map[string]bool, home string) (string, string, error) { token, err := security.RandomToken() if err != nil { return "", "", fmt.Errorf("session token: %w", err) @@ -74,10 +80,13 @@ func (s *SessionStore) Create(username, password string, features map[string]boo now := time.Now() s.mu.Lock() s.sessions[token] = &sessionEntry{ - username: username, - password: password, - csrfToken: csrf, - features: features, + Session: Session{ + Username: username, + Password: password, + CSRF: csrf, + Features: features, + Home: home, + }, createdAt: now, lastSeenAt: now, timeout: sessionTimeout, @@ -86,16 +95,15 @@ func (s *SessionStore) Create(username, password string, features map[string]boo return token, csrf, nil } -// Lookup returns the credentials associated with a session token, or -// ok=false if the token is unknown or expired. An expired entry is -// reaped as a side effect. -func (s *SessionStore) Lookup(token string) (username, password, csrf string, features map[string]bool, ok bool) { +// Lookup returns the session behind a token, or ok=false if the token +// is unknown or expired. An expired entry is reaped as a side effect. +func (s *SessionStore) Lookup(token string) (Session, bool) { s.mu.RLock() e, present := s.sessions[token] if present && !expired(e) { - username, password, csrf, features = e.username, e.password, e.csrfToken, e.features + sess := e.Session s.mu.RUnlock() - return username, password, csrf, features, true + return sess, true } s.mu.RUnlock() @@ -110,7 +118,7 @@ func (s *SessionStore) Lookup(token string) (username, password, csrf string, fe } s.mu.Unlock() } - return "", "", "", nil, false + return Session{}, false } // SetTimeout updates a session's idle timeout (0 = never expire) so the diff --git a/src/webui/internal/auth/store_test.go b/src/webui/internal/auth/store_test.go index f1fd069c20..d6731d62eb 100644 --- a/src/webui/internal/auth/store_test.go +++ b/src/webui/internal/auth/store_test.go @@ -9,7 +9,7 @@ import ( func TestSessionLifetime(t *testing.T) { s := &SessionStore{sessions: make(map[string]*sessionEntry)} - token, _, err := s.Create("admin", "admin", nil) + token, _, err := s.Create("admin", "admin", nil, "") if err != nil { t.Fatal(err) } @@ -19,14 +19,14 @@ func TestSessionLifetime(t *testing.T) { e := s.sessions[token] e.createdAt = time.Now().Add(-sessionLifetime - time.Minute) e.lastSeenAt = time.Now().Add(-time.Minute) - if _, _, _, _, ok := s.Lookup(token); ok { + if _, ok := s.Lookup(token); ok { t.Error("session outlived its lifetime") } - token, _, _ = s.Create("admin", "admin", nil) + token, _, _ = s.Create("admin", "admin", nil, "") s.SetTimeout(token, 0) s.sessions[token].lastSeenAt = time.Now().Add(-12 * time.Hour) - if _, _, _, _, ok := s.Lookup(token); !ok { + if _, ok := s.Lookup(token); !ok { t.Error("idle session with Auto-logout off expired before its lifetime") } } diff --git a/src/webui/internal/handlers/nacm.go b/src/webui/internal/handlers/nacm.go index 0ab9e7528b..c3792a3d7f 100644 --- a/src/webui/internal/handlers/nacm.go +++ b/src/webui/internal/handlers/nacm.go @@ -3,10 +3,16 @@ package handlers import ( + "bytes" + "context" + "encoding/json" "html/template" "log" "net/http" + "os/exec" + "slices" "strings" + "time" "infix/webui/internal/restconf" ) @@ -38,6 +44,37 @@ type nacmGroupJSON struct { UserNames []string `json:"user-name"` } +// NACMGroups returns the NACM groups user is a member of. It reads +// straight from sysrepo, outside NACM: only an admin may read the NACM +// data over RESTCONF. +func NACMGroups(ctx context.Context, user string) ([]string, error) { + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + out, err := exec.CommandContext(ctx, "sysrepocfg", "-X", "-d", "running", "-f", "json", + "-x", "/ietf-netconf-acm:nacm/groups").Output() + if err != nil { + return nil, err + } + return nacmGroupsOf(out, user) +} + +func nacmGroupsOf(data []byte, user string) ([]string, error) { + var raw nacmWrapper + // No groups at all comes back as no output + if len(bytes.TrimSpace(data)) > 0 { + if err := json.Unmarshal(data, &raw); err != nil { + return nil, err + } + } + var groups []string + for _, g := range raw.NACM.Groups.Group { + if slices.Contains(g.UserNames, user) { + groups = append(groups, g.Name) + } + } + return groups, nil +} + type nacmRuleListJSON struct { Name string `json:"name"` Group []string `json:"group"` diff --git a/src/webui/internal/handlers/nacm_test.go b/src/webui/internal/handlers/nacm_test.go new file mode 100644 index 0000000000..3b4c21a068 --- /dev/null +++ b/src/webui/internal/handlers/nacm_test.go @@ -0,0 +1,24 @@ +// SPDX-License-Identifier: MIT + +package handlers + +import "testing" + +func TestNACMGroupsOf(t *testing.T) { + data := []byte(`{"ietf-netconf-acm:nacm":{"groups":{"group":[ + {"name":"admin","user-name":["admin"]}, + {"name":"guest","user-name":["jane","joe"]}, + {"name":"empty"}, + {"name":"service","user-name":["jane"]}]}}}`) + + got, err := nacmGroupsOf(data, "jane") + if err != nil || len(got) != 2 || got[0] != "guest" || got[1] != "service" { + t.Errorf("jane: got %v, %v", got, err) + } + if got, err := nacmGroupsOf(nil, "jane"); err != nil || len(got) != 0 { + t.Errorf("no data: got %v, %v", got, err) + } + if _, err := nacmGroupsOf([]byte("{"), "jane"); err == nil { + t.Error("bad data: no error") + } +} diff --git a/src/webui/internal/server/middleware.go b/src/webui/internal/server/middleware.go index e14f6ceaf9..2c1c8ada5b 100644 --- a/src/webui/internal/server/middleware.go +++ b/src/webui/internal/server/middleware.go @@ -21,7 +21,7 @@ const cookieName = "session" // the token up in the in-memory store, and attaches the session's // credentials to the context. Unauthenticated requests are // redirected to /login (or get a 401 if the request comes from HTMX). -func authMiddleware(store *auth.SessionStore, rc restconf.Fetcher, homes map[string]string, next http.Handler) http.Handler { +func authMiddleware(store *auth.SessionStore, rc restconf.Fetcher, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if isPublicPath(r.URL.Path) { next.ServeHTTP(w, r) @@ -34,14 +34,14 @@ func authMiddleware(store *auth.SessionStore, rc restconf.Fetcher, homes map[str return } - username, password, csrf, features, ok := store.Lookup(cookie.Value) + sess, ok := store.Lookup(cookie.Value) if !ok { deny(w, r) return } - if home := homes[username]; home != "" && !homeAllowed(r.URL.Path, home) { - redirect(w, r, home) + if sess.Home != "" && !homeAllowed(r.URL.Path, sess.Home) { + redirect(w, r, sess.Home) return } @@ -56,10 +56,10 @@ func authMiddleware(store *auth.SessionStore, rc restconf.Fetcher, homes map[str } ctx := restconf.ContextWithCredentials(r.Context(), restconf.Credentials{ - Username: username, - Password: password, + Username: sess.Username, + Password: sess.Password, }) - ctx = security.WithToken(ctx, csrf) + ctx = security.WithToken(ctx, sess.CSRF) // The console / netbrowse shortcuts are toggleable in running-config at // runtime, unlike the other (per-boot) capabilities baked into the @@ -69,11 +69,11 @@ func authMiddleware(store *auth.SessionStore, rc restconf.Fetcher, homes map[str // never re-draw them, so they're skipped (no read per request). fullPageLoad := !polling && r.Header.Get("HX-Request") != "true" if rc != nil && fullPageLoad { - features = maps.Clone(features) // don't mutate the shared session map - handlers.ApplyWebShortcuts(ctx, rc, features) + sess.Features = maps.Clone(sess.Features) // don't mutate the shared session map + handlers.ApplyWebShortcuts(ctx, rc, sess.Features) } - ctx = handlers.ContextWithCapabilities(ctx, handlers.NewCapabilities(features)) + ctx = handlers.ContextWithCapabilities(ctx, handlers.NewCapabilities(sess.Features)) next.ServeHTTP(w, r.WithContext(ctx)) }) } diff --git a/src/webui/internal/server/middleware_test.go b/src/webui/internal/server/middleware_test.go index 638fbe74a1..65a305d1f6 100644 --- a/src/webui/internal/server/middleware_test.go +++ b/src/webui/internal/server/middleware_test.go @@ -124,30 +124,29 @@ func TestSameOriginIgnoresForwardedHost(t *testing.T) { } } -// A user with a home page, see WEBUI_HOME, is sent there from every +// A session with a home page, see WEBUI_HOME, is sent there from every // regular page but keeps the API the page reads from, and logout. func TestHomeUserIsKeptOnHomePage(t *testing.T) { store := auth.NewSessionStore() - homes := map[string]string{"guest": "/stats"} - h := authMiddleware(store, nil, homes, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) + h := authMiddleware(store, nil, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})) for _, tc := range []struct { - user, method, path string + home, method, path string want int }{ - {"guest", http.MethodGet, "/", http.StatusSeeOther}, - {"guest", http.MethodGet, "/configure/tree", http.StatusSeeOther}, - {"guest", http.MethodGet, "/api/data", http.StatusSeeOther}, - {"guest", http.MethodGet, "/api/restconf/data/ietf-hardware:hardware", http.StatusOK}, - {"guest", http.MethodGet, "/api/session", http.StatusOK}, - {"guest", http.MethodPost, "/logout", http.StatusOK}, - {"guest", http.MethodGet, "/stats/missing.js", http.StatusOK}, - {"guest", http.MethodGet, "/stats", http.StatusOK}, - {"guest", http.MethodGet, "/statsother", http.StatusSeeOther}, - {"guest", http.MethodGet, "/status/tree", http.StatusSeeOther}, - {"admin", http.MethodGet, "/", http.StatusOK}, + {"/stats", http.MethodGet, "/", http.StatusSeeOther}, + {"/stats", http.MethodGet, "/configure/tree", http.StatusSeeOther}, + {"/stats", http.MethodGet, "/api/data", http.StatusSeeOther}, + {"/stats", http.MethodGet, "/api/restconf/data/ietf-hardware:hardware", http.StatusOK}, + {"/stats", http.MethodGet, "/api/session", http.StatusOK}, + {"/stats", http.MethodPost, "/logout", http.StatusOK}, + {"/stats", http.MethodGet, "/stats/missing.js", http.StatusOK}, + {"/stats", http.MethodGet, "/stats", http.StatusOK}, + {"/stats", http.MethodGet, "/statsother", http.StatusSeeOther}, + {"/stats", http.MethodGet, "/status/tree", http.StatusSeeOther}, + {"", http.MethodGet, "/", http.StatusOK}, } { - token, _, err := store.Create(tc.user, "pw", nil) + token, _, err := store.Create("user", "pw", nil, tc.home) if err != nil { t.Fatal(err) } @@ -156,10 +155,10 @@ func TestHomeUserIsKeptOnHomePage(t *testing.T) { w := httptest.NewRecorder() h.ServeHTTP(w, r) if w.Code != tc.want { - t.Errorf("%s %s %s: status %d, want %d", tc.user, tc.method, tc.path, w.Code, tc.want) + t.Errorf("%q %s %s: status %d, want %d", tc.home, tc.method, tc.path, w.Code, tc.want) } if tc.want == http.StatusSeeOther && w.Header().Get("Location") != "/stats" { - t.Errorf("%s %s: redirected to %q, want /stats", tc.user, tc.path, w.Header().Get("Location")) + t.Errorf("%q %s: redirected to %q, want /stats", tc.home, tc.path, w.Header().Get("Location")) } } } diff --git a/src/webui/internal/server/server.go b/src/webui/internal/server/server.go index e4f17732e4..3cbaf3ab5b 100644 --- a/src/webui/internal/server/server.go +++ b/src/webui/internal/server/server.go @@ -21,7 +21,7 @@ func New( schemaCache *schema.Cache, templateFS fs.FS, staticFS fs.FS, - homes map[string]string, + homes auth.Homes, ) (http.Handler, error) { // Parse templates per page so each can define its own "content" block // without collisions. @@ -549,7 +549,7 @@ func New( mux.HandleFunc("GET /status/tree/children", statusTreeH.TreeChildren) mux.HandleFunc("GET /status/tree/node", statusTreeH.TreeNode) - handler := authMiddleware(store, rc, homes, mux) + handler := authMiddleware(store, rc, mux) handler = csrfMiddleware(handler) handler = securityHeadersMiddleware(handler) return handler, nil diff --git a/src/webui/main.go b/src/webui/main.go index d69afb651c..02f0588253 100644 --- a/src/webui/main.go +++ b/src/webui/main.go @@ -53,7 +53,7 @@ func main() { log.Fatalf("static fs: %v", err) } - handler, err := server.New(store, rc, schemaCache, tmplFS, stFS, parseHomes(os.Getenv("WEBUI_HOME"))) + handler, err := server.New(store, rc, schemaCache, tmplFS, stFS, auth.ParseHomes(os.Getenv("WEBUI_HOME"))) if err != nil { log.Fatalf("server setup: %v", err) } @@ -72,25 +72,6 @@ func main() { } } -// parseHomes reads WEBUI_HOME, a space separated list of user=path. A -// user listed here lands on path after login instead of the dashboard, -// and is kept there, see homeAllowed. The page itself is served by -// nginx, it is not part of this binary. -func parseHomes(v string) map[string]string { - homes := make(map[string]string) - for _, f := range strings.Fields(v) { - user, path, ok := strings.Cut(f, "=") - // A browser takes //host and /\host for another host - if !ok || user == "" || path == "/" || !strings.HasPrefix(path, "/") || - strings.HasPrefix(path, "//") || strings.Contains(path, "\\") { - log.Printf("WEBUI_HOME: ignoring %q, want user=/path", f) - continue - } - homes[user] = path - } - return homes -} - func envBool(key string) bool { v := strings.TrimSpace(os.Getenv(key)) if v == "" { diff --git a/src/webui/main_test.go b/src/webui/main_test.go index 9ac5966df6..8842af68fe 100644 --- a/src/webui/main_test.go +++ b/src/webui/main_test.go @@ -34,16 +34,3 @@ func TestTemplatesParse(t *testing.T) { } } } - -func TestParseHomes(t *testing.T) { - got := parseHomes("guest=/stats/ bad nopath= rel=stats host=//evil.example/ bs=/\\evil.example/ root=/ op=/op/") - want := map[string]string{"guest": "/stats/", "op": "/op/"} - if len(got) != len(want) { - t.Fatalf("got %v, want %v", got, want) - } - for user, path := range want { - if got[user] != path { - t.Errorf("%s: got %q, want %q", user, got[user], path) - } - } -} From 52429d385c524de1bd4d1383a438266e8c13521a Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Mon, 23 Nov 2026 17:06:51 +0100 Subject: [PATCH 2/5] doc: list the container runtime and PyYAML as test dependencies The developer's guide left out two things a fresh machine needs for the tests. make test runs Infamy in a container and needs Docker or podman for that, and the test specification generator imports the Python yaml module. Signed-off-by: Joachim Wiberg --- doc/developers-guide.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/doc/developers-guide.md b/doc/developers-guide.md index 5772a1903c..e5bfd17a01 100644 --- a/doc/developers-guide.md +++ b/doc/developers-guide.md @@ -101,10 +101,18 @@ $ sudo apt install jq graphviz qemu-system-x86 qemu-system-arm \ .. ``` +The tests themselves run in a container, so `make test` also needs +Docker, or podman: + +```bash +$ sudo apt install docker.io +.. +``` + To be able to build the test specification you also need: ```bash -$ sudo apt-get install python3-graphviz ruby-asciidoctor-pdf +$ sudo apt-get install python3-graphviz python3-yaml ruby-asciidoctor-pdf .. ``` From a4481621ddabb856b8b80ab4fd22c9162114d81c Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Mon, 23 Nov 2026 17:27:49 +0100 Subject: [PATCH 3/5] confd: add whoami RPC, for a user to learn its own NACM groups Only an admin can read the NACM configuration, so nobody else, and no application acting for them, can tell what groups a user is in. POST /restconf/operations/infix-system:whoami returns the name of the calling user and its groups, nothing about other users. The factory rules deny guests all RPCs, so permit this one ahead of that rule, and add the same rule to existing configurations on upgrade. The rpc_output() helper in Infamy now returns a leaf-list as a list. Signed-off-by: Joachim Wiberg --- .../etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../bananapi,bpi-r3/etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../bananapi,bpi-r4/etc/factory-config.cfg | 10 ++- .../bananapi,bpi-r64/etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../raspberrypi,400/etc/factory-config.cfg | 10 ++- .../lemaker,bananapi/etc/factory-config.cfg | 10 ++- .../etc/factory-config.cfg | 10 ++- .../bananapi,bpi-f3/etc/factory-config.cfg | 10 ++- doc/ChangeLog.md | 4 ++ doc/nacm.md | 18 ++++- src/confd/configure.ac | 3 +- src/confd/share/factory.d/10-nacm.json | 8 +++ .../migrate/1.14/10-nacm-permit-whoami.sh | 30 ++++++++ src/confd/share/migrate/1.14/Makefile.am | 2 + src/confd/share/migrate/Makefile.am | 2 +- src/confd/src/syslog.c | 6 +- src/confd/src/system.c | 40 +++++++++++ src/confd/yang/confd/infix-system.yang | 22 +++++- test/case/syslog/rpc_log/test.py | 4 +- test/case/system/Readme.adoc | 4 ++ test/case/system/all.yaml | 3 + test/case/system/whoami/Readme.adoc | 1 + test/case/system/whoami/test.adoc | 24 +++++++ test/case/system/whoami/test.py | 72 +++++++++++++++++++ test/case/system/whoami/topology.dot | 1 + test/case/system/whoami/topology.svg | 33 +++++++++ test/infamy/netconf.py | 11 ++- test/infamy/restconf.py | 5 +- 34 files changed, 405 insertions(+), 28 deletions(-) create mode 100755 src/confd/share/migrate/1.14/10-nacm-permit-whoami.sh create mode 100644 src/confd/share/migrate/1.14/Makefile.am create mode 120000 test/case/system/whoami/Readme.adoc create mode 100644 test/case/system/whoami/test.adoc create mode 100755 test/case/system/whoami/test.py create mode 120000 test/case/system/whoami/topology.dot create mode 100644 test/case/system/whoami/topology.svg diff --git a/board/aarch64/acer-connect-vero-w6m/rootfs/usr/share/product/acer,connect-vero-w/etc/factory-config.cfg b/board/aarch64/acer-connect-vero-w6m/rootfs/usr/share/product/acer,connect-vero-w/etc/factory-config.cfg index 9f7909ef90..1c5cde8ad8 100644 --- a/board/aarch64/acer-connect-vero-w6m/rootfs/usr/share/product/acer,connect-vero-w/etc/factory-config.cfg +++ b/board/aarch64/acer-connect-vero-w6m/rootfs/usr/share/product/acer,connect-vero-w/etc/factory-config.cfg @@ -300,6 +300,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -463,7 +471,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r2-pro/rootfs/usr/share/product/sinovoip,rk3568-bpi-r2pro/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r2-pro/rootfs/usr/share/product/sinovoip,rk3568-bpi-r2pro/etc/factory-config.cfg index 27dbf5d96a..6c9e786451 100644 --- a/board/aarch64/bananapi-bpi-r2-pro/rootfs/usr/share/product/sinovoip,rk3568-bpi-r2pro/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r2-pro/rootfs/usr/share/product/sinovoip,rk3568-bpi-r2pro/etc/factory-config.cfg @@ -231,6 +231,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -394,7 +402,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3/etc/factory-config.cfg index 5cee66d38f..9959413297 100644 --- a/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3/etc/factory-config.cfg @@ -294,6 +294,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -457,7 +465,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3mini/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3mini/etc/factory-config.cfg index 19975fa25b..f81ffe504c 100644 --- a/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3mini/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r3/rootfs/usr/share/product/bananapi,bpi-r3mini/etc/factory-config.cfg @@ -260,6 +260,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -423,7 +431,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4-2g5/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4-2g5/etc/factory-config.cfg index 4f55aee1aa..606fc035d8 100644 --- a/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4-2g5/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4-2g5/etc/factory-config.cfg @@ -224,6 +224,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -387,7 +395,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4/etc/factory-config.cfg index bed49c1bde..7a3b10eb5d 100644 --- a/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r4/rootfs/usr/share/product/bananapi,bpi-r4/etc/factory-config.cfg @@ -216,6 +216,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -379,7 +387,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/bananapi-bpi-r64/rootfs/usr/share/product/bananapi,bpi-r64/etc/factory-config.cfg b/board/aarch64/bananapi-bpi-r64/rootfs/usr/share/product/bananapi,bpi-r64/etc/factory-config.cfg index 407b97cc83..3db962b22d 100644 --- a/board/aarch64/bananapi-bpi-r64/rootfs/usr/share/product/bananapi,bpi-r64/etc/factory-config.cfg +++ b/board/aarch64/bananapi-bpi-r64/rootfs/usr/share/product/bananapi,bpi-r64/etc/factory-config.cfg @@ -260,6 +260,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -423,7 +431,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s-plus/etc/factory-config.cfg b/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s-plus/etc/factory-config.cfg index 3cc6d11eb9..a7efcc84c9 100644 --- a/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s-plus/etc/factory-config.cfg +++ b/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s-plus/etc/factory-config.cfg @@ -207,6 +207,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -370,7 +378,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s/etc/factory-config.cfg b/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s/etc/factory-config.cfg index 3dc5e819fc..b6a91678eb 100644 --- a/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s/etc/factory-config.cfg +++ b/board/aarch64/friendlyarm-nanopi-r2s/rootfs/usr/share/product/friendlyarm,nanopi-r2s/etc/factory-config.cfg @@ -200,6 +200,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -363,7 +371,7 @@ ] }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,4-model-b/etc/factory-config.cfg b/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,4-model-b/etc/factory-config.cfg index e1e0ef46d7..0ca32f37b2 100644 --- a/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,4-model-b/etc/factory-config.cfg +++ b/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,4-model-b/etc/factory-config.cfg @@ -161,6 +161,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -259,7 +267,7 @@ "infix-system:motd-banner": "Li0tLS0tLS0uCnwgIC4gLiAgfCBJbmZpeCBPUyDigJQgSW1tdXRhYmxlLkZyaWVuZGx5LlNlY3VyZQp8LS4gdiAuLXwgaHR0cHM6Ly9rZXJuZWxraXQub3JnCictJy0tLSctJwo=" }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,400/etc/factory-config.cfg b/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,400/etc/factory-config.cfg index 7458acf418..687810f481 100644 --- a/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,400/etc/factory-config.cfg +++ b/board/aarch64/raspberrypi-rpi64/rootfs/usr/share/product/raspberrypi,400/etc/factory-config.cfg @@ -175,6 +175,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -273,7 +281,7 @@ "infix-system:motd-banner": "Li0tLS0tLS0uCnwgIC4gLiAgfCBJbmZpeCBPUyDigJQgSW1tdXRhYmxlLkZyaWVuZGx5LlNlY3VyZQp8LS4gdiAuLXwgaHR0cHM6Ly9rZXJuZWxraXQub3JnCictJy0tLSctJwo=" }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/arm/bananapi-bpi-m1/rootfs/usr/share/product/lemaker,bananapi/etc/factory-config.cfg b/board/arm/bananapi-bpi-m1/rootfs/usr/share/product/lemaker,bananapi/etc/factory-config.cfg index a2f89ec008..d045679f27 100644 --- a/board/arm/bananapi-bpi-m1/rootfs/usr/share/product/lemaker,bananapi/etc/factory-config.cfg +++ b/board/arm/bananapi-bpi-m1/rootfs/usr/share/product/lemaker,bananapi/etc/factory-config.cfg @@ -174,6 +174,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -272,7 +280,7 @@ "infix-system:motd-banner": "Li0tLS0tLS0uCnwgIC4gLiAgfCBJbmZpeCBPUyDigJQgSW1tdXRhYmxlLkZyaWVuZGx5LlNlY3VyZQp8LS4gdiAuLXwgaHR0cHM6Ly9rZXJuZWxraXQub3JnCictJy0tLSctJwo=" }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/arm/raspberrypi-rpi2/rootfs/usr/share/product/raspberrypi,2-model-b/etc/factory-config.cfg b/board/arm/raspberrypi-rpi2/rootfs/usr/share/product/raspberrypi,2-model-b/etc/factory-config.cfg index f3e1673176..67c60baa8b 100644 --- a/board/arm/raspberrypi-rpi2/rootfs/usr/share/product/raspberrypi,2-model-b/etc/factory-config.cfg +++ b/board/arm/raspberrypi-rpi2/rootfs/usr/share/product/raspberrypi,2-model-b/etc/factory-config.cfg @@ -156,6 +156,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -254,7 +262,7 @@ "infix-system:motd-banner": "Li0tLS0tLS0uCnwgIC4gLiAgfCBJbmZpeCBPUyDigJQgSW1tdXRhYmxlLkZyaWVuZGx5LlNlY3VyZQp8LS4gdiAuLXwgaHR0cHM6Ly9rZXJuZWxraXQub3JnCictJy0tLSctJwo=" }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/board/riscv64/bananapi-bpi-f3/rootfs/usr/share/product/bananapi,bpi-f3/etc/factory-config.cfg b/board/riscv64/bananapi-bpi-f3/rootfs/usr/share/product/bananapi,bpi-f3/etc/factory-config.cfg index 0d8a8dc17e..e2dea0a089 100644 --- a/board/riscv64/bananapi-bpi-f3/rootfs/usr/share/product/bananapi,bpi-f3/etc/factory-config.cfg +++ b/board/riscv64/bananapi-bpi-f3/rootfs/usr/share/product/bananapi,bpi-f3/etc/factory-config.cfg @@ -228,6 +228,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -324,7 +332,7 @@ "infix-system:motd-banner": "Li0tLS0tLS0uCnwgIC4gLiAgfCBJbmZpeCBPUyDigJQgSW1tdXRhYmxlLkZyaWVuZGx5LlNlY3VyZQp8LS4gdiAuLXwgaHR0cHM6Ly9rZXJuZWxraXQub3JnCictJy0tLSctJwo=" }, "infix-meta:meta": { - "version": "1.13" + "version": "1.14" }, "infix-services:mdns": { "enabled": true diff --git a/doc/ChangeLog.md b/doc/ChangeLog.md index 6aea9295c0..d2fd4621fd 100644 --- a/doc/ChangeLog.md +++ b/doc/ChangeLog.md @@ -38,6 +38,9 @@ All notable changes to the project are documented in this file. - Wi-Fi: a radio without a band no longer accepts a channel, channel width or legacy rates. They had no effect there and are dropped from the configuration on upgrade +- New `infix-system:whoami` RPC, returns the calling user and the NACM + groups the user is in. Guests are permitted to call it, see [NACM][nacm], + and the rule for that is added to existing configurations on upgrade - WebUI: the Wi-Fi radio forms offer only the bands the radio supports, and the channel is picked from the channels of the selected band. The country code is set in one place on the interfaces page @@ -422,6 +425,7 @@ All notable changes to the project are documented in this file. [gps]: https://www.kernelkit.org/infix/latest/hardware/#anchor-a-gps-receiver-to-a-usb-port [locate]: https://www.kernelkit.org/infix/latest/hardware/#locate [hw]: https://www.kernelkit.org/infix/latest/hardware/#processor +[nacm]: https://www.kernelkit.org/infix/latest/nacm/#example-factory-configuration [ripng]: https://www.kernelkit.org/infix/latest/routing/#ripng-routing [ospfv3]: https://www.kernelkit.org/infix/latest/routing/#ospfv3-routing [fdb]: https://www.kernelkit.org/infix/latest/bridging/#unicast-forwarding-database diff --git a/doc/nacm.md b/doc/nacm.md index 881d144018..e9f178c5d4 100644 --- a/doc/nacm.md +++ b/doc/nacm.md @@ -271,7 +271,7 @@ rule matches. ## Example: Factory Configuration The factory configuration permits by default and denies the sensitive -items, with six rules in total: +items, with seven rules in total: ```json { @@ -319,6 +319,14 @@ items, with six rules in total: "name": "guest-acl", "group": ["guest"], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in" + }, { "name": "deny-all-write+exec", "module-name": "*", @@ -368,13 +376,19 @@ and truststore are denied for everyone else through the `"*"` group. Factory reset and software upgrade are not mentioned at all, their YANG annotations keep them admin-only. +Guests are denied all RPCs but one. The `infix-system:whoami` RPC +returns the name of the calling user and the groups that user is in. +Only an admin can read the NACM configuration, so this is how any other +user, or an application acting for that user, learns its own groups. +The permit rule must come before the deny, the first match wins. + The resulting permissions per group: | Group | Read | Write | Exec | Exceptions | |----------|------|-------|------|-----------------------------------------------| | admin | All | All | All | None | | operator | All | All | All | Cannot access passwords, keystore, truststore | -| guest | All | None | None | Read-only access | +| guest | All | None | None | Read-only access, may call `whoami` | ## Common Patterns diff --git a/src/confd/configure.ac b/src/confd/configure.ac index 5a1ada679d..7fe453f34c 100644 --- a/src/confd/configure.ac +++ b/src/confd/configure.ac @@ -1,6 +1,6 @@ AC_PREREQ(2.61) # confd version is same as system YANG model version, step on breaking changes -AC_INIT([confd], [1.13], [https://github.com/kernelkit/infix/issues]) +AC_INIT([confd], [1.14], [https://github.com/kernelkit/infix/issues]) AM_INIT_AUTOMAKE(1.11 foreign subdir-objects) AM_SILENT_RULES(yes) @@ -27,6 +27,7 @@ AC_CONFIG_FILES([ share/migrate/1.11/Makefile share/migrate/1.12/Makefile share/migrate/1.13/Makefile + share/migrate/1.14/Makefile yang/Makefile yang/confd/Makefile yang/test-mode/Makefile diff --git a/src/confd/share/factory.d/10-nacm.json b/src/confd/share/factory.d/10-nacm.json index 017c78cb37..2b38cc645b 100644 --- a/src/confd/share/factory.d/10-nacm.json +++ b/src/confd/share/factory.d/10-nacm.json @@ -60,6 +60,14 @@ "guest" ], "rule": [ + { + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }, { "name": "deny-all-write+exec", "module-name": "*", diff --git a/src/confd/share/migrate/1.14/10-nacm-permit-whoami.sh b/src/confd/share/migrate/1.14/10-nacm-permit-whoami.sh new file mode 100755 index 0000000000..903db88732 --- /dev/null +++ b/src/confd/share/migrate/1.14/10-nacm-permit-whoami.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# The whoami RPC tells a user its own NACM groups. Permit it ahead of +# the rules in every rule-list that denies exec for all modules, e.g. +# the factory guest-acl, or for infix-system. + +file=$1 +temp=${file}.tmp + +jq ' + def denies_exec: + .action == "deny" + and ((.["module-name"] // "*") | . == "*" or . == "infix-system") + and (has("path") or has("rpc-name") or has("notification-name") | not) + and ((.["access-operations"] // "*") | . == "*" or (split(" ") | index("exec") != null)); + + if .["ietf-netconf-acm:nacm"]?["rule-list"]? then + .["ietf-netconf-acm:nacm"]["rule-list"] |= map( + (.rule // []) as $rules | + if ($rules | any(denies_exec)) and ($rules | any(.name == "permit-whoami") | not) then + .rule = [{ + "name": "permit-whoami", + "module-name": "infix-system", + "rpc-name": "whoami", + "access-operations": "exec", + "action": "permit", + "comment": "Guests can ask who they are and what groups they are in." + }] + $rules + else . end) + else . end +' "$file" > "$temp" && mv "$temp" "$file" diff --git a/src/confd/share/migrate/1.14/Makefile.am b/src/confd/share/migrate/1.14/Makefile.am new file mode 100644 index 0000000000..bcf551e405 --- /dev/null +++ b/src/confd/share/migrate/1.14/Makefile.am @@ -0,0 +1,2 @@ +migratedir = $(pkgdatadir)/migrate/1.14 +dist_migrate_DATA = 10-nacm-permit-whoami.sh diff --git a/src/confd/share/migrate/Makefile.am b/src/confd/share/migrate/Makefile.am index d53bb0d19b..d5950bd46a 100644 --- a/src/confd/share/migrate/Makefile.am +++ b/src/confd/share/migrate/Makefile.am @@ -1,2 +1,2 @@ -SUBDIRS = 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 +SUBDIRS = 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 1.10 1.11 1.12 1.13 1.14 migratedir = $(pkgdatadir)/migrate diff --git a/src/confd/src/syslog.c b/src/confd/src/syslog.c index f964ed0d02..760025a8a5 100644 --- a/src/confd/src/syslog.c +++ b/src/confd/src/syslog.c @@ -510,9 +510,9 @@ static int log_severity(const char *name) /* * The event session runs as confd, so its own user says nothing about the * caller. Only the originator crosses over: netopeer2 pushes [nc-sid, - * username], the CLI and the rpc tool set their originator name to the - * user. RESTCONF sets neither, then the tag is left at NILVALUE rather - * than naming root, or confd, which libsyslog would fall back to. + * username], RESTCONF, the CLI and the rpc tool set their originator + * name to the user. A session with neither leaves the tag at NILVALUE + * rather than naming root, or confd, which libsyslog would fall back to. */ static const char *log_user(sr_session_ctx_t *session) { diff --git a/src/confd/src/system.c b/src/confd/src/system.c index 57625af7cb..c85e6fc38e 100644 --- a/src/confd/src/system.c +++ b/src/confd/src/system.c @@ -1919,6 +1919,45 @@ int system_change(sr_session_ctx_t *session, struct lyd_node *config, struct lyd return SR_ERR_OK; } +/* '/infix-system:whoami' */ +static int rpc_whoami(sr_session_ctx_t *session, uint32_t sub_id, const char *path, + const struct lyd_node *input, sr_event_t event, uint32_t request_id, + struct lyd_node *output, void *priv) +{ + const char *via, *user = rpc_user(session, &via) ?: via; + sr_session_ctx_t *cfg; + sr_val_t *groups = NULL; + size_t cnt = 0; + int rc; + + if (!is_valid_username(user)) + return rpc_failed(session, "Cannot tell who is calling"); + + if (lyd_new_term(output, NULL, "username", user, LYD_NEW_VAL_OUTPUT, NULL)) + return SR_ERR_INTERNAL; + + if (sr_session_start(sr_session_get_connection(session), SR_DS_RUNNING, &cfg)) + return SR_ERR_INTERNAL; + + rc = srx_get_items(cfg, &groups, &cnt, NACM_BASE_"/groups/group[user-name='%s']/name", user); + sr_session_stop(cfg); + if (rc == SR_ERR_NOT_FOUND) + rc = SR_ERR_OK; + if (rc) + return rc; + + for (size_t i = 0; i < cnt; i++) { + if (lyd_new_term(output, NULL, "group", groups[i].data.string_val, + LYD_NEW_VAL_OUTPUT, NULL)) { + rc = SR_ERR_INTERNAL; + break; + } + } + sr_free_values(groups, cnt); + + return rc; +} + int system_rpc_init(struct confd *confd) { int rc; @@ -1929,6 +1968,7 @@ int system_rpc_init(struct confd *confd) REGISTER_RPC(confd->session, "/ietf-system:system-restart", rpc_exec, "reboot", &confd->sub); REGISTER_RPC(confd->session, "/ietf-system:system-shutdown", rpc_exec, "poweroff", &confd->sub); REGISTER_RPC(confd->session, "/ietf-system:set-current-datetime", rpc_set_datetime, NULL, &confd->sub); + REGISTER_RPC_TREE(confd->session, "/infix-system:whoami", rpc_whoami, NULL, &confd->sub); return SR_ERR_OK; fail: diff --git a/src/confd/yang/confd/infix-system.yang b/src/confd/yang/confd/infix-system.yang index c07214cf37..4ed0497526 100644 --- a/src/confd/yang/confd/infix-system.yang +++ b/src/confd/yang/confd/infix-system.yang @@ -39,7 +39,8 @@ module infix-system { description "Infix augments and deviations to ietf-system."; revision 2026-11-09 { - description "Explain a rejected hostname in words instead of the pattern."; + description "Explain a rejected hostname in words instead of the pattern. + Add the whoami RPC."; reference "internal"; } @@ -954,6 +955,25 @@ module infix-system { } } + rpc whoami { + description + "Show the calling user and the NACM groups the user is in. + + Only the groups in the NACM configuration are listed. A user + that is not allowed to read that configuration can still learn + its own groups this way, but nothing about other users."; + output { + leaf username { + type infix-sys:username; + description "Name of the calling user."; + } + leaf-list group { + type nacm:group-name-type; + description "NACM group the user is a member of."; + } + } + } + rpc support-collect { nacm:default-deny-all; description diff --git a/test/case/syslog/rpc_log/test.py b/test/case/syslog/rpc_log/test.py index a58f44328b..6a045ebd95 100755 --- a/test/case/syslog/rpc_log/test.py +++ b/test/case/syslog/rpc_log/test.py @@ -78,8 +78,8 @@ def logfile(): match = re.search(r" (\S+) - - - Plain message, no frills$", line) if not match: test.fail(f"Unexpected header for default message: {line}") - # NETCONF carries the user, RESTCONF carries no caller identity at - # all, and then the tag must stay nil rather than name a daemon. + # NETCONF and RESTCONF both carry the user, the tag must never + # name a daemon. if match.group(1) in ("root", "confd"): test.fail(f"Default app-name claims a system identity: {line}") diff --git a/test/case/system/Readme.adoc b/test/case/system/Readme.adoc index 8006bf7273..42e1a8f606 100644 --- a/test/case/system/Readme.adoc +++ b/test/case/system/Readme.adoc @@ -27,6 +27,10 @@ include::nacm-basic/Readme.adoc[] <<< +include::whoami/Readme.adoc[] + +<<< + include::timezone/Readme.adoc[] <<< diff --git a/test/case/system/all.yaml b/test/case/system/all.yaml index 0f59aa1941..b75ae4f59b 100644 --- a/test/case/system/all.yaml +++ b/test/case/system/all.yaml @@ -11,6 +11,9 @@ - name: Basic NACM Permissions case: nacm-basic/test.py +- name: Who Am I + case: whoami/test.py + - name: Set Timezone Using Timezone Name case: timezone/test.py diff --git a/test/case/system/whoami/Readme.adoc b/test/case/system/whoami/Readme.adoc new file mode 120000 index 0000000000..ae32c84120 --- /dev/null +++ b/test/case/system/whoami/Readme.adoc @@ -0,0 +1 @@ +test.adoc \ No newline at end of file diff --git a/test/case/system/whoami/test.adoc b/test/case/system/whoami/test.adoc new file mode 100644 index 0000000000..4553eba9af --- /dev/null +++ b/test/case/system/whoami/test.adoc @@ -0,0 +1,24 @@ +=== Who Am I + +ifdef::topdoc[:imagesdir: {topdoc}../../test/case/system/whoami] + +==== Description + +Verify the infix-system:whoami RPC. It returns the name of the calling +user and the NACM groups that user is a member of. The factory NACM +rules deny guests all RPCs but this one, since a guest cannot read the +NACM configuration to find out. + +==== Topology + +image::topology.svg[Who Am I topology, align=center, scaledwidth=75%] + +==== Sequence + +. Set up topology and attach to target DUT +. Add user jane to NACM groups guest and operator +. Verify whoami as admin returns admin, in group admin +. Verify whoami as jane returns jane, in groups guest and operator +. Verify jane cannot read the NACM groups + + diff --git a/test/case/system/whoami/test.py b/test/case/system/whoami/test.py new file mode 100755 index 0000000000..d047efdd8c --- /dev/null +++ b/test/case/system/whoami/test.py @@ -0,0 +1,72 @@ +#!/usr/bin/env python3 +"""Who Am I + +Verify the infix-system:whoami RPC. It returns the name of the calling +user and the NACM groups that user is a member of. The factory NACM +rules deny guests all RPCs but this one, since a guest cannot read the +NACM configuration to find out. +""" +import infamy + +USER = "jane" +PASS = "guest123" +HASH = "$1$4rdUOhNN$vw3i4FyPvIkzRFwrUXQod1" + + +def whoami(target): + """Call whoami, return username and the groups as a sorted list""" + out = target.rpc_output("infix-system", "whoami") + + return out.get("username"), sorted(out.get("group", [])) + + +with infamy.Test() as test: + with test.step("Set up topology and attach to target DUT"): + env = infamy.Env() + target = env.attach("target", "mgmt") + + with test.step("Add user jane to NACM groups guest and operator"): + target.put_config_dicts({ + "ietf-system": { + "system": { + "authentication": { + "user": [{ + "name": USER, + "password": HASH, + "shell": "infix-system:bash" + }] + } + } + }, + "ietf-netconf-acm": { + "nacm": { + "groups": { + "group": [{ + "name": "guest", + "user-name": [USER] + }, { + "name": "operator", + "user-name": [USER] + }] + } + } + } + }) + + with test.step("Verify whoami as admin returns admin, in group admin"): + user, groups = whoami(target) + assert user == "admin", f"Unexpected username: {user}" + assert groups == ["admin"], f"Unexpected groups: {groups}" + + with test.step("Verify whoami as jane returns jane, in groups guest and operator"): + jane = env.attach("target", "mgmt", username=USER, password=PASS, + test_reset=False) + user, groups = whoami(jane) + assert user == USER, f"Unexpected username: {user}" + assert groups == ["guest", "operator"], f"Unexpected groups: {groups}" + + with test.step("Verify jane cannot read the NACM groups"): + cfg = jane.get_config_dict("/ietf-netconf-acm:nacm") + assert not cfg, f"Guest can read the NACM configuration: {cfg}" + + test.succeed() diff --git a/test/case/system/whoami/topology.dot b/test/case/system/whoami/topology.dot new file mode 120000 index 0000000000..02b788692c --- /dev/null +++ b/test/case/system/whoami/topology.dot @@ -0,0 +1 @@ +../../../infamy/topologies/1x1.dot \ No newline at end of file diff --git a/test/case/system/whoami/topology.svg b/test/case/system/whoami/topology.svg new file mode 100644 index 0000000000..6fc6f47a8e --- /dev/null +++ b/test/case/system/whoami/topology.svg @@ -0,0 +1,33 @@ + + + + + + +1x1 + + + +host + +host + +mgmt + + + +target + +mgmt + +target + + + +host:mgmt--target:mgmt + + + + diff --git a/test/infamy/netconf.py b/test/infamy/netconf.py index 1bee1193b5..68cf1fcf09 100644 --- a/test/infamy/netconf.py +++ b/test/infamy/netconf.py @@ -457,18 +457,25 @@ def call_dict(self, modname, call): return self.call(lyd.print_mem("xml", with_siblings=True, pretty=False)) def rpc_output(self, module, rpc, input_data=None): - """Call RPC, returning output leaves as a dict of strings""" + """Call RPC, returning output leaves as a dict of strings, lists for leaf-lists""" reply = self.call_dict(module, {rpc: input_data or {}}) xml = reply.xml if isinstance(xml, str): xml = xml.encode() + schema = next(self.ly.find_path(f"/{module}:{rpc}")) + lists = {c.name() for c in schema.output() + if isinstance(c, libyang.schema.SLeafList)} + output = {} for node in fromstring(xml).iter(): if len(node) or not node.text: continue leaf = lxml.etree.QName(node).localname - output[leaf] = node.text.strip() + if leaf in lists: + output.setdefault(leaf, []).append(node.text.strip()) + else: + output[leaf] = node.text.strip() return output diff --git a/test/infamy/restconf.py b/test/infamy/restconf.py index 02f47100bb..c953862bcd 100644 --- a/test/infamy/restconf.py +++ b/test/infamy/restconf.py @@ -467,7 +467,7 @@ def call_rpc(self, rpc): response.raise_for_status() # Raise an exception for HTTP errors def rpc_output(self, module, rpc, input_data=None): - """Call RPC, returning output leaves as a dict of strings""" + """Call RPC, returning output leaves as a dict of strings, lists for leaf-lists""" coverage.track_dict(module, {rpc: input_data or {}}) url = f"{self.rpc_url}/{module}:{rpc}" body = {f"{module}:input": input_data} if input_data else None @@ -490,7 +490,8 @@ def rpc_output(self, module, rpc, input_data=None): data = response.json() output = data.get(f"{module}:output", data) - return {k: str(v) for k, v in output.items()} + return {k: [str(e) for e in v] if isinstance(v, list) else str(v) + for k, v in output.items()} def get_dict(self, xpath=None, parse=True): """NETCONF compat function, just wraps get_data""" From 2009ac8b9c5e70b21088d98834a895bd2dab8f12 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Mon, 23 Nov 2026 17:27:50 +0100 Subject: [PATCH 4/5] webui: look up the NACM groups of a user with the whoami RPC The groups behind a @group entry in WEBUI_HOME were read with sysrepocfg, as root. That goes around NACM and stops working the day the WebUI runs as an unprivileged user. Ask for them over RESTCONF as the user logging in, like everything else. The NACM rules must permit the members of a listed group to call whoami, as the factory rules do for guest. Signed-off-by: Joachim Wiberg --- src/webui/README.md | 4 +++ src/webui/internal/auth/home.go | 4 +-- src/webui/internal/auth/home_test.go | 13 +++---- src/webui/internal/auth/login.go | 6 ++-- src/webui/internal/handlers/nacm.go | 42 ++++++---------------- src/webui/internal/handlers/nacm_test.go | 44 ++++++++++++++++-------- 6 files changed, 57 insertions(+), 56 deletions(-) diff --git a/src/webui/README.md b/src/webui/README.md index 90a5708a3f..25d506c30c 100644 --- a/src/webui/README.md +++ b/src/webui/README.md @@ -83,6 +83,10 @@ A group entry never applies to an administrator, i.e. a user allowed to read the NACM configuration. Group membership is read at login, so a change takes effect the next time the user logs in. +The groups come from the `infix-system:whoami` RPC, called as the user. +The NACM rules must permit the members of a listed group to call it, +like the factory rules do for `guest`, otherwise their login is refused. + The page uses the same login as the WebUI, and two endpoints: | **Endpoint** | **Use** | diff --git a/src/webui/internal/auth/home.go b/src/webui/internal/auth/home.go index a8e0217d39..818530888c 100644 --- a/src/webui/internal/auth/home.go +++ b/src/webui/internal/auth/home.go @@ -46,11 +46,11 @@ func ParseHomes(v string) Homes { // It never does for an admin, who could not get back to the regular // pages to leave the group. func (h Homes) Resolve(ctx context.Context, user string, admin bool, - lookup func(context.Context, string) ([]string, error)) (string, error) { + lookup func(context.Context) ([]string, error)) (string, error) { if home := h.users[user]; home != "" || admin || len(h.groups) == 0 { return home, nil } - groups, err := lookup(ctx, user) + groups, err := lookup(ctx) if err != nil { return "", err } diff --git a/src/webui/internal/auth/home_test.go b/src/webui/internal/auth/home_test.go index 3e47294bdc..e2239336fb 100644 --- a/src/webui/internal/auth/home_test.go +++ b/src/webui/internal/auth/home_test.go @@ -30,11 +30,11 @@ func TestHomesResolve(t *testing.T) { "op": {"guest"}, "admin": {"admin", "guest"}, } - lookups := 0 - lookup := func(_ context.Context, user string) ([]string, error) { + lookups, user := 0, "" + lookup := func(context.Context) ([]string, error) { lookups++ if user == "broken" { - return nil, errors.New("no sysrepo") + return nil, errors.New("denied") } return members[user], nil } @@ -55,7 +55,7 @@ func TestHomesResolve(t *testing.T) { {"op", true, "/op/", 0}, {"admin", true, "", 0}, } { - lookups = 0 + lookups, user = 0, tc.user got, err := h.Resolve(context.Background(), tc.user, tc.admin, lookup) if err != nil || got != tc.want || lookups != tc.lookups { t.Errorf("%s: got %q, %v after %d lookups, want %q after %d", @@ -63,11 +63,12 @@ func TestHomesResolve(t *testing.T) { } } - if _, err := h.Resolve(context.Background(), "broken", false, lookup); err == nil { + user = "broken" + if _, err := h.Resolve(context.Background(), user, false, lookup); err == nil { t.Error("failed group lookup: no error") } - lookups = 0 + lookups, user = 0, "jane" got, err := ParseHomes("op=/op/").Resolve(context.Background(), "jane", false, lookup) if err != nil || got != "" || lookups != 0 { t.Errorf("no group homes: got %q, %v after %d lookups", got, err, lookups) diff --git a/src/webui/internal/auth/login.go b/src/webui/internal/auth/login.go index e8b25e0d49..0dab6af5e7 100644 --- a/src/webui/internal/auth/login.go +++ b/src/webui/internal/auth/login.go @@ -91,9 +91,11 @@ func (h *LoginHandler) DoLogin(w http.ResponseWriter, r *http.Request) { admin := handlers.DetectNACMAccess(ctx, h.RC) caps.Features()["nacm"] = admin - home, err := h.Homes.Resolve(ctx, username, admin, handlers.NACMGroups) + home, err := h.Homes.Resolve(ctx, username, admin, func(ctx context.Context) ([]string, error) { + return handlers.WhoamiGroups(ctx, h.RC) + }) if err != nil { - log.Printf("login refused for %q, cannot read NACM groups: %v", username, err) + log.Printf("login refused for %q, cannot look up its NACM groups: %v", username, err) h.renderLogin(w, r, "Unable to reach the device. Please try again later.") return } diff --git a/src/webui/internal/handlers/nacm.go b/src/webui/internal/handlers/nacm.go index c3792a3d7f..ed1537c2aa 100644 --- a/src/webui/internal/handlers/nacm.go +++ b/src/webui/internal/handlers/nacm.go @@ -3,16 +3,11 @@ package handlers import ( - "bytes" "context" - "encoding/json" "html/template" "log" "net/http" - "os/exec" - "slices" "strings" - "time" "infix/webui/internal/restconf" ) @@ -44,35 +39,18 @@ type nacmGroupJSON struct { UserNames []string `json:"user-name"` } -// NACMGroups returns the NACM groups user is a member of. It reads -// straight from sysrepo, outside NACM: only an admin may read the NACM -// data over RESTCONF. -func NACMGroups(ctx context.Context, user string) ([]string, error) { - ctx, cancel := context.WithTimeout(ctx, 10*time.Second) - defer cancel() - out, err := exec.CommandContext(ctx, "sysrepocfg", "-X", "-d", "running", "-f", "json", - "-x", "/ietf-netconf-acm:nacm/groups").Output() - if err != nil { - return nil, err +// WhoamiGroups returns the NACM groups of the user behind ctx, who need +// not be allowed to read the NACM data. +func WhoamiGroups(ctx context.Context, rc restconf.Fetcher) ([]string, error) { + var reply struct { + Output struct { + Groups []string `json:"group"` + } `json:"infix-system:output"` } - return nacmGroupsOf(out, user) -} - -func nacmGroupsOf(data []byte, user string) ([]string, error) { - var raw nacmWrapper - // No groups at all comes back as no output - if len(bytes.TrimSpace(data)) > 0 { - if err := json.Unmarshal(data, &raw); err != nil { - return nil, err - } - } - var groups []string - for _, g := range raw.NACM.Groups.Group { - if slices.Contains(g.UserNames, user) { - groups = append(groups, g.Name) - } + if err := rc.CallRPC(ctx, "/operations/infix-system:whoami", nil, &reply); err != nil { + return nil, err } - return groups, nil + return reply.Output.Groups, nil } type nacmRuleListJSON struct { diff --git a/src/webui/internal/handlers/nacm_test.go b/src/webui/internal/handlers/nacm_test.go index 3b4c21a068..690c6c526c 100644 --- a/src/webui/internal/handlers/nacm_test.go +++ b/src/webui/internal/handlers/nacm_test.go @@ -2,23 +2,39 @@ package handlers -import "testing" +import ( + "context" + "errors" + "slices" + "testing" -func TestNACMGroupsOf(t *testing.T) { - data := []byte(`{"ietf-netconf-acm:nacm":{"groups":{"group":[ - {"name":"admin","user-name":["admin"]}, - {"name":"guest","user-name":["jane","joe"]}, - {"name":"empty"}, - {"name":"service","user-name":["jane"]}]}}}`) + "infix/webui/internal/testutil" +) - got, err := nacmGroupsOf(data, "jane") - if err != nil || len(got) != 2 || got[0] != "guest" || got[1] != "service" { - t.Errorf("jane: got %v, %v", got, err) +func TestWhoamiGroups(t *testing.T) { + const path = "/operations/infix-system:whoami" + + rc := testutil.NewMockFetcher() + rc.SetResponse(path, map[string]any{ + "infix-system:output": map[string]any{ + "username": "jane", + "group": []string{"guest", "service"}, + }, + }) + got, err := WhoamiGroups(context.Background(), rc) + if err != nil || !slices.Equal(got, []string{"guest", "service"}) { + t.Errorf("got %v, %v", got, err) } - if got, err := nacmGroupsOf(nil, "jane"); err != nil || len(got) != 0 { - t.Errorf("no data: got %v, %v", got, err) + + rc.SetResponse(path, map[string]any{ + "infix-system:output": map[string]any{"username": "jane"}, + }) + if got, err := WhoamiGroups(context.Background(), rc); err != nil || len(got) != 0 { + t.Errorf("no groups: got %v, %v", got, err) } - if _, err := nacmGroupsOf([]byte("{"), "jane"); err == nil { - t.Error("bad data: no error") + + rc.SetError(path, errors.New("access denied")) + if _, err := WhoamiGroups(context.Background(), rc); err == nil { + t.Error("denied: no error") } } From 251e7bb5e94ef2427f6dd99355d267318a25fb40 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Mon, 23 Nov 2026 19:46:53 +0100 Subject: [PATCH 5/5] fixup! confd: add whoami RPC, for a user to learn its own NACM groups Signed-off-by: Joachim Wiberg --- test/infamy/netconf.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/infamy/netconf.py b/test/infamy/netconf.py index 68cf1fcf09..5bc70b27c7 100644 --- a/test/infamy/netconf.py +++ b/test/infamy/netconf.py @@ -344,7 +344,8 @@ def get_factory(self, xpath=None): def get_config_dict(self, xpath): """Get Python dictionary version of XML configuration""" - return self.get_config(xpath).print_dict() + cfg = self.get_config(xpath) + return cfg.print_dict() if cfg else None def put_config(self, edit, retries=3): """Send XML configuration over NETCONF"""