From edd99ca05d7b31b427261d6fb761190fa26b0591 Mon Sep 17 00:00:00 2001 From: doxuta Date: Thu, 22 Oct 2026 12:09:49 +0700 Subject: [PATCH 1/9] perf(ai): propose_access asks only for the admins holding the roles it names (#23) ListUsers loaded every user of the tenant on each call to find whether an admin or a platform operator holds the role. UserRepository.PrivilegedHolders asks tenant_id = ? AND role_id IN (...) AND (is_admin OR is_platform_operator), once per call, for the roles the call names. Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/ai/tools.go | 5 +- nexus-platform/internal/ai/tools_access.go | 17 ++++- .../internal/ai/tools_access_test.go | 17 +++++ .../internal/ai/tools_explain_access_test.go | 17 ++++- ...ser_privileged_holders_integration_test.go | 65 +++++++++++++++++++ .../internal/auth/user_repository_crud.go | 18 +++++ 6 files changed, 132 insertions(+), 7 deletions(-) create mode 100644 nexus-platform/internal/auth/user_privileged_holders_integration_test.go diff --git a/nexus-platform/internal/ai/tools.go b/nexus-platform/internal/ai/tools.go index 11e8828..03357f8 100644 --- a/nexus-platform/internal/ai/tools.go +++ b/nexus-platform/internal/ai/tools.go @@ -3104,8 +3104,9 @@ func (e *toolExecutor) proposeWorkQueue(ctx context.Context, argsJSON string) st type accessUserLookup interface { GetUserByEmail(ctx context.Context, tenantID, email string) (*auth.User, error) GetUserByID(ctx context.Context, tenantID, id string) (*auth.User, error) - // ListUsers backs propose_access: never a role an admin or a platform operator holds. - ListUsers(ctx context.Context, tenantID string) ([]auth.User, error) + // PrivilegedHolders backs propose_access: the admins and platform operators holding one of + // roleIDs (never a role one of them holds), not every user of the tenant (issue #23). + PrivilegedHolders(ctx context.Context, tenantID string, roleIDs []string) ([]auth.User, error) } type accessRoleLookup interface { diff --git a/nexus-platform/internal/ai/tools_access.go b/nexus-platform/internal/ai/tools_access.go index 40cf786..0a78a44 100644 --- a/nexus-platform/internal/ai/tools_access.go +++ b/nexus-platform/internal/ai/tools_access.go @@ -103,7 +103,19 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin if err != nil { return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } - users, err := probes.Users.ListUsers(ctx, e.tenantID) + // One query for the admins and operators holding a role this call names (issue #23): a refused + // grant is still judged in order below, so a role that does not resolve is simply not asked about. + var named []string + for _, g := range raw { + var ref string + if json.Unmarshal(g["role"], &ref) != nil { + continue // not a string: refused as INVALID_ARGS below + } + if r, msg := resolveAccessRole(roles, ref, 0); msg == "" { + named = append(named, r.ID) + } + } + users, err := probes.Users.PrivilegedHolders(ctx, e.tenantID, named) if err != nil { return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } @@ -239,7 +251,8 @@ func resolveAccessRole(roles []auth.Role, ref string, n int) (auth.Role, string) } // privilegedHolder says who makes the role privileged ("" = nobody): an admin or a platform operator -// holding it. They bypass access control anyway, and the assistant stays off their roles. +// holding it (users = PrivilegedHolders). They bypass access control anyway, and the assistant stays +// off their roles. func privilegedHolder(users []auth.User, roleID string) string { for _, u := range users { if u.RoleID == nil || *u.RoleID != roleID { diff --git a/nexus-platform/internal/ai/tools_access_test.go b/nexus-platform/internal/ai/tools_access_test.go index 1b66e9a..2f2b54f 100644 --- a/nexus-platform/internal/ai/tools_access_test.go +++ b/nexus-platform/internal/ai/tools_access_test.go @@ -152,6 +152,23 @@ func TestProposeAccess_BuffersOneCardPerRoleWithTheRoleChange(t *testing.T) { } } +// Issue #23: the admin check asks for the holders of the roles this call names, in this tenant, once +// — not for every user of the tenant. +func TestProposeAccess_AsksOnlyAboutTheNamedRoles(t *testing.T) { + e := withTickets(t, accessExecutor(fakeCutoff{at: &accCutoff})) + users := e.reader.(AccessProbeCarrier).AccessProbes().Users.(*fakeAccessUsers) + mustBuffer(t, e, "propose_access", grantArgs(grant("crm_sales_rep", "tickets", "all", "view"), grant("Xem tất cả", "tickets", "owner", "edit"))) + if len(users.asked) != 1 || !slices.Equal(users.asked[0], []string{"r-rep", "r-star"}) { + t.Fatalf("PrivilegedHolders asked %v; want one call for [r-rep r-star]", users.asked) + } + // A role that does not resolve is not asked about; the call is still refused for it, in order. + users.asked = nil + mustReject(t, e, "propose_access", grantArgs(grant("nobody", "tickets", "all", "view"), grant("crm_sales_manager", "tickets", "all", "view")), "ACCESS_ROLE_NOT_FOUND") + if len(users.asked) != 1 || !slices.Equal(users.asked[0], []string{"r-mgr"}) { + t.Fatalf("PrivilegedHolders asked %v; want [r-mgr]", users.asked) + } +} + func TestProposeAccess_RoleByLabelAndTablesNotYetPublished(t *testing.T) { // The builder says the label; the table was born after the last publish (still hidden). e := accessExecutor(fakeCutoff{at: &accCutoff}) diff --git a/nexus-platform/internal/ai/tools_explain_access_test.go b/nexus-platform/internal/ai/tools_explain_access_test.go index 0b8d5fd..8ab752e 100644 --- a/nexus-platform/internal/ai/tools_explain_access_test.go +++ b/nexus-platform/internal/ai/tools_explain_access_test.go @@ -8,6 +8,7 @@ package ai import ( "context" "encoding/json" + "slices" "strings" "testing" @@ -18,11 +19,21 @@ import ( type fakeAccessUsers struct { byKey map[string]*auth.User // key: tenantID+"/"+email or +id - byTenant map[string][]auth.User // ListUsers (propose_access) + byTenant map[string][]auth.User // PrivilegedHolders (propose_access) + asked [][]string // the roleIDs of each PrivilegedHolders call } -func (f *fakeAccessUsers) ListUsers(_ context.Context, tenantID string) ([]auth.User, error) { - return f.byTenant[tenantID], nil +// PrivilegedHolders filters as the SQL does (tenant, role in roleIDs, admin or operator) and records +// which roles were asked about. +func (f *fakeAccessUsers) PrivilegedHolders(_ context.Context, tenantID string, roleIDs []string) ([]auth.User, error) { + f.asked = append(f.asked, roleIDs) + var out []auth.User + for _, u := range f.byTenant[tenantID] { + if u.RoleID != nil && slices.Contains(roleIDs, *u.RoleID) && (u.IsAdmin || u.IsPlatformOperator) { + out = append(out, u) + } + } + return out, nil } func (f *fakeAccessUsers) GetUserByEmail(_ context.Context, tenantID, email string) (*auth.User, error) { diff --git a/nexus-platform/internal/auth/user_privileged_holders_integration_test.go b/nexus-platform/internal/auth/user_privileged_holders_integration_test.go new file mode 100644 index 0000000..346a1b3 --- /dev/null +++ b/nexus-platform/internal/auth/user_privileged_holders_integration_test.go @@ -0,0 +1,65 @@ +//go:build integration + +// UserRepository.PrivilegedHolders against a real MySQL (issue #23): propose_access asks only for the +// admins and platform operators holding the roles it names, never every user of the tenant. +// +// bash scripts/run-integration.sh -run 'TestPrivilegedHolders_' ./internal/auth/ +package auth + +import ( + "context" + "slices" + "testing" + + "github.com/google/uuid" +) + +func TestPrivilegedHolders_OnlyAdminsAndOperatorsOfTheNamedRolesInTheTenant(t *testing.T) { + ctx := context.Background() + f := manageSetup(t) + role := func(tenant, name string) string { + t.Helper() + id := uuid.NewString() + if err := f.db.Exec(`INSERT INTO acl_roles (id, tenant_id, name, label) VALUES (?, ?, ?, ?)`, id, tenant, name, name).Error; err != nil { + t.Fatalf("seed role %s: %v", name, err) + } + return id + } + holder := func(tenant, roleID, label string, admin, operator bool) string { + t.Helper() + id := uuid.NewString() + f.seed(t, tenant, id, label, "active", admin, false, operator) + if err := f.db.Exec(`UPDATE users SET role_id = ? WHERE id = ?`, roleID, id).Error; err != nil { + t.Fatalf("give %s the role: %v", label, err) + } + return id + } + asked, other, unnamed := role(f.tenant, "ph_asked"), role(f.tenant, "ph_other"), role(f.tenant, "ph_unnamed") + admin := holder(f.tenant, asked, "admin", true, false) + operator := holder(f.tenant, other, "operator", false, true) + holder(f.tenant, asked, "staff", false, false) // holds a named role, but is neither + holder(f.tenant, unnamed, "admin2", true, false) // an admin of a role nobody asked about + holder(f.other, asked, "foreign", true, false) // another tenant's admin carrying this role id + gone := holder(f.tenant, asked, "gone", true, false) // soft-deleted + if err := f.db.Exec(`UPDATE users SET deleted_at = NOW() WHERE id = ?`, gone).Error; err != nil { + t.Fatal(err) + } + + got, err := f.repo.PrivilegedHolders(ctx, f.tenant, []string{asked, other}) + if err != nil { + t.Fatalf("PrivilegedHolders: %v", err) + } + ids := make([]string, len(got)) + for i, u := range got { + ids[i] = u.ID + } + want := []string{admin, operator} + slices.Sort(ids) + slices.Sort(want) + if !slices.Equal(ids, want) { + t.Fatalf("holders = %v; want only the admin and the operator of the two named roles in this tenant %v", ids, want) + } + if none, err := f.repo.PrivilegedHolders(ctx, f.tenant, nil); err != nil || none != nil { + t.Fatalf("no roles = %v, %v; want nil without a query", none, err) + } +} diff --git a/nexus-platform/internal/auth/user_repository_crud.go b/nexus-platform/internal/auth/user_repository_crud.go index 2672537..9f1b278 100644 --- a/nexus-platform/internal/auth/user_repository_crud.go +++ b/nexus-platform/internal/auth/user_repository_crud.go @@ -70,6 +70,24 @@ func (r *UserRepository) ListUsers(ctx context.Context, tenantID string) ([]User return users, nil } +// PrivilegedHolders returns the tenant's admins and platform operators who hold one of roleIDs: +// the only users propose_access asks about (issue #23), instead of every user of the tenant. +// Pinned to tenant_id; an empty roleIDs is (nil, nil) without a query. +func (r *UserRepository) PrivilegedHolders(ctx context.Context, tenantID string, roleIDs []string) ([]User, error) { + if len(roleIDs) == 0 { + return nil, nil + } + var users []User + err := r.db.WithContext(ctx). + Where("tenant_id = ? AND role_id IN ? AND (is_admin = ? OR is_platform_operator = ?)", tenantID, roleIDs, true, true). + Order("created_at ASC, id ASC"). + Find(&users).Error + if err != nil { + return nil, fmt.Errorf("auth.UserRepository.PrivilegedHolders: %w", err) + } + return users, nil +} + // CreateUser inserts u (which must already carry a server-derived ID and TenantID). A // duplicate (tenant_id, email) is reported as ErrUserAlreadyExists; any other failure is // wrapped. The caller is responsible for hashing the password before this runs — the repo From 8b186086bee295ab174b35dbab8cb9993d9a3789 Mon Sep 17 00:00:00 2001 From: doxuta Date: Thu, 22 Oct 2026 12:13:05 +0700 Subject: [PATCH 2/9] fix(audit): a role's audit rows carry the role id, and an update names the role (#23) A __role__ update row had record_id NULL and, when only grants changed (the AI's access card), no name in its diff: the audit log alone could not say which role changed. Every role row now carries the role id as record_id, and an update's diff has the role's name on both sides. Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/audit/audit.go | 2 +- .../rm19_audit_log_integration_test.go | 36 +++++++++++- .../internal/services/audit_emit.go | 8 ++- .../internal/services/role_service.go | 33 ++++++++--- .../services/role_service_audit_test.go | 58 +++++++++++++++++++ 5 files changed, 125 insertions(+), 12 deletions(-) create mode 100644 nexus-platform/internal/services/role_service_audit_test.go diff --git a/nexus-platform/internal/audit/audit.go b/nexus-platform/internal/audit/audit.go index f4c8fbd..2783be3 100644 --- a/nexus-platform/internal/audit/audit.go +++ b/nexus-platform/internal/audit/audit.go @@ -170,7 +170,7 @@ const ( ) // Event is the payload a service emits after a mutation commits. RecordID is empty for -// admin-meta mutations (entity/field/role) that have no obj_* record. Diff is the +// admin-meta mutations (entity/field) that have no obj_* record; a role's rows carry the role id. Diff is the // {before,after} of only the fields that changed; create populates only after, delete only // before. At is the originating event time (the dispatcher stamps the row clock instead, but // At is carried for context/debug). All maps must be JSON-serializable. diff --git a/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go b/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go index d805cb2..b6d6609 100644 --- a/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go +++ b/nexus-platform/internal/handlers/rm19_audit_log_integration_test.go @@ -369,7 +369,8 @@ func TestRM19_RecordMutations_WriteOneAuditRowEach(t *testing.T) { // TestRM19_AdminMetaMutations_WriteAuditRows proves entity-create, field-add and role-create each // write one admin-meta audit row (__entity__/__field__/__role__) attributed to the caller, with -// NULL record_id (admin-meta mutations have no obj_* record). +// NULL record_id (admin-meta mutations have no obj_* record) — except the role's, which carries the +// role id (issue #23), and a role update, whose diff names the role even when only grants changed. func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { gdb, sx := a4SetupMigratedDB(t) auditRequireSchemaV14(t, sx) @@ -396,12 +397,26 @@ func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { } // Role create → __role__ row. + var role struct { + Data struct { + Role struct { + ID string `json:"id"` + } `json:"role"` + } `json:"data"` + } if w := doAuthed(t, rt.engine, "POST", "/api/v1/admin/roles", token, map[string]any{ "name": "rm19_viewer", "label": "RM19 Viewer", "actions": []map[string]any{{"entityName": entity, "action": "view", "accessLevel": "all"}}, - }, nil); w.Code != http.StatusCreated { + }, nil); w.Code != http.StatusCreated || json.Unmarshal(w.Body.Bytes(), &role) != nil || role.Data.Role.ID == "" { t.Fatalf("create role: HTTP %d; body=%s", w.Code, w.Body.String()) } + // Grants-only update, as the AI's access card applies it → a __role__ update row naming the role. + if w := doAuthed(t, rt.engine, "PUT", "/api/v1/admin/roles/"+role.Data.Role.ID, token, map[string]any{ + "name": "rm19_viewer", "label": "RM19 Viewer", + "actions": []map[string]any{{"entityName": entity, "action": "view", "accessLevel": "all"}, {"entityName": entity, "action": "edit", "accessLevel": "owner"}}, + }, nil); w.Code != http.StatusOK { + t.Fatalf("update role: HTTP %d; body=%s", w.Code, w.Body.String()) + } rt.drain(t) @@ -427,10 +442,27 @@ func TestRM19_AdminMetaMutations_WriteAuditRows(t *testing.T) { if r.TenantID != tenantID { t.Errorf("%s row tenant=%q; want %q", key, r.TenantID, tenantID) } + if key == audit.RoleMeta { + if r.RecordID == nil || *r.RecordID != role.Data.Role.ID { + t.Errorf("%s row record_id=%v; want the role id %q", key, r.RecordID, role.Data.Role.ID) + } + continue + } if r.RecordID != nil { t.Errorf("%s row record_id=%v; want NULL (admin-meta)", key, *r.RecordID) } } + var upd *auditLogRow + for i := range rows { + if rows[i].EntityName == audit.RoleMeta && rows[i].Action == audit.ActionUpdate { + upd = &rows[i] + } + } + var diff audit.Diff + if upd == nil || upd.RecordID == nil || *upd.RecordID != role.Data.Role.ID || json.Unmarshal(upd.Diff, &diff) != nil || + diff.Before["name"] != "rm19_viewer" || diff.After["name"] != "rm19_viewer" { + t.Fatalf("role update row = %+v; want record_id %q and the role's name on both sides of its diff", upd, role.Data.Role.ID) + } } // TestRM19_TeamMetaMutations_WriteAuditRows closes the __team__ zero-emit gap diff --git a/nexus-platform/internal/services/audit_emit.go b/nexus-platform/internal/services/audit_emit.go index d5760c2..25a87af 100644 --- a/nexus-platform/internal/services/audit_emit.go +++ b/nexus-platform/internal/services/audit_emit.go @@ -29,6 +29,12 @@ func emitMetaAudit(ctx context.Context, a audit.Auditor, tenantID, metaEntity, a // GET /audit-log?entityName=__user__&recordId= returns the whole account history alongside // the W7 reset-link row (auth_password_reset.go), which already uses RecordID=userId. func emitMetaAuditFor(ctx context.Context, a audit.Auditor, tenantID, metaEntity, recordID, action string, before, after any) { + emitMetaDiff(ctx, a, tenantID, metaEntity, recordID, action, audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after))) +} + +// emitMetaDiff is emitMetaAuditFor with a diff the caller has already built (a role update adds the +// role's name to both sides, role_service.go). +func emitMetaDiff(ctx context.Context, a audit.Auditor, tenantID, metaEntity, recordID, action string, diff *audit.Diff) { if a == nil { // a service built by struct literal in a test has no auditor; the trail is best-effort anyway return } @@ -38,7 +44,7 @@ func emitMetaAuditFor(ctx context.Context, a audit.Auditor, tenantID, metaEntity EntityName: metaEntity, RecordID: recordID, Action: action, - Diff: audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after)), + Diff: diff, At: time.Now().UTC(), }) } diff --git a/nexus-platform/internal/services/role_service.go b/nexus-platform/internal/services/role_service.go index 9ff44bc..91b3706 100644 --- a/nexus-platform/internal/services/role_service.go +++ b/nexus-platform/internal/services/role_service.go @@ -264,8 +264,8 @@ func (s *RoleService) CreateRole(ctx context.Context, tenantID string, in Create v := roleToView(role, actions) // Invalidate the new role's cached grants AFTER commit (defensive — nothing cached yet) (O3). s.aclCache.Invalidate(tenantID, role.ID) - // RM-19: audit the committed role create (after-only diff). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionCreate, nil, v) + // RM-19: audit the committed role create (after-only diff) on the role's own row. Async + fail-open. + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, role.ID, audit.ActionCreate, nil, v) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: role.ID, Label: roleLabel(v), Op: "create", After: v}) return &v, nil } @@ -349,9 +349,8 @@ func (s *RoleService) UpdateRole(ctx context.Context, tenantID, id string, in Up v := roleToView(role, current) // Invalidate the role's cached grants AFTER commit so changed/revoked grants take effect now (O3). s.aclCache.Invalidate(tenantID, id) - // RM-19: audit the committed role update. We record the after-view; the diff highlights the - // fields present (name/label/actions). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionUpdate, beforeView, v) + // RM-19: audit the committed role update on the role's own row. Async + fail-open. + emitMetaDiff(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionUpdate, roleUpdateDiff(priorRole.Name, beforeView, v)) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabel(v), Op: "update", Before: beforeView, After: v}) return &v, nil } @@ -385,7 +384,7 @@ func (s *RoleService) Recreate(ctx context.Context, tenantID, id string, before } s.aclCache.Invalidate(tenantID, id) v := roleToView(role, actions) - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionCreate, nil, v) + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionCreate, nil, v) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabel(v), Op: "create", After: v, Meta: map[string]any{"reassignedUserIds": userIDs, "reassigned": n}}) return int(n), nil @@ -450,8 +449,8 @@ func (s *RoleService) DeleteRole(ctx context.Context, tenantID, id string) error } // Invalidate the deleted role's cached grants AFTER commit so it can no longer authorize (O3). s.aclCache.Invalidate(tenantID, id) - // RM-19: audit the committed role delete (before-only diff). Async + fail-open. - emitMetaAudit(ctx, s.auditor, tenantID, audit.RoleMeta, audit.ActionDelete, beforeView, nil) + // RM-19: audit the committed role delete (before-only diff) on the role's own row. Async + fail-open. + emitMetaAuditFor(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionDelete, beforeView, nil) rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabelAny(beforeView), Op: "delete", Before: beforeView, Meta: meta}) return nil } @@ -538,6 +537,24 @@ func roleToView(r *auth.Role, actions []auth.RoleAction) RoleView { return v } +// roleUpdateDiff is a role update's audit diff with the role's name on both sides (issue #23): an +// update diff keeps only the changed keys, so a grants-only change, or a save that changes nothing, +// would otherwise leave a row that names no role. +func roleUpdateDiff(priorName string, before any, after RoleView) *audit.Diff { + d := audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after)) + if d == nil { + d = &audit.Diff{} + } + if d.Before == nil { + d.Before = map[string]any{} + } + if d.After == nil { + d.After = map[string]any{} + } + d.Before["name"], d.After["name"] = priorName, after.Name + return d +} + func roleLabel(v RoleView) string { if v.Label != "" { return v.Label diff --git a/nexus-platform/internal/services/role_service_audit_test.go b/nexus-platform/internal/services/role_service_audit_test.go new file mode 100644 index 0000000..94bd820 --- /dev/null +++ b/nexus-platform/internal/services/role_service_audit_test.go @@ -0,0 +1,58 @@ +package services + +// Issue #23: a role's audit rows name the role. An update diff keeps only the changed keys, so a +// grants-only change (the AI's access card) used to leave a __role__ row with record_id NULL and no +// name: the audit log alone could not say which role changed. + +import ( + "context" + "testing" + + "nexus/platform/internal/audit" +) + +func TestRole_AuditRowsNameTheRole(t *testing.T) { + ctx := context.Background() + svc, _ := newRoleSvc() + cap := &captureAuditor{} + svc.WithAuditor(cap) + created, err := svc.CreateRole(ctx, "t1", CreateRoleInput{Name: "sales", Label: "Sales", Actions: []RoleActionInput{{EntityName: "contacts", Action: "view"}}}) + if err != nil { + t.Fatal(err) + } + // Grants only, as the access card's apply writes it: the name is resent unchanged. + name, label := "sales", "Sales" + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Name: &name, Label: &label, + Actions: []RoleActionInput{{EntityName: "contacts", Action: "view"}, {EntityName: "tickets", Action: "view"}}}); err != nil { + t.Fatal(err) + } + // Nothing changes at all: the row still says which role was saved. + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Label: &label}); err != nil { + t.Fatal(err) + } + renamed := "sales_team" + if _, err := svc.UpdateRole(ctx, "t1", created.ID, UpdateRoleInput{Name: &renamed}); err != nil { + t.Fatal(err) + } + if err := svc.DeleteRole(ctx, "t1", created.ID); err != nil { + t.Fatal(err) + } + + if len(cap.events) != 5 { + t.Fatalf("events = %d; want create, three updates, delete", len(cap.events)) + } + for i, e := range cap.events { + if e.EntityName != audit.RoleMeta || e.RecordID != created.ID { + t.Errorf("event %d (%s) = %s/%q; want __role__ with record_id = the role's id %q", i, e.Action, e.EntityName, e.RecordID, created.ID) + } + } + for i, want := range [][2]string{{"sales", "sales"}, {"sales", "sales"}, {"sales", "sales_team"}} { + d := cap.events[1+i].Diff + if d == nil || d.Before["name"] != want[0] || d.After["name"] != want[1] { + t.Errorf("update %d diff = %+v; want name %q -> %q", i+1, d, want[0], want[1]) + } + } + if d := cap.events[1].Diff; d.After["actions"] == nil { + t.Errorf("grants-only update diff = %+v; want the changed actions kept", d) + } +} From 86c0acb4c7caca6fcad04ba254ff059f2137d429 Mon Sep 17 00:00:00 2001 From: doxuta Date: Thu, 22 Oct 2026 12:15:54 +0700 Subject: [PATCH 3/9] feat(ai): list_roles {grants: true} lists each role's current grants, also over MCP (#23) list_roles returned names only, so the builder agent and an MCP agent could answer "who can edit contacts?" only in part. With grants: true it returns every role of the tenant with its grants (entity, action, access level). It is a read: tenant pinned from the executor, nothing buffered. Without the argument the result is unchanged, and no tool was added, so the demo cassettes replay. The tool description is now short and in English. Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/ai/list_roles_test.go | 53 ++++++++++++++++++ nexus-platform/internal/ai/tools.go | 26 +++++++-- nexus-platform/internal/ai/tools_access.go | 42 ++++++++++++-- .../internal/handlers/mcp_integration_test.go | 55 +++++++++++++++++++ .../internal/mcpserver/mcpserver.go | 2 +- .../internal/mcpserver/mcpserver_test.go | 2 +- 6 files changed, 168 insertions(+), 12 deletions(-) diff --git a/nexus-platform/internal/ai/list_roles_test.go b/nexus-platform/internal/ai/list_roles_test.go index e2402cc..35e076a 100644 --- a/nexus-platform/internal/ai/list_roles_test.go +++ b/nexus-platform/internal/ai/list_roles_test.go @@ -10,8 +10,11 @@ package ai import ( "context" "encoding/json" + "slices" "strings" "testing" + + "nexus/platform/internal/services" ) func TestListRoles(t *testing.T) { @@ -54,3 +57,53 @@ func TestListRoles_EmptyTenantReturnsAnEmptyList(t *testing.T) { t.Errorf("out = %s, want an explicit empty array", out) } } + +// Issue #23: list_roles {grants: true} answers "who can edit contacts?" whole — every role of THIS +// tenant with its current grants, and nothing buffered (a read, so MCP may offer it too). +func TestListRoles_WithGrants(t *testing.T) { + e := accessExecutor(nil) + out := e.execute(context.Background(), "list_roles", `{"grants":true}`) + var got struct { + OK bool `json:"ok"` + Result struct { + Roles []struct { + Name string `json:"name"` + Label string `json:"label"` + Grants []services.RoleActionView `json:"grants"` + } `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(out), &got); err != nil || !got.OK { + t.Fatalf("out = %s (%v); want ok", out, err) + } + byName := map[string][]services.RoleActionView{} + for _, r := range got.Result.Roles { + byName[r.Name] = r.Grants + } + if len(got.Result.Roles) != 5 || got.Result.Roles[0].Label != "Nhân viên kinh doanh" { + t.Fatalf("roles = %+v; want tenant A's five roles with their labels", got.Result.Roles) + } + rep := []services.RoleActionView{{EntityName: "crm_accounts", Action: "view", AccessLevel: "all"}, {EntityName: "crm_accounts", Action: "create", AccessLevel: "all"}, {EntityName: "crm_accounts", Action: "edit", AccessLevel: "owner"}} + if !slices.Equal(byName["crm_sales_rep"], rep) || !slices.Equal(byName["viewer"], []services.RoleActionView{{EntityName: "*", Action: "view", AccessLevel: "all"}}) { + t.Fatalf("grants = %+v; want the rep's three crm_accounts grants and viewer's \"*\" view", byName) + } + if g, ok := byName["ops"]; !ok || g == nil || len(g) != 0 { + t.Errorf("a role with no grant = %v; want an explicit empty list", g) + } + if strings.Contains(out, "b_only") { + t.Fatalf("another tenant's role leaked: %s", out) + } + if len(e.draft) != 0 { + t.Fatalf("draft = %+v; a read buffers nothing", e.draft) + } +} + +func TestListRoles_GrantsNeedTheRoleReader(t *testing.T) { + e := &toolExecutor{reader: twoTenantReader(), tenantID: "t1"} + if out := e.execute(context.Background(), "list_roles", `{"grants":true}`); !strings.Contains(out, "ROLES_GRANTS_UNAVAILABLE") { + t.Fatalf("out = %s; want ROLES_GRANTS_UNAVAILABLE", out) + } + if out := e.execute(context.Background(), "list_roles", `{"grants":"yes"}`); !strings.Contains(out, "INVALID_ARGS") { + t.Fatalf("out = %s; want INVALID_ARGS", out) + } +} diff --git a/nexus-platform/internal/ai/tools.go b/nexus-platform/internal/ai/tools.go index 03357f8..b315e54 100644 --- a/nexus-platform/internal/ai/tools.go +++ b/nexus-platform/internal/ai/tools.go @@ -538,10 +538,12 @@ func toolDefinitionsBase() []Tool { Type: "function", Function: ToolFunction{ Name: "list_roles", - Description: "Liệt kê TÊN các vai (role) đang có của tenant. BẮT BUỘC gọi trước khi dùng roleName trong propose_workqueue, người duyệt (approverType='role') trong propose_approval hoặc role trong propose_access — tên vai không có thật sẽ làm bước Apply thất bại. Chưa có vai phù hợp thì bỏ trống roleName (queue hiện với mọi người) hoặc dùng approverType='user'.", + Description: "Lists the workspace's role names. Call it before naming a role in propose_workqueue (roleName), propose_approval (approverType 'role') or propose_access: a role that does not exist fails at Apply. No fitting role: leave roleName empty or use approverType 'user'. grants: true adds each role's current grants (entityName '*' = every table, accessLevel = which rows) to answer who can view or edit a table. Admins bypass grants. Read-only.", Parameters: map[string]any{ - "type": "object", - "properties": map[string]any{}, + "type": "object", + "properties": map[string]any{ + "grants": map[string]any{"type": "boolean", "description": "true: also list each role's current grants."}, + }, }, }, }, @@ -803,7 +805,7 @@ func (e *toolExecutor) dispatch(ctx context.Context, name, argsJSON string) stri case "get_app": return e.getApp(ctx, argsJSON) case "list_roles": - return e.listRoles(ctx) + return e.listRoles(ctx, argsJSON) case "snapshot_model": return e.snapshotModel(ctx) case "propose_entity": @@ -1313,13 +1315,25 @@ func (p proposedField) toDraftField(entity string) DraftField { func ptrDraftField(f DraftField) *DraftField { return &f } -// listRoles returns the tenant's role names so the model can only NAME a role that exists. +// listRoles returns the tenant's role names so the model can only NAME a role that exists; with +// {grants: true}, every role with its grants (listRoleGrants, issue #23). // // propose_workqueue's roleName and propose_approval's role approver are resolved to ids at Apply, // and until now the model had no way to see the list — so it produced a reasonable-sounding name // and the Apply failed on a role nobody had created. Failing at Apply is the worst place to learn // it: the proposal already looked right and the person already pressed the button. -func (e *toolExecutor) listRoles(ctx context.Context) string { +func (e *toolExecutor) listRoles(ctx context.Context, argsJSON string) string { + var a struct { + Grants bool `json:"grants"` + } + if strings.TrimSpace(argsJSON) != "" { + if err := json.Unmarshal([]byte(argsJSON), &a); err != nil { + return toolErr("INVALID_ARGS: %v", err) + } + } + if a.Grants { + return e.listRoleGrants(ctx) + } names, err := e.reader.ListRoleNames(ctx, e.tenantID) if err != nil { return toolErr("ROLES_READ_FAILED: không đọc được danh sách vai: %v", err) diff --git a/nexus-platform/internal/ai/tools_access.go b/nexus-platform/internal/ai/tools_access.go index 0a78a44..33b3d36 100644 --- a/nexus-platform/internal/ai/tools_access.go +++ b/nexus-platform/internal/ai/tools_access.go @@ -197,10 +197,7 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin e.draft = e.draft[:from] return toolErr("ACCESS_PROPOSE_FAILED: %v", err) } - before := make([]services.RoleActionView, len(acts)) - for i, a := range acts { - before[i] = services.RoleActionView{EntityName: a.EntityName, Action: a.Action, AccessLevel: a.AccessLevel} - } + before := grantViews(acts) after := mergeAccessGrants(before, p.grants) if slices.Equal(after, before) { unchanged = append(unchanged, p.role.Name) @@ -227,6 +224,43 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin return toolOK(out) } +// listRoleGrants is list_roles {grants: true} (issue #23): every role of the tenant with its current +// grants, so "who can edit contacts?" gets a whole answer. A read: the tenant is the executor's, +// nothing is buffered or written, which is why MCP offers it too. +// ponytail: two reads per role (ListActionsForRole re-checks the role's tenant); a tenant has tens of +// roles. One JOIN over acl_roles/acl_role_actions if that ever shows up. +func (e *toolExecutor) listRoleGrants(ctx context.Context) string { + var probes *AccessProbes + if c, ok := e.reader.(AccessProbeCarrier); ok { + probes = c.AccessProbes() + } + if probes == nil || probes.Roles == nil { + return toolErr("ROLES_GRANTS_UNAVAILABLE: the server has no role reader wired for the assistant; call list_roles without grants") + } + roles, err := probes.Roles.ListRoles(ctx, e.tenantID) + if err != nil { + return toolErr("ROLES_READ_FAILED: %v", err) + } + out := make([]map[string]any, 0, len(roles)) + for _, r := range roles { + acts, err := probes.Roles.ListActionsForRole(ctx, e.tenantID, r.ID) + if err != nil { + return toolErr("ROLES_READ_FAILED: role %q: %v", r.Name, err) + } + out = append(out, map[string]any{"name": r.Name, "label": r.Label, "grants": grantViews(acts)}) + } + return toolOK(map[string]any{"roles": out}) +} + +// grantViews is a role's grant rows as the API and the access card show them; never nil. +func grantViews(acts []auth.RoleAction) []services.RoleActionView { + out := make([]services.RoleActionView, len(acts)) + for i, a := range acts { + out[i] = services.RoleActionView{EntityName: a.EntityName, Action: a.Action, AccessLevel: a.AccessLevel} + } + return out +} + // resolveAccessRole finds the role by its name, else by its label when exactly one role carries it // (the builder may say "Nhân viên kinh doanh"). roles is tenant-pinned, so another tenant's role is // simply not there. The second value is the tool error ("" = found). diff --git a/nexus-platform/internal/handlers/mcp_integration_test.go b/nexus-platform/internal/handlers/mcp_integration_test.go index 969dbb1..67253bd 100644 --- a/nexus-platform/internal/handlers/mcp_integration_test.go +++ b/nexus-platform/internal/handlers/mcp_integration_test.go @@ -15,6 +15,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "reflect" "strings" "sync" "testing" @@ -820,3 +821,57 @@ func TestMCP_SettledProposalsAreNotReplayed(t *testing.T) { mustPropose(t, "propose_field", map[string]any{"entity": "st_visits", "name": "doctor", "label": "Doctor", "fieldType": "user"}) // doctor_id is free }) } + +// Issue #23: an outside agent answers "who can edit contacts?" whole. nexus_list_roles {grants: true} +// lists this workspace's roles with their grants (the role reader main.go wires), never another +// tenant's, and as a read it leaves the token's thread alone. +func TestMCP_ListRolesWithGrants(t *testing.T) { + gdb, sx := a4SetupMigratedDB(t) + ctx := context.Background() + const tenant, other = "ten-mcp-grants", "ten-mcp-grants-b" + builderID := mcpBuilder(t, gdb, tenant, "mcp-grants") + a4SeedTenant(t, gdb, other, "mcp-grants-b", "mcp-grants-b") + roleRepo := auth.NewRoleRepository(gdb) + roles := services.NewRoleService(roleRepo) + if _, err := roles.CreateRole(ctx, tenant, services.CreateRoleInput{Name: "it_contacts_editor", Label: "Contacts editor", Actions: []services.RoleActionInput{ + {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}, {EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}}}); err != nil { + t.Fatalf("role: %v", err) + } + if _, err := roles.CreateRole(ctx, other, services.CreateRoleInput{Name: "it_other_tenant_role", Label: "B"}); err != nil { + t.Fatalf("other tenant's role: %v", err) + } + store := ai.NewSessionStore(sx) + mcpSvc := services.NewMCPTokenService(auth.NewMCPTokenRepository(gdb), store, auth.NewUserRepository(gdb)) + tok, secret, err := mcpSvc.Issue(ctx, auth.Subject{UserID: builderID, TenantID: tenant, IsAdmin: true}, nil) + if err != nil { + t.Fatalf("issue: %v", err) + } + agent := ai.NewAIBuilderAgent(config.AIConfig{}, nil, ai.ReaderWithAccessProbes(metadata.NewRepository(gdb), &ai.AccessProbes{Roles: roleRepo}), nil, nil, zap.NewNop()) + ts := httptest.NewServer(mcpserver.New(mcpSvc, agent, store, nil, zap.NewNop())) + defer ts.Close() + cs := mcpConnect(t, ts.URL, secret) + + res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "nexus_list_roles", Arguments: map[string]any{"grants": true}}) + if err != nil || res.IsError { + t.Fatalf("list_roles grants: %v %s", err, mcpText(res)) + } + var out struct { + Result struct { + Roles []struct { + Name string `json:"name"` + Grants []services.RoleActionView `json:"grants"` + } `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(mcpText(res)), &out); err != nil { + t.Fatalf("decode %s: %v", mcpText(res), err) + } + want := []services.RoleActionView{{EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}, {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}} + if len(out.Result.Roles) != 1 || out.Result.Roles[0].Name != "it_contacts_editor" || !reflect.DeepEqual(out.Result.Roles[0].Grants, want) { + t.Fatalf("roles = %+v; want only this workspace's role with %v", out.Result.Roles, want) + } + var rows int + if err := sx.Get(&rows, "SELECT COUNT(*) FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ?", tok.SessionID, tenant); err != nil || rows != 2 { + t.Fatalf("thread rows = %d (%v); want only the 2 of the key's opening turn", rows, err) + } +} diff --git a/nexus-platform/internal/mcpserver/mcpserver.go b/nexus-platform/internal/mcpserver/mcpserver.go index a9650a7..b50a032 100644 --- a/nexus-platform/internal/mcpserver/mcpserver.go +++ b/nexus-platform/internal/mcpserver/mcpserver.go @@ -48,7 +48,7 @@ type Threads interface { } // instructions is what an MCP client hands its model about this server. -const instructions = `Nexus is a platform for business apps whose apps are metadata: tables (entities), fields, relations, layouts, automation rules, reports, apps and access. These tools read ONE workspace's model and PROPOSE changes to it. A proposal changes nothing: it is saved as a card in the builder's Studio thread, where a human reviews it, applies it to drafts and publishes it. No tool applies, publishes or writes data, so tell the user the change is waiting for review. Read before you propose (nexus_list_entities, nexus_list_fields). Names are snake_case; labels are what users see. A call refused by a validator answers {"ok":false,"error":"CODE: message"}: fix the arguments and call again. Tool descriptions are in Vietnamese.` +const instructions = `Nexus is a platform for business apps whose apps are metadata: tables (entities), fields, relations, layouts, automation rules, reports, apps and access. These tools read ONE workspace's model and PROPOSE changes to it. A proposal changes nothing: it is saved as a card in the builder's Studio thread, where a human reviews it, applies it to drafts and publishes it. No tool applies, publishes or writes data, so tell the user the change is waiting for review. Read before you propose (nexus_list_entities, nexus_list_fields). Names are snake_case; labels are what users see. A call refused by a validator answers {"ok":false,"error":"CODE: message"}: fix the arguments and call again. Most tool descriptions are in Vietnamese.` type server struct { tokens Verifier diff --git a/nexus-platform/internal/mcpserver/mcpserver_test.go b/nexus-platform/internal/mcpserver/mcpserver_test.go index 81bb413..1bc1883 100644 --- a/nexus-platform/internal/mcpserver/mcpserver_test.go +++ b/nexus-platform/internal/mcpserver/mcpserver_test.go @@ -69,7 +69,7 @@ func TestTools_AreTheBuilderAgentsReadAndProposeToolsOnly(t *testing.T) { if len(got) != want { t.Errorf("exposed %d tools, want the %d of the builder agent", len(got), want) } - for _, n := range []string{"list_entities", "list_fields", "list_relationships", "snapshot_model", "explain_access", + for _, n := range []string{"list_entities", "list_fields", "list_relationships", "list_roles", "snapshot_model", "explain_access", "propose_entity", "propose_field", "propose_relationship", "propose_layout"} { if _, ok := got[toolPrefix+n]; !ok { t.Errorf("core tool %s%s missing", toolPrefix, n) From a4afc6b4926d39efd05226b6fd6a7c48d6a235a9 Mon Sep 17 00:00:00 2001 From: doxuta Date: Thu, 22 Oct 2026 12:17:59 +0700 Subject: [PATCH 4/9] fix(studio): the access page filtered to an app still draws the card's ghost cell (#23) With ?app= (or ?bang=) the matrix drew only that app's tables, and a built table the previewed access card names outside it was neither drawn nor a not-built-yet column, so its ghost cell had nowhere to go. accessGhost now adds a column for every table the card names that the page does not draw: the table's real, editable column when it is built, the read-only one when not. Co-Authored-By: Claude Opus 5.5 --- .../components/studio/AccessMatrix.test.tsx | 23 +++++++++++++++---- nexus-web/components/studio/AccessMatrix.tsx | 13 +++++++---- .../components/studio/build/AccessPage.tsx | 6 ++--- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/nexus-web/components/studio/AccessMatrix.test.tsx b/nexus-web/components/studio/AccessMatrix.test.tsx index d3bda0f..de6dff8 100644 --- a/nexus-web/components/studio/AccessMatrix.test.tsx +++ b/nexus-web/components/studio/AccessMatrix.test.tsx @@ -226,12 +226,13 @@ describe("delivered project: 'Áp ngay cho người dùng thật' (lát f2-direc describe("assistant preview (an access card)", () => { const card = (before: RoleGrant[], after: RoleGrant[], labels: Record) => mkChange("role", "update", { docKey: "r3", target: { name: "r3", entity: Object.keys(labels)[0] }, before: { grants: before, labels }, after: { grants: after, labels } }); - function Page({ roles, tables }: { roles: RoleDetail[]; tables: { name: string; label: string }[] }) { - const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, tables); - return ; + // `tables` is what the page draws (?app= / ?bang= may leave some out), `built` every table of the project. + function Page({ roles, tables, built = tables }: { roles: RoleDetail[]; tables: { name: string; label: string }[]; built?: { name: string; label: string }[] }) { + const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, built, tables); + return ; } - const renderWith = (c: ReturnType | null) => - render(); + const renderWith = (c: ReturnType | null, tables = TABLES) => + render(); const onVisit = card([g("invoice", "create")], [g("invoice", "create"), g("visit", "view"), g("visit", "create"), g("visit", "edit", "owner")], { visit: "Lịch hẹn" }); it("tints the card's cell, says the level it leads to and the one it replaces; other cells stay plain", async () => { @@ -271,6 +272,18 @@ describe("assistant preview (an access card)", () => { expect(screen.queryByRole("combobox", { name: /Phiếu hỗ trợ/ })).toBeNull(); }); + // issue #23: the page filtered to an app that leaves the card's (built) table out still draws its ghost cell, on the + // table's real, editable column. + it("a built table outside the ?app= filter gets its column, so the ghost cell is drawn", async () => { + renderWith(onVisit, [TABLES[0]]); + const td = (await screen.findByText("Xem và sửa · Đề xuất")).closest("td")!; + expect(td.className).toContain("nx-proposed"); + expect(within(td).getByRole("combobox", { name: name("Kế toán", "Lịch hẹn", "Không thấy") })).toBeInTheDocument(); + const head = screen.getByRole("columnheader", { name: "Lịch hẹn" }); + expect(head.className).not.toContain("nx-proposed"); + expect(screen.getAllByRole("columnheader")).toHaveLength(3); + }); + it("Bỏ (clear) removes the ghost and leaves the real grants alone", async () => { renderWith(onVisit); await screen.findByText("Xem và sửa · Đề xuất"); diff --git a/nexus-web/components/studio/AccessMatrix.tsx b/nexus-web/components/studio/AccessMatrix.tsx index bf02925..c8ee61d 100644 --- a/nexus-web/components/studio/AccessMatrix.tsx +++ b/nexus-web/components/studio/AccessMatrix.tsx @@ -41,16 +41,21 @@ const tierText = (v: unknown, table: string): string | null => { const accessTablesOf = (c: ProposedChange | null): string[] => Object.keys(side(c?.after).labels ?? {}); /** - * What the access card being previewed draws on the page: its role's cells (`proposed`) and, as read-only columns, the - * tables it names that are not built yet (the table card is still to be applied). + * What the access card being previewed draws on the page: its role's cells (`proposed`) and the columns of the tables it + * names that the page does not draw (`extra`, `shown` = the drawn tables): a table not built yet is a read-only column + * (the table card is still to be applied); a built one that `?app=` / `?bang=` left out gets its own column, or its + * ghost cell would have nowhere to go (issue #23). */ -export function accessGhost(change: ProposedChange | null, roles: readonly RoleDetail[], built: readonly { name: string }[]) { +export function accessGhost(change: ProposedChange | null, roles: readonly RoleDetail[], built: readonly { name: string; label?: string }[], shown: readonly { name: string }[]) { const tables = accessTablesOf(change); const role = change ? roles.find((r) => r.id === change.docKey || r.name === change.target.name) : undefined; const labels = side(change?.after).labels ?? {}; return { proposed: role ? new Set(tables.map((n) => `${role.id}|${n}`)) : undefined, - pending: tables.filter((n) => !built.some((e) => e.name === n)).map((n) => ({ name: n, label: labels[n] || n, pending: true })), + extra: tables.filter((n) => !shown.some((e) => e.name === n)).map((n) => { + const table = built.find((e) => e.name === n); + return table ? { name: n, label: table.label || n } : { name: n, label: labels[n] || n, pending: true }; + }), }; } function GhostNote({ change, table }: { change: ProposedChange; table: string }) { diff --git a/nexus-web/components/studio/build/AccessPage.tsx b/nexus-web/components/studio/build/AccessPage.tsx index 9bf09c3..e444923 100644 --- a/nexus-web/components/studio/build/AccessPage.tsx +++ b/nexus-web/components/studio/build/AccessPage.tsx @@ -52,8 +52,8 @@ export function AccessPage({ slug, app: appParam, bang }: { slug: string; app?: const { visible, hidden } = splitByScope(entities, scope.entityNames, (e) => e.name); const tables = (bang ? visible.filter((e) => e.name === bang) : visible).map((e) => ({ name: e.name, label: e.label || e.name })); - // The assistant's access card being previewed ("Xem trước"): its role's cells, and the tables it names not built yet. - const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, entities); + // The assistant's access card being previewed ("Xem trước"): its role's cells, and the tables it names the page does not draw. + const ghost = accessGhost(useProposedChanges("role")[0] ?? null, roles, entities, tables); // ── "+ Vai mới" strip ── const [open, setOpen] = useState(false); @@ -139,7 +139,7 @@ export function AccessPage({ slug, app: appParam, bang }: { slug: string; app?: body = ( studioHref(slug, "dung/nguoi-dung-quyen/vai/:id", { id })} From acf37f5cb455b3cedf648f35b88ad64a437701da Mon Sep 17 00:00:00 2001 From: doxuta Date: Thu, 22 Oct 2026 12:18:52 +0700 Subject: [PATCH 5/9] fix(studio): a change list line wraps instead of being cut to one line (#23) ChangeList truncated every line (slds-truncate), so a long rule condition, grant or path lost the part the builder had to read, on every proposal card, the publish review and the history. The text now wraps (slds-hyphenate, min-w-0) with the mark on its first line. The access card keeps its sentence title: the in-place question reads it, it was never only a workaround. Co-Authored-By: Claude Opus 5.5 --- nexus-web/components/studio/ChangeList.test.tsx | 10 ++++++++++ nexus-web/components/studio/ChangeList.tsx | 7 ++++--- nexus-web/lib/aiProposalView.ts | 5 +++-- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/nexus-web/components/studio/ChangeList.test.tsx b/nexus-web/components/studio/ChangeList.test.tsx index 0102cd7..0a0ff6e 100644 --- a/nexus-web/components/studio/ChangeList.test.tsx +++ b/nexus-web/components/studio/ChangeList.test.tsx @@ -27,6 +27,16 @@ describe("ChangeList", () => { expect(rows[0].textContent).toContain("Luật gửi thư"); }); + // issue #23: a long line (a rule's condition, a grant, a path) wraps instead of being cut to one line. + it("a long line wraps, the mark stays on its first line", () => { + render(); + const row = screen.getByRole("listitem"); + const text = within(row).getByText(/người phụ trách/); + expect(text.className).not.toContain("slds-truncate"); + expect(text.className).toContain("slds-hyphenate"); + expect(row.className).toContain("slds-grid_vertical-align-start"); + }); + it("tone=proposed marks the list as an assistant proposal", () => { const { container } = render(); expect(container.querySelector("ul")?.className).toContain("nx-proposed"); diff --git a/nexus-web/components/studio/ChangeList.tsx b/nexus-web/components/studio/ChangeList.tsx index 7f81781..b490627 100644 --- a/nexus-web/components/studio/ChangeList.tsx +++ b/nexus-web/components/studio/ChangeList.tsx @@ -1,5 +1,6 @@ // ChangeList — "+ ~ − =" list of changes (specs/073 UI-ARCH 5.3). The mark is decoration (aria-hidden); the word beside it is -// for screen readers. Used by PublishReview and, with tone="proposed", by assistant proposals. +// for screen readers. Used by PublishReview and, with tone="proposed", by assistant proposals. A long line wraps (a rule's +// condition, a grant, a path): cut to one line it hid the part the builder had to read (issue #23). import clsx from "clsx"; import type { ReactNode } from "react"; import { t } from "@/lib/i18n"; @@ -19,10 +20,10 @@ export function ChangeList({ items, tone = "neutral", label }: { items: readonly return (
    {items.map((it, i) => ( -
  • +
  • {t(MARK[it.op].word)} - {it.text} + {it.text}
  • ))}
diff --git a/nexus-web/lib/aiProposalView.ts b/nexus-web/lib/aiProposalView.ts index eb1c526..66dcb6b 100644 --- a/nexus-web/lib/aiProposalView.ts +++ b/nexus-web/lib/aiProposalView.ts @@ -218,8 +218,9 @@ export function proposalView(item: AiDraftItem, ctx: Ctx = {}): ProposalView | n } const ac = item.kind === "access" ? getAccessDraft(item) : undefined; if (ac) { - // The title is the whole sentence, so it wraps instead of being cut: "Nhân viên kinh doanh được xem tất cả · tạo · sửa - // của mình trên Phiếu hỗ trợ" (one clause per table); the list has one short "+" line per grant. + // The title is the whole sentence, which the in-place question also reads ("Quyền này áp ngay cho người dùng thật: …"): + // "Nhân viên kinh doanh được xem tất cả · tạo · sửa của mình trên Phiếu hỗ trợ" (one clause per table); the list has + // one "+" line per grant. const role = ac.roleLabel || ac.role; const label = (n: string) => ac.labels?.[n] || n; const tables = [...new Set(ac.grants.map((g) => g.entityName))]; From 6b1766ee2c1ae4e2c25fe3790d8d626ff07d9f96 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 11:45:53 +0700 Subject: [PATCH 6/9] fix(audit): a role update's audit row names the role without dereferencing a missing before-image (#23) roleUpdateDiff took priorRole.Name while UpdateRole still guards priorRole against nil; it now reads the name from the before view, and from the role after the update when there is none. Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/services/role_service.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/nexus-platform/internal/services/role_service.go b/nexus-platform/internal/services/role_service.go index 91b3706..91f8a6d 100644 --- a/nexus-platform/internal/services/role_service.go +++ b/nexus-platform/internal/services/role_service.go @@ -350,7 +350,7 @@ func (s *RoleService) UpdateRole(ctx context.Context, tenantID, id string, in Up // Invalidate the role's cached grants AFTER commit so changed/revoked grants take effect now (O3). s.aclCache.Invalidate(tenantID, id) // RM-19: audit the committed role update on the role's own row. Async + fail-open. - emitMetaDiff(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionUpdate, roleUpdateDiff(priorRole.Name, beforeView, v)) + emitMetaDiff(ctx, s.auditor, tenantID, audit.RoleMeta, id, audit.ActionUpdate, roleUpdateDiff(beforeView, v)) s.rec.RecordDirect(ctx, tenantID, "", DirectDoc{DocType: "role", DocKey: id, Label: roleLabel(v), Op: "update", Before: beforeView, After: v}) return &v, nil } @@ -539,8 +539,13 @@ func roleToView(r *auth.Role, actions []auth.RoleAction) RoleView { // roleUpdateDiff is a role update's audit diff with the role's name on both sides (issue #23): an // update diff keeps only the changed keys, so a grants-only change, or a save that changes nothing, -// would otherwise leave a row that names no role. -func roleUpdateDiff(priorName string, before any, after RoleView) *audit.Diff { +// would otherwise leave a row that names no role. before is the RoleView read before the update (nil +// when there was none to read: the row then names the role by its name after). +func roleUpdateDiff(before any, after RoleView) *audit.Diff { + priorName := after.Name + if b, ok := before.(RoleView); ok { + priorName = b.Name + } d := audit.ComputeDiff(audit.StructToMap(before), audit.StructToMap(after)) if d == nil { d = &audit.Diff{} From 32b4ee10f570adbd72d63e7a3a220f37f41ffffd Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 11:45:53 +0700 Subject: [PATCH 7/9] fix(ai): list_roles keeps its Vietnamese description, now with the grants sentence (#23) The other builder tools and the MCP instructions ("Tool descriptions are in Vietnamese") stay Vietnamese (#58 kept the prompts Vietnamese), so list_roles does too; ROLES_GRANTS_UNAVAILABLE reads like its siblings. Only names are in the cassette fingerprint, so the demo replays unchanged. Co-Authored-By: Claude Opus 5.5 --- nexus-platform/internal/ai/tools.go | 4 ++-- nexus-platform/internal/ai/tools_access.go | 2 +- nexus-platform/internal/mcpserver/mcpserver.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/nexus-platform/internal/ai/tools.go b/nexus-platform/internal/ai/tools.go index b315e54..e86ab3f 100644 --- a/nexus-platform/internal/ai/tools.go +++ b/nexus-platform/internal/ai/tools.go @@ -538,11 +538,11 @@ func toolDefinitionsBase() []Tool { Type: "function", Function: ToolFunction{ Name: "list_roles", - Description: "Lists the workspace's role names. Call it before naming a role in propose_workqueue (roleName), propose_approval (approverType 'role') or propose_access: a role that does not exist fails at Apply. No fitting role: leave roleName empty or use approverType 'user'. grants: true adds each role's current grants (entityName '*' = every table, accessLevel = which rows) to answer who can view or edit a table. Admins bypass grants. Read-only.", + Description: "Liệt kê TÊN các vai (role) đang có của tenant. BẮT BUỘC gọi trước khi dùng roleName trong propose_workqueue, người duyệt (approverType='role') trong propose_approval hoặc role trong propose_access — tên vai không có thật sẽ làm bước Apply thất bại. Chưa có vai phù hợp thì bỏ trống roleName (queue hiện với mọi người) hoặc dùng approverType='user'. grants: true → kèm quyền hiện có của từng vai (entityName '*' = mọi bảng, accessLevel = những bản ghi nào) để trả lời 'ai được xem / sửa bảng X'; quản trị viên bỏ qua quyền. Chỉ đọc, không ghi, không vào draft.", Parameters: map[string]any{ "type": "object", "properties": map[string]any{ - "grants": map[string]any{"type": "boolean", "description": "true: also list each role's current grants."}, + "grants": map[string]any{"type": "boolean", "description": "true: kèm quyền hiện có của từng vai."}, }, }, }, diff --git a/nexus-platform/internal/ai/tools_access.go b/nexus-platform/internal/ai/tools_access.go index 33b3d36..6bb3374 100644 --- a/nexus-platform/internal/ai/tools_access.go +++ b/nexus-platform/internal/ai/tools_access.go @@ -235,7 +235,7 @@ func (e *toolExecutor) listRoleGrants(ctx context.Context) string { probes = c.AccessProbes() } if probes == nil || probes.Roles == nil { - return toolErr("ROLES_GRANTS_UNAVAILABLE: the server has no role reader wired for the assistant; call list_roles without grants") + return toolErr("ROLES_GRANTS_UNAVAILABLE: server chưa nối bộ đọc vai cho AI Builder — gọi list_roles không kèm grants") } roles, err := probes.Roles.ListRoles(ctx, e.tenantID) if err != nil { diff --git a/nexus-platform/internal/mcpserver/mcpserver.go b/nexus-platform/internal/mcpserver/mcpserver.go index b50a032..a9650a7 100644 --- a/nexus-platform/internal/mcpserver/mcpserver.go +++ b/nexus-platform/internal/mcpserver/mcpserver.go @@ -48,7 +48,7 @@ type Threads interface { } // instructions is what an MCP client hands its model about this server. -const instructions = `Nexus is a platform for business apps whose apps are metadata: tables (entities), fields, relations, layouts, automation rules, reports, apps and access. These tools read ONE workspace's model and PROPOSE changes to it. A proposal changes nothing: it is saved as a card in the builder's Studio thread, where a human reviews it, applies it to drafts and publishes it. No tool applies, publishes or writes data, so tell the user the change is waiting for review. Read before you propose (nexus_list_entities, nexus_list_fields). Names are snake_case; labels are what users see. A call refused by a validator answers {"ok":false,"error":"CODE: message"}: fix the arguments and call again. Most tool descriptions are in Vietnamese.` +const instructions = `Nexus is a platform for business apps whose apps are metadata: tables (entities), fields, relations, layouts, automation rules, reports, apps and access. These tools read ONE workspace's model and PROPOSE changes to it. A proposal changes nothing: it is saved as a card in the builder's Studio thread, where a human reviews it, applies it to drafts and publishes it. No tool applies, publishes or writes data, so tell the user the change is waiting for review. Read before you propose (nexus_list_entities, nexus_list_fields). Names are snake_case; labels are what users see. A call refused by a validator answers {"ok":false,"error":"CODE: message"}: fix the arguments and call again. Tool descriptions are in Vietnamese.` type server struct { tokens Verifier From be0167f7a9f039f2924fcac8b7b5a19b686e0569 Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 11:45:53 +0700 Subject: [PATCH 8/9] test(mcp): list_roles grants seen from two tenants' tokens, and nothing written (#23) Tenant B's role now carries grants (a leak shows as a role or a grant), B's token sees only B's, and a read leaves acl_roles, acl_role_actions and both threads as they were. Co-Authored-By: Claude Opus 5.5 --- .../internal/handlers/mcp_integration_test.go | 89 ++++++++++++------- 1 file changed, 57 insertions(+), 32 deletions(-) diff --git a/nexus-platform/internal/handlers/mcp_integration_test.go b/nexus-platform/internal/handlers/mcp_integration_test.go index 67253bd..cc7e3c0 100644 --- a/nexus-platform/internal/handlers/mcp_integration_test.go +++ b/nexus-platform/internal/handlers/mcp_integration_test.go @@ -823,55 +823,80 @@ func TestMCP_SettledProposalsAreNotReplayed(t *testing.T) { } // Issue #23: an outside agent answers "who can edit contacts?" whole. nexus_list_roles {grants: true} -// lists this workspace's roles with their grants (the role reader main.go wires), never another -// tenant's, and as a read it leaves the token's thread alone. +// lists this workspace's roles with their grants (the role reader main.go wires). A token of tenant A +// never sees tenant B's roles or grants (nor B's token A's), and as a read it writes nothing: no +// role or grant changes, and the token's thread keeps only its opening turn. func TestMCP_ListRolesWithGrants(t *testing.T) { gdb, sx := a4SetupMigratedDB(t) ctx := context.Background() - const tenant, other = "ten-mcp-grants", "ten-mcp-grants-b" - builderID := mcpBuilder(t, gdb, tenant, "mcp-grants") - a4SeedTenant(t, gdb, other, "mcp-grants-b", "mcp-grants-b") + const tenantA, tenantB = "ten-mcp-grants", "ten-mcp-grants-b" + builderA := mcpBuilder(t, gdb, tenantA, "mcp-grants") + builderB := mcpBuilder(t, gdb, tenantB, "mcp-grants-b") roleRepo := auth.NewRoleRepository(gdb) roles := services.NewRoleService(roleRepo) - if _, err := roles.CreateRole(ctx, tenant, services.CreateRoleInput{Name: "it_contacts_editor", Label: "Contacts editor", Actions: []services.RoleActionInput{ + if _, err := roles.CreateRole(ctx, tenantA, services.CreateRoleInput{Name: "it_contacts_editor", Label: "Contacts editor", Actions: []services.RoleActionInput{ {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}, {EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}}}); err != nil { - t.Fatalf("role: %v", err) + t.Fatalf("role A: %v", err) } - if _, err := roles.CreateRole(ctx, other, services.CreateRoleInput{Name: "it_other_tenant_role", Label: "B"}); err != nil { - t.Fatalf("other tenant's role: %v", err) + // B's role grants on a table of the same name: a leak would show up as a role or as a grant. + if _, err := roles.CreateRole(ctx, tenantB, services.CreateRoleInput{Name: "it_b_contacts_admin", Label: "B", Actions: []services.RoleActionInput{ + {EntityName: "it_contacts", Action: "delete", AccessLevel: "all"}, {EntityName: "*", Action: "edit", AccessLevel: "all"}}}); err != nil { + t.Fatalf("role B: %v", err) } store := ai.NewSessionStore(sx) mcpSvc := services.NewMCPTokenService(auth.NewMCPTokenRepository(gdb), store, auth.NewUserRepository(gdb)) - tok, secret, err := mcpSvc.Issue(ctx, auth.Subject{UserID: builderID, TenantID: tenant, IsAdmin: true}, nil) - if err != nil { - t.Fatalf("issue: %v", err) - } agent := ai.NewAIBuilderAgent(config.AIConfig{}, nil, ai.ReaderWithAccessProbes(metadata.NewRepository(gdb), &ai.AccessProbes{Roles: roleRepo}), nil, nil, zap.NewNop()) ts := httptest.NewServer(mcpserver.New(mcpSvc, agent, store, nil, zap.NewNop())) defer ts.Close() - cs := mcpConnect(t, ts.URL, secret) - res, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "nexus_list_roles", Arguments: map[string]any{"grants": true}}) - if err != nil || res.IsError { - t.Fatalf("list_roles grants: %v %s", err, mcpText(res)) + type role struct { + Name string `json:"name"` + Grants []services.RoleActionView `json:"grants"` } - var out struct { - Result struct { - Roles []struct { - Name string `json:"name"` - Grants []services.RoleActionView `json:"grants"` - } `json:"roles"` - } `json:"result"` + count := func(q string, args ...any) int { + t.Helper() + var n int + if err := sx.Get(&n, q, args...); err != nil { + t.Fatalf("%s: %v", q, err) + } + return n } - if err := json.Unmarshal([]byte(mcpText(res)), &out); err != nil { - t.Fatalf("decode %s: %v", mcpText(res), err) + grantsBefore := count("SELECT COUNT(*) FROM acl_role_actions") + rolesBefore := count("SELECT COUNT(*) FROM acl_roles") + listAs := func(tenant, builderID string) []role { + t.Helper() + tok, secret, err := mcpSvc.Issue(ctx, auth.Subject{UserID: builderID, TenantID: tenant, IsAdmin: true}, nil) + if err != nil { + t.Fatalf("issue %s: %v", tenant, err) + } + res, err := mcpConnect(t, ts.URL, secret).CallTool(ctx, &mcp.CallToolParams{Name: "nexus_list_roles", Arguments: map[string]any{"grants": true}}) + if err != nil || res.IsError { + t.Fatalf("list_roles grants as %s: %v %s", tenant, err, mcpText(res)) + } + var out struct { + Result struct { + Roles []role `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(mcpText(res)), &out); err != nil { + t.Fatalf("decode %s: %v", mcpText(res), err) + } + if n := count("SELECT COUNT(*) FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ?", tok.SessionID, tenant); n != 2 { + t.Fatalf("%s thread rows = %d; want only the 2 of the key's opening turn", tenant, n) + } + return out.Result.Roles } - want := []services.RoleActionView{{EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}, {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}} - if len(out.Result.Roles) != 1 || out.Result.Roles[0].Name != "it_contacts_editor" || !reflect.DeepEqual(out.Result.Roles[0].Grants, want) { - t.Fatalf("roles = %+v; want only this workspace's role with %v", out.Result.Roles, want) + + gotA := listAs(tenantA, builderA) + wantA := []role{{Name: "it_contacts_editor", Grants: []services.RoleActionView{{EntityName: "it_contacts", Action: "edit", AccessLevel: "owner"}, {EntityName: "it_contacts", Action: "view", AccessLevel: "all"}}}} + if !reflect.DeepEqual(gotA, wantA) { + t.Fatalf("tenant A's token sees %+v; want only its own role and grants %+v", gotA, wantA) } - var rows int - if err := sx.Get(&rows, "SELECT COUNT(*) FROM sys_ai_messages WHERE session_id = ? AND tenant_id = ?", tok.SessionID, tenant); err != nil || rows != 2 { - t.Fatalf("thread rows = %d (%v); want only the 2 of the key's opening turn", rows, err) + gotB := listAs(tenantB, builderB) + if len(gotB) != 1 || gotB[0].Name != "it_b_contacts_admin" || len(gotB[0].Grants) != 2 { + t.Fatalf("tenant B's token sees %+v; want only its own role with its 2 grants", gotB) + } + if g, r := count("SELECT COUNT(*) FROM acl_role_actions"), count("SELECT COUNT(*) FROM acl_roles"); g != grantsBefore || r != rolesBefore { + t.Fatalf("after two reads: %d grants, %d roles; want %d and %d (a read writes nothing)", g, r, grantsBefore, rolesBefore) } } From 7dc109d2089a64d1e201cc61601199509a8462ed Mon Sep 17 00:00:00 2001 From: doxuta Date: Tue, 27 Oct 2026 11:45:53 +0700 Subject: [PATCH 9/9] test(studio): the access page under ?app= draws the card's built table and its ghost cell (#23) AccessMatrix's test fed accessGhost directly; this one renders AccessPage with ?app=clinic and a previewed card on a table outside it, so the page's wiring (the drawn tables as 'shown') is pinned too. Co-Authored-By: Claude Opus 5.5 --- .../studio/build/AccessPage.test.tsx | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/nexus-web/components/studio/build/AccessPage.test.tsx b/nexus-web/components/studio/build/AccessPage.test.tsx index f905021..5e1f38e 100644 --- a/nexus-web/components/studio/build/AccessPage.test.tsx +++ b/nexus-web/components/studio/build/AccessPage.test.tsx @@ -47,6 +47,7 @@ vi.mock("@/lib/admin", async (orig) => ({ })); import { AccessPage } from "./AccessPage"; +import { mkChange, WithPreview } from "@/test/previewProbe"; const ROLES = [ role("r1", "Lễ tân", [{ entityName: "invoice", action: "view", accessLevel: "all" }]), @@ -152,6 +153,24 @@ describe("app filter and related column", () => { expect(screen.getByRole("combobox", { name: "Xem theo app" })).toHaveValue("clinic"); }); + // issue #23: the assistant's access card names a built table the ?app= filter leaves out; the page still draws that + // table's column, so the card's ghost cell is there to see. + it("?app= that leaves out the card's table still draws its column and the ghost cell", async () => { + const after = { grants: [{ entityName: "invoice", action: "view", accessLevel: "all" }], labels: { invoice: "Hoá đơn" } }; + const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } }); + render( + + + + + , + ); + const td = (await screen.findByText("Chỉ xem · Đề xuất")).closest("td")!; + expect(td.className).toContain("nx-proposed"); + expect(within(td).getByRole("combobox", { name: "Kế toán trên Hoá đơn: Không thấy" })).toBeInTheDocument(); + expect(screen.getByRole("combobox", { name: /Lễ tân trên Lịch hẹn/ })).toBeInTheDocument(); + }); + it("?bang= narrows to that table and offers the way back to all", async () => { renderPage({ bang: "invoice" }); await screen.findByRole("combobox", { name: /Lễ tân trên Hoá đơn/ });