Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions nexus-platform/internal/ai/list_roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,11 @@ package ai
import (
"context"
"encoding/json"
"slices"
"strings"
"testing"

"nexus/platform/internal/services"
)

func TestListRoles(t *testing.T) {
Expand Down Expand Up @@ -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)
}
}
31 changes: 23 additions & 8 deletions nexus-platform/internal/ai/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -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: "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{},
"type": "object",
"properties": map[string]any{
"grants": map[string]any{"type": "boolean", "description": "true: kèm quyền hiện có của từng vai."},
},
},
},
},
Expand Down Expand Up @@ -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":
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -3104,8 +3118,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 {
Expand Down
59 changes: 53 additions & 6 deletions nexus-platform/internal/ai/tools_access.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -185,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)
Expand All @@ -215,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: 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 {
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).
Expand All @@ -239,7 +285,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 {
Expand Down
17 changes: 17 additions & 0 deletions nexus-platform/internal/ai/tools_access_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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})
Expand Down
17 changes: 14 additions & 3 deletions nexus-platform/internal/ai/tools_explain_access_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package ai
import (
"context"
"encoding/json"
"slices"
"strings"
"testing"

Expand All @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion nexus-platform/internal/audit/audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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)
}
}
18 changes: 18 additions & 0 deletions nexus-platform/internal/auth/user_repository_crud.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading