Skip to content
Merged
134 changes: 134 additions & 0 deletions nexus-platform/internal/ai/list_roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,12 @@ package ai
import (
"context"
"encoding/json"
"fmt"
"slices"
"strings"
"testing"

"nexus/platform/internal/auth"
"nexus/platform/internal/services"
)

Expand Down Expand Up @@ -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:<user 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)
}
})
}
2 changes: 2 additions & 0 deletions nexus-platform/internal/ai/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
39 changes: 31 additions & 8 deletions nexus-platform/internal/ai/tools_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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.
Expand Down
17 changes: 16 additions & 1 deletion nexus-platform/internal/ai/tools_explain_access_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
}
}
Expand Down
86 changes: 86 additions & 0 deletions nexus-platform/internal/auth/role_grants_integration_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading