diff --git a/nexus-platform/internal/ai/list_roles_test.go b/nexus-platform/internal/ai/list_roles_test.go index 35e076a..0ac12fb 100644 --- a/nexus-platform/internal/ai/list_roles_test.go +++ b/nexus-platform/internal/ai/list_roles_test.go @@ -10,10 +10,12 @@ package ai import ( "context" "encoding/json" + "fmt" "slices" "strings" "testing" + "nexus/platform/internal/auth" "nexus/platform/internal/services" ) @@ -107,3 +109,135 @@ func TestListRoles_GrantsNeedTheRoleReader(t *testing.T) { t.Fatalf("out = %s; want INVALID_ARGS", out) } } + +// Issue #67: a role deleted between the role list and its grants is skipped, not a failed read. The +// grants come from one snapshot of every role, so a role gone meanwhile is simply not in it. The fake +// stands in for that snapshot: the property itself is InnoDB's consistent read of ONE SELECT +// (ListRoleGrants). role_grants_integration_test.go checks a role deleted before the read is absent; a +// delete racing the statement is not exercised. +func TestListRoles_GrantsSkipARoleDeletedMeanwhile(t *testing.T) { + e := accessExecutor(nil) + e.reader.(*readerWithAccessProbes).probes.Roles.(*fakeAccessRoles).gone = map[string]bool{"r-ops": true} + out := e.execute(context.Background(), "list_roles", `{"grants":true}`) + var got struct { + OK bool `json:"ok"` + Result struct { + Roles []struct { + Name string `json:"name"` + } `json:"roles"` + } `json:"result"` + } + if err := json.Unmarshal([]byte(out), &got); err != nil || !got.OK { + t.Fatalf("out = %s (%v); want ok with the roles that still exist", out, err) + } + var names []string + for _, r := range got.Result.Roles { + names = append(names, r.Name) + } + if strings.Join(names, ",") != "crm_sales_rep,crm_sales_manager,tenant_owner,viewer" { + t.Fatalf("roles = %v; want the four roles left, without the deleted ops", names) + } +} + +// Issue #67: list_roles {grants: true} is bounded like snapshot_model and says what it cut. The issue's +// tenant (20 roles × 100 tables × 4 actions) was ≈ 550 KB in one tool result. +func TestListRoles_GrantsAreBoundedAndSayWhatWasCut(t *testing.T) { + type role struct { + Name string `json:"name"` + Grants []services.RoleActionView `json:"grants"` + GrantsTruncated bool `json:"grantsTruncated"` + GrantsTotal int `json:"grantsTotal"` + } + type result struct { + Roles []role `json:"roles"` + RolesTruncated bool `json:"rolesTruncated"` + RolesTotal int `json:"rolesTotal"` + Note string `json:"note"` + } + run := func(t *testing.T, roles, tables int, smallFrom int) (result, string) { + t.Helper() + fake := &fakeAccessRoles{byTenant: map[string][]auth.Role{}, actions: map[string][]auth.RoleAction{}} + for i := range roles { + id := fmt.Sprintf("r%03d", i) + fake.byTenant["t1"] = append(fake.byTenant["t1"], auth.Role{ID: id, TenantID: "t1", Name: fmt.Sprintf("role_%03d", i), Label: "Vai"}) + n := tables + if i >= smallFrom { + n = 1 + } + for tb := range n { + for _, a := range []string{"create", "delete", "edit", "view"} { + fake.actions[id] = append(fake.actions[id], auth.RoleAction{EntityName: fmt.Sprintf("crm_table_%03d", tb), Action: a, AccessLevel: "all"}) + } + } + } + e := &toolExecutor{reader: ReaderWithAccessProbes(&fakeMetaReader{}, &AccessProbes{Roles: fake}), tenantID: "t1"} + out := e.execute(context.Background(), "list_roles", `{"grants":true}`) + var got struct { + OK bool `json:"ok"` + Result result `json:"result"` + } + if err := json.Unmarshal([]byte(out), &got); err != nil || !got.OK { + t.Fatalf("out = %.300s (%v); want ok", out, err) + } + return got.Result, out + } + + t.Run("the issue's tenant stays small", func(t *testing.T) { + _, out := run(t, 20, 100, 20) + if len(out) > 100_000 { + t.Fatalf("20 roles × 100 tables × 4 actions = %d bytes; want at most 100 KB", len(out)) + } + }) + + t.Run("roles and grants past the caps are cut and counted", func(t *testing.T) { + res, _ := run(t, maxListedRoles+5, 100, 1) + if len(res.Roles) != maxListedRoles || !res.RolesTruncated || res.RolesTotal != maxListedRoles+5 { + t.Fatalf("roles = %d, truncated %v, total %d; want %d shown of %d", len(res.Roles), res.RolesTruncated, res.RolesTotal, maxListedRoles, maxListedRoles+5) + } + big, small := res.Roles[0], res.Roles[1] + if len(big.Grants) != maxListedGrantsPerRole || !big.GrantsTruncated || big.GrantsTotal != 400 { + t.Fatalf("big role: %d grants, truncated %v, total %d; want %d shown of 400", len(big.Grants), big.GrantsTruncated, big.GrantsTotal, maxListedGrantsPerRole) + } + // The first grants in the stored order are the ones kept (the store sorts "*" before every table + // name, role_grants_integration_test.go). + if big.Grants[0].EntityName != "crm_table_000" || big.Grants[0].Action != "create" { + t.Errorf("first kept grant = %+v; want the first stored one", big.Grants[0]) + } + if len(small.Grants) != 4 || small.GrantsTruncated || small.GrantsTotal != 0 { + t.Errorf("small role = %+v; want its 4 grants and no cut flag", small) + } + if !strings.Contains(res.Note, "explain_access") { + t.Errorf("note = %q; want what was cut and where to ask instead", res.Note) + } + }) + + // The caps count rows, not bytes: the ceiling is the longest names the schema allows — a 26-char table + // (ddl identifierPattern), a 32-char "field:" level, a 100-char role name and 150-char label. + t.Run("the worst case at the caps stays under the ceiling the comment states", func(t *testing.T) { + fake := &fakeAccessRoles{byTenant: map[string][]auth.Role{}, actions: map[string][]auth.RoleAction{}} + for i := range maxListedRoles { + id := fmt.Sprintf("r%03d", i) + fake.byTenant["t1"] = append(fake.byTenant["t1"], auth.Role{ID: id, TenantID: "t1", + Name: fmt.Sprintf("%03d%s", i, strings.Repeat("r", 97)), Label: strings.Repeat("L", 150)}) + for tb := range maxListedGrantsPerRole / 4 { + for _, a := range []string{"create", "delete", "edit", "view"} { + fake.actions[id] = append(fake.actions[id], auth.RoleAction{EntityName: fmt.Sprintf("%03d%s", tb, strings.Repeat("e", 23)), + Action: a, AccessLevel: "field:" + strings.Repeat("f", 26)}) + } + } + } + e := &toolExecutor{reader: ReaderWithAccessProbes(&fakeMetaReader{}, &AccessProbes{Roles: fake}), tenantID: "t1"} + out := e.execute(context.Background(), "list_roles", `{"grants":true}`) + t.Logf("worst case at the caps: %d bytes", len(out)) + if len(out) > 300_000 { + t.Fatalf("%d roles × %d grants with the longest names = %d bytes; want at most 300 KB", maxListedRoles, maxListedGrantsPerRole, len(out)) + } + }) + + t.Run("nothing cut, no flag", func(t *testing.T) { + res, out := run(t, 3, 2, 3) + if res.RolesTruncated || res.Note != "" || strings.Contains(out, "Truncated") { + t.Fatalf("out = %s; want no cut flag or note when everything fits", out) + } + }) +} diff --git a/nexus-platform/internal/ai/tools.go b/nexus-platform/internal/ai/tools.go index e86ab3f..ecc0f05 100644 --- a/nexus-platform/internal/ai/tools.go +++ b/nexus-platform/internal/ai/tools.go @@ -3128,6 +3128,8 @@ type accessRoleLookup interface { // ListRoles + ListActionsForRole back propose_access: the role it names and that role's grants. ListRoles(ctx context.Context, tenantID string) ([]auth.Role, error) ListActionsForRole(ctx context.Context, tenantID, roleID string) ([]auth.RoleAction, error) + // ListRoleGrants backs list_roles {grants: true}: every role with its grants, one query (issue #67). + ListRoleGrants(ctx context.Context, tenantID string) ([]auth.RoleGrants, error) } // publishCutoff is when the workspace was last published (nil = never delivered). Signature of diff --git a/nexus-platform/internal/ai/tools_access.go b/nexus-platform/internal/ai/tools_access.go index 6bb3374..6ffa71c 100644 --- a/nexus-platform/internal/ai/tools_access.go +++ b/nexus-platform/internal/ai/tools_access.go @@ -224,11 +224,20 @@ func (e *toolExecutor) proposeAccess(ctx context.Context, argsJSON string) strin return toolOK(out) } +// list_roles {grants: true} output caps (issue #67), like snapshot_model's: a safety ceiling, not a +// working limit (the CRM pack's widest role holds about 40 grants). The caps count rows, not bytes: 40 × 60 +// grant rows with the longest names the schema allows is about 275 KB (pinned in list_roles_test.go); the +// issue's tenant (20 roles × 100 tables × 4 actions) was 550 KB in one result. Grants come sorted by table, +// and "*" sorts before every table name only because a table name starts with a letter (ddl identifierPattern; +// in utf8mb4_unicode_ci "_" sorts before "*"), so every-table grants are the last cut. +const ( + maxListedRoles = 40 + maxListedGrantsPerRole = 60 +) + // 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 { @@ -237,19 +246,33 @@ func (e *toolExecutor) listRoleGrants(ctx context.Context) string { if probes == nil || probes.Roles == nil { 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) + // One snapshot of every role with its grants: a role deleted meanwhile is absent, not a failed read. + roles, err := probes.Roles.ListRoleGrants(ctx, e.tenantID) if err != nil { return toolErr("ROLES_READ_FAILED: %v", err) } + res := map[string]any{} + cut := len(roles) > maxListedRoles + if cut { + res["rolesTruncated"], res["rolesTotal"] = true, len(roles) + roles = roles[:maxListedRoles] + } 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) + row := map[string]any{"name": r.Role.Name, "label": r.Role.Label} + acts := r.Actions + if len(acts) > maxListedGrantsPerRole { + row["grantsTruncated"], row["grantsTotal"] = true, len(acts) + acts, cut = acts[:maxListedGrantsPerRole], true } - out = append(out, map[string]any{"name": r.Name, "label": r.Label, "grants": grantViews(acts)}) + row["grants"] = grantViews(acts) + out = append(out, row) + } + res["roles"] = out + if cut { + res["note"] = fmt.Sprintf("đã cắt bớt: tối đa %d vai, %d quyền mỗi vai (rolesTotal / grantsTotal là số thật) — quyền của một người trên một bảng cụ thể: hỏi explain_access", maxListedRoles, maxListedGrantsPerRole) } - return toolOK(map[string]any{"roles": out}) + return toolOK(res) } // grantViews is a role's grant rows as the API and the access card show them; never nil. diff --git a/nexus-platform/internal/ai/tools_explain_access_test.go b/nexus-platform/internal/ai/tools_explain_access_test.go index 8ab752e..c07a3d8 100644 --- a/nexus-platform/internal/ai/tools_explain_access_test.go +++ b/nexus-platform/internal/ai/tools_explain_access_test.go @@ -54,6 +54,21 @@ type fakeAccessRoles struct { byID map[string]*auth.Role byTenant map[string][]auth.Role // ListRoles (propose_access) actions map[string][]auth.RoleAction // role id -> grants + // gone: roles deleted after ListRoles was read — ListActionsForRole no longer finds them and a + // later ListRoleGrants snapshot does not hold them (issue #67). + gone map[string]bool +} + +// ListRoleGrants is the one-query snapshot (auth.RoleRepository.ListRoleGrants): this tenant's roles, +// each with its grants (never nil), without the roles deleted meanwhile. +func (f *fakeAccessRoles) ListRoleGrants(_ context.Context, tenantID string) ([]auth.RoleGrants, error) { + out := []auth.RoleGrants{} + for _, r := range f.byTenant[tenantID] { + if !f.gone[r.ID] { + out = append(out, auth.RoleGrants{Role: r, Actions: append([]auth.RoleAction{}, f.actions[r.ID]...)}) + } + } + return out, nil } func (f *fakeAccessRoles) GetRoleByID(_ context.Context, _, id string) (*auth.Role, error) { @@ -69,7 +84,7 @@ func (f *fakeAccessRoles) ListRoles(_ context.Context, tenantID string) ([]auth. func (f *fakeAccessRoles) ListActionsForRole(_ context.Context, tenantID, roleID string) ([]auth.RoleAction, error) { for _, r := range f.byTenant[tenantID] { - if r.ID == roleID { + if r.ID == roleID && !f.gone[roleID] { return f.actions[roleID], nil } } diff --git a/nexus-platform/internal/auth/role_grants_integration_test.go b/nexus-platform/internal/auth/role_grants_integration_test.go new file mode 100644 index 0000000..8d7db8b --- /dev/null +++ b/nexus-platform/internal/auth/role_grants_integration_test.go @@ -0,0 +1,86 @@ +//go:build integration + +// RoleRepository.ListRoleGrants against a real MySQL (issue #67): list_roles {grants: true} reads every +// role of the tenant with its grants in one query, so a role deleted meanwhile is absent instead of +// failing the read. Here the role is deleted before the read; a delete racing the one SELECT is left to +// InnoDB's consistent read and not exercised. +// +// bash scripts/run-integration.sh -run 'TestListRoleGrants_' ./internal/auth/ +package auth + +import ( + "context" + "reflect" + "testing" + + "github.com/google/uuid" +) + +func TestListRoleGrants_EveryRoleOfTheTenantWithItsGrantsInOrder(t *testing.T) { + ctx := context.Background() + f := manageSetup(t) + repo := NewRoleRepository(f.db) + role := func(tenant, name string, grants ...[3]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, "L "+name).Error; err != nil { + t.Fatalf("seed role %s: %v", name, err) + } + for _, g := range grants { + if err := f.db.Exec(`INSERT INTO acl_role_actions (id, role_id, entity_name, action, access_level) VALUES (?, ?, ?, ?, ?)`, + uuid.NewString(), id, g[0], g[1], g[2]).Error; err != nil { + t.Fatalf("seed grant %v: %v", g, err) + } + } + return id + } + // Inserted out of order: the read sorts roles by name and grants by entity, then action. "*" sorts before + // every table name (they start with a letter), so list_roles' per-role cap cuts every-table grants last. + rep := role(f.tenant, "rg_rep", [3]string{"tickets", "view", "owner"}, [3]string{"contacts", "view", "all"}, [3]string{"contacts", "edit", "owner"}, + [3]string{"*", "view", "owner"}, [3]string{"a_first", "view", "all"}) + empty := role(f.tenant, "rg_empty") + star := role(f.tenant, "rg_all", [3]string{"*", "view", "all"}) + gone := role(f.tenant, "rg_gone", [3]string{"contacts", "delete", "all"}) + role(f.other, "rg_foreign", [3]string{"contacts", "delete", "all"}) // another tenant's role and grant + if err := repo.DeleteRole(ctx, f.tenant, gone); err != nil { + t.Fatalf("delete: %v", err) + } + + got, err := repo.ListRoleGrants(ctx, f.tenant) + if err != nil { + t.Fatalf("ListRoleGrants: %v", err) + } + type view struct { + ID, Name, Label string + Grants [][3]string + } + views := make([]view, len(got)) + for i, g := range got { + if g.Role.TenantID != f.tenant { + t.Fatalf("role %q carries tenant %q; want %q", g.Role.Name, g.Role.TenantID, f.tenant) + } + views[i] = view{ID: g.Role.ID, Name: g.Role.Name, Label: g.Role.Label, Grants: [][3]string{}} + for _, a := range g.Actions { + if a.RoleID != g.Role.ID || a.ID == "" { + t.Fatalf("grant %+v of role %q: want its own id and the role's id", a, g.Role.Name) + } + views[i].Grants = append(views[i].Grants, [3]string{a.EntityName, a.Action, a.AccessLevel}) + } + } + want := []view{ + {ID: star, Name: "rg_all", Label: "L rg_all", Grants: [][3]string{{"*", "view", "all"}}}, + {ID: empty, Name: "rg_empty", Label: "L rg_empty", Grants: [][3]string{}}, + {ID: rep, Name: "rg_rep", Label: "L rg_rep", Grants: [][3]string{{"*", "view", "owner"}, {"a_first", "view", "all"}, {"contacts", "edit", "owner"}, {"contacts", "view", "all"}, {"tickets", "view", "owner"}}}, + } + if !reflect.DeepEqual(views, want) { + t.Fatalf("roles = %+v\nwant %+v (this tenant only, the deleted role absent, sorted)", views, want) + } + if got[1].Actions == nil { + t.Fatal("a role without a grant has nil Actions; want an empty list") + } + + none, err := repo.ListRoleGrants(ctx, uuid.NewString()) + if err != nil || none == nil || len(none) != 0 { + t.Fatalf("a tenant without roles = %#v, %v; want an empty, non-nil list", none, err) + } +} diff --git a/nexus-platform/internal/auth/role_repository.go b/nexus-platform/internal/auth/role_repository.go index 33c8b3f..071e9f3 100644 --- a/nexus-platform/internal/auth/role_repository.go +++ b/nexus-platform/internal/auth/role_repository.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "time" "gorm.io/gorm" "gorm.io/gorm/clause" @@ -325,6 +326,66 @@ func (r *RoleRepository) ListActionsForRole(ctx context.Context, tenantID, roleI return actions, nil } +// RoleGrants is one role of a tenant with its grant rows (ListRoleGrants). Each grant carries its id, +// role id, entity, action and access level; its timestamps are not read. +type RoleGrants struct { + Role Role + Actions []RoleAction // never nil: a role without a grant has an empty list +} + +// ListRoleGrants returns every role of the tenant with its grants in ONE query (issue #67): acl_roles +// LEFT JOIN acl_role_actions, pinned to tenant_id. One statement reads one snapshot, so a role deleted +// meanwhile is simply absent (list_roles used to read the role list and then each role's grants, and a +// role deleted in between failed the whole read). Roles by name, grants by entity then action, the +// order ListRoles and ListActionsForRole give. +func (r *RoleRepository) ListRoleGrants(ctx context.Context, tenantID string) ([]RoleGrants, error) { + var rows []struct { + RoleID string + TenantID string + Name string + Label string + CreatedAt time.Time + UpdatedAt time.Time + GrantID *string + EntityName *string + Action *string + AccessLevel *string + } + err := r.db.WithContext(ctx). + Table("acl_roles"). + Select("acl_roles.id AS role_id, acl_roles.tenant_id, acl_roles.name, acl_roles.label, acl_roles.created_at, acl_roles.updated_at, "+ + "acl_role_actions.id AS grant_id, acl_role_actions.entity_name, acl_role_actions.action, acl_role_actions.access_level"). + Joins("LEFT JOIN acl_role_actions ON acl_role_actions.role_id = acl_roles.id"). + Where("acl_roles.tenant_id = ?", tenantID). + Order("acl_roles.name ASC, acl_roles.id ASC, acl_role_actions.entity_name ASC, acl_role_actions.action ASC"). + Scan(&rows).Error + if err != nil { + return nil, fmt.Errorf("auth.RoleRepository.ListRoleGrants: %w", err) + } + out := []RoleGrants{} + for _, row := range rows { + if n := len(out); n == 0 || out[n-1].Role.ID != row.RoleID { + out = append(out, RoleGrants{ + Role: Role{ID: row.RoleID, TenantID: row.TenantID, Name: row.Name, Label: row.Label, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt}, + Actions: []RoleAction{}, + }) + } + if row.GrantID == nil { // LEFT JOIN: a role without a grant + continue + } + g := &out[len(out)-1] + g.Actions = append(g.Actions, RoleAction{ID: *row.GrantID, RoleID: row.RoleID, EntityName: deref(row.EntityName), Action: deref(row.Action), AccessLevel: deref(row.AccessLevel)}) + } + return out, nil +} + +func deref(s *string) string { + if s == nil { + return "" + } + return *s +} + // LoadActionsForACL loads a role's grants for the per-request ACL decision. It is the HOT PATH // (runs on every dynamic /:entity request for a non-admin) and is tenant-pinned via a JOIN to // acl_roles: a role_id from another tenant returns ZERO grants → default-deny (D4 forge-tenant diff --git a/nexus-platform/internal/services/role_service_audit_test.go b/nexus-platform/internal/services/role_service_audit_test.go index 94bd820..7128ab3 100644 --- a/nexus-platform/internal/services/role_service_audit_test.go +++ b/nexus-platform/internal/services/role_service_audit_test.go @@ -9,6 +9,7 @@ import ( "testing" "nexus/platform/internal/audit" + "nexus/platform/internal/auth" ) func TestRole_AuditRowsNameTheRole(t *testing.T) { @@ -56,3 +57,33 @@ func TestRole_AuditRowsNameTheRole(t *testing.T) { t.Errorf("grants-only update diff = %+v; want the changed actions kept", d) } } + +// RecreateRole makes the in-memory repo a roleRecreator: the role and its grants come back under their id. +func (f *fakeRoleRepo) RecreateRole(ctx context.Context, role *auth.Role, actions []auth.RoleAction, _ []auth.FieldACL, _ []string) (int64, error) { + return 0, f.CreateRole(ctx, role, actions) +} + +// Issue #67: Recreate (the undo of a role delete, publish revert) writes its create row on the role's +// own id too, so GET /audit-log?entityName=__role__&recordId= keeps the whole life of the role. +func TestRole_RecreateAuditRowCarriesTheRoleID(t *testing.T) { + ctx := context.Background() + svc, repo := newRoleSvc() + svc.WithRecreator(repo) + cap := &captureAuditor{} + svc.WithAuditor(cap) + before := RoleView{ID: "rid-gone", TenantID: "t1", Name: "sales", Label: "Sales", + Actions: []RoleActionView{{EntityName: "contacts", Action: "view", AccessLevel: "all"}}} + if _, err := svc.Recreate(ctx, "t1", "rid-gone", before, nil, nil); err != nil { + t.Fatalf("recreate: %v", err) + } + if len(cap.events) != 1 { + t.Fatalf("events = %d; want the one create row", len(cap.events)) + } + e := cap.events[0] + if e.TenantID != "t1" || e.EntityName != audit.RoleMeta || e.Action != audit.ActionCreate || e.RecordID != "rid-gone" { + t.Fatalf("event = %s %s/%q in %q; want create __role__ with record_id = the role's id \"rid-gone\" in t1", e.Action, e.EntityName, e.RecordID, e.TenantID) + } + if e.Diff == nil || e.Diff.After["name"] != "sales" { + t.Errorf("diff = %+v; want the recreated role's name", e.Diff) + } +} diff --git a/nexus-web/components/screens/admin/AuditLog.test.tsx b/nexus-web/components/screens/admin/AuditLog.test.tsx index 328f62f..a98c1e1 100644 --- a/nexus-web/components/screens/admin/AuditLog.test.tsx +++ b/nexus-web/components/screens/admin/AuditLog.test.tsx @@ -270,6 +270,74 @@ describe("AuditLog", () => { }); }); + // issue #67: a role update's diff carries the role's name on both sides (so the row names the role); + // drawn as a "name | X | X" row it read as a rename. A key whose value did not change is not drawn, + // and a role row names its role in the record column instead. + describe("unchanged keys (issue #67)", () => { + const GRANT = { entityName: "crm_accounts", action: "view", accessLevel: "all" }; + const ROLE: AuditEntry = { + id: "r1", actorUserId: "u1", entityName: "__role__", recordId: "4f1c0de0-0000-4000-8000-000000000003", action: "update", + diff: { + before: { name: "crm_sales_rep", actions: [GRANT] }, + after: { name: "crm_sales_rep", actions: [GRANT, { entityName: "tickets", action: "view", accessLevel: "all" }] }, + }, + at: "2026-10-27T01:00:00Z", + }; + const SAME: AuditEntry = { ...ROLE, id: "r2", diff: { before: { name: "crm_sales_rep" }, after: { name: "crm_sales_rep" } } }; + + it("a grants-only role update shows the grants, no name row, and names the role in the record column", async () => { + vi.mocked(listAuditFiltered).mockResolvedValue({ entries: [ROLE], limit: 50 }); + render(); + const diff = await screen.findByRole("table", { name: "Trường thay đổi" }); + expect(within(diff).getByText("actions")).toBeInTheDocument(); + expect(within(diff).queryByText("name")).not.toBeInTheDocument(); + expect(within(diff).queryByText("crm_sales_rep")).not.toBeInTheDocument(); + expect(screen.getByText("crm_sales_rep").closest("td")).not.toBeNull(); + expect(screen.queryByText("4f1c0de0")).not.toBeInTheDocument(); + // The full record id stays on the cell's title, to cross-reference the role by id. + expect(screen.getByText("crm_sales_rep")).toHaveAttribute("title", `crm_sales_rep · ${ROLE.recordId}`); + }); + + it("a save that changed nothing has no diff to open", async () => { + vi.mocked(listAuditFiltered).mockResolvedValue({ entries: [SAME, UPDATE], limit: 50 }); + render(); + expect(await screen.findByText("crm_sales_rep")).toBeInTheDocument(); // the role row, named + // Only the contact update keeps a toggle; the role row that changed nothing has none. + expect(toggles()).toHaveLength(1); + expect(toggles()[0]).toHaveAccessibleName(/Liên hệ/); + }); + + it("a role rename still shows the name row", async () => { + const RENAME: AuditEntry = { ...ROLE, diff: { before: { name: "crm_sales_rep" }, after: { name: "crm_sales_agent" } } }; + vi.mocked(listAuditFiltered).mockResolvedValue({ entries: [RENAME], limit: 50 }); + render(); + const diff = await screen.findByRole("table", { name: "Trường thay đổi" }); + expect(within(diff).getAllByRole("rowheader").map((th) => th.textContent)).toEqual(["name"]); + }); + + // Only the role's padded name is hidden. A sensitive (PII) field's change is written "[redacted]" on BOTH + // sides on purpose (services/audit_redact.go keeps the key: who changed what field, when), so the same + // value on both sides of any other row is still a change to show. + const PII: AuditEntry = { ...UPDATE, diff: { + before: { cccd: "[redacted]", stage: "new" }, after: { cccd: "[redacted]", stage: "won" }, + } }; + it("a sensitive field redacted on both sides is still drawn as a change", async () => { + vi.mocked(listAuditFiltered).mockResolvedValue({ entries: [PII], limit: 50 }); + render(); + const diff = await screen.findByRole("table", { name: "Trường thay đổi" }); + expect(within(diff).getAllByRole("rowheader").map((th) => th.textContent)).toEqual(["cccd", "stage"]); + expect(within(diff).getAllByText("[redacted]")).toHaveLength(2); + }); + + it("an update of a sensitive field only still has a diff to open", async () => { + const ONLY_PII: AuditEntry = { ...PII, diff: { before: { cccd: "[redacted]" }, after: { cccd: "[redacted]" } } }; + vi.mocked(listAuditFiltered).mockResolvedValue({ entries: [ONLY_PII], limit: 50 }); + render(); + await screen.findAllByText("Nexus Admin"); + expect(toggles()).toHaveLength(1); + }); + }); + // specs/062 L3 T056: the builder's name on the customer's trail, the layout rows, the session rows. describe("builder rows (specs/062 L3)", () => { const BUILDER = "b0000000-aaaa-4bbb-8ccc-000000000001"; diff --git a/nexus-web/components/screens/admin/AuditLog.tsx b/nexus-web/components/screens/admin/AuditLog.tsx index a87d415..9f187e1 100644 --- a/nexus-web/components/screens/admin/AuditLog.tsx +++ b/nexus-web/components/screens/admin/AuditLog.tsx @@ -79,13 +79,21 @@ function renderValue(v: unknown): string { if (typeof v === "object") return JSON.stringify(v); return String(v); } -function buildDiffRows(diff: { before?: Record; after?: Record }) { - const keys = Array.from(new Set([...Object.keys(diff.before ?? {}), ...Object.keys(diff.after ?? {})])); - return keys.map((k) => ({ field: k, before: renderValue(diff.before?.[k]), after: renderValue(diff.after?.[k]) })); +// A role update carries the role's name on both sides so the row names the role (#66); drawn, an unchanged name +// read as a rename, so that one key is dropped (issue #67). Only that one: elsewhere the same value on both +// sides IS a change, e.g. a sensitive field is written "[redacted]" on both sides on purpose (audit_redact.go). +function buildDiffRows(entry: AuditEntry) { + const before = entry.diff?.before ?? {}; + const after = entry.diff?.after ?? {}; + const paddedName = entry.entityName === ROLE_META && before.name === after.name; + return Array.from(new Set([...Object.keys(before), ...Object.keys(after)])) + .filter((k) => !(paddedName && k === "name")) + .map((k) => ({ field: k, before: renderValue(before[k]), after: renderValue(after[k]) })); } const SESSION_META = "__workspace_session__"; const LAYOUT_META = "__layout__"; +const ROLE_META = "__role__"; /** The action word of a row: a workspace session is "Mở"/"Đóng" (D-9 reuses create/delete), the rest by action. */ function rowVerb(entry: AuditEntry): string { @@ -111,6 +119,14 @@ function layoutTarget(entry: AuditEntry, tableLabel: (entityName: string) => str return [tableLabel(entity), view ? t(viewKey) : ""].filter(Boolean).join(" · "); } +/** A role row's record cell names the role (issue #67): its name is in the diff, on both sides of an update, but an + * unchanged name is no longer drawn there. */ +function roleTarget(entry: AuditEntry): string | undefined { + if (entry.entityName !== ROLE_META) return undefined; + const name = entry.diff?.after?.name ?? entry.diff?.before?.name; + return typeof name === "string" && name ? name : undefined; +} + /** The loaded list for one request key (filter + refresh tick). */ interface LoadedPage { key: string; @@ -406,7 +422,7 @@ function AuditRow({ entry, actorName, entityLabel, tableLabel, defaultOpen }: { }) { const [open, setOpen] = useState(!!defaultOpen); const diffId = useId(); - const diffRows = entry.diff ? buildDiffRows(entry.diff) : []; + const diffRows = buildDiffRows(entry); const hasDiff = diffRows.length > 0; // Who acted, in order of trust: a user of THIS customer (resolved by the caller, which also maps the // engine's synthetic ids); else the label the SERVER computed for a Nexus builder who worked in this @@ -416,7 +432,7 @@ function AuditRow({ entry, actorName, entityLabel, tableLabel, defaultOpen }: { const actorDisplay = actorName ?? entry.actorLabel ?? SYSTEM_ACTORS[entry.actorUserId] ?? shortId(entry.actorUserId); const verb = rowVerb(entry); const until = sessionUntil(entry); - const target = layoutTarget(entry, tableLabel); + const target = layoutTarget(entry, tableLabel) ?? roleTarget(entry); const at = fmtAt(entry.at); const toggleLabel = tf("page.audit.toggleDiff", { actor: actorDisplay, entity: entityLabel, at }); @@ -457,7 +473,7 @@ function AuditRow({ entry, actorName, entityLabel, tableLabel, defaultOpen }: { {target - ?
{target}
+ ?
{target}
:
{shortId(entry.recordId)}
} diff --git a/nexus-web/components/studio/ChangeList.test.tsx b/nexus-web/components/studio/ChangeList.test.tsx index 0a0ff6e..11bb6bb 100644 --- a/nexus-web/components/studio/ChangeList.test.tsx +++ b/nexus-web/components/studio/ChangeList.test.tsx @@ -37,6 +37,17 @@ describe("ChangeList", () => { expect(row.className).toContain("slds-grid_vertical-align-start"); }); + // issue #67: one long token without a space (a snake_case table or grant) cannot wrap at a space. The text is + // a flex item, whose minimum width is its longest word unless min-w-0 lets it shrink and slds-hyphenate break + // the word; without it the row is wider than the card at 390 px. jsdom cannot measure, so the class is pinned + // here and the width in a real browser (verify-ui). + it("a long snake_case token may shrink and break inside the row (min-w-0)", () => { + const token = "crm_customer_support_ticket_escalation_history_entries.view_all"; + render(); + const text = within(screen.getByRole("listitem")).getByText(token); + expect(text.className.split(" ")).toEqual(expect.arrayContaining(["slds-col", "slds-hyphenate", "min-w-0"])); + }); + it("tone=proposed marks the list as an assistant proposal", () => { const { container } = render(); expect(container.querySelector("ul")?.className).toContain("nx-proposed");