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
5 changes: 2 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ flowchart TD
docker compose up --build
```

Open <http://localhost:8080> (set `NEXUS_PORT` to use another port). Workspace code: `northwind`. For the English UI,
Open <http://localhost:8080> (set `NEXUS_PORT` to use another port; `NEXUS_SUBNET` if its network `10.213.47.0/24`
clashes with one you have, and run `docker compose down` once after changing it). Workspace code: `northwind`. For the English UI,
open <http://localhost:8080/login?lang=en>: the choice is kept for the next pages.

| Who | Email | Password | Sees |
Expand Down Expand Up @@ -242,8 +243,6 @@ on this repository's Security tab.
- **Open issues that matter:**
- [#18](https://github.com/doxuta/nexus/issues/18): a record the rep can read but not edit answers `PUT` with 404,
not 403.
- [#22](https://github.com/doxuta/nexus/issues/22): `/mcp` has no rate limit and no cap on turns per thread, and its
tool filter is a naming rule.
- [#23](https://github.com/doxuta/nexus/issues/23): a table that is still hidden can be reached through N-N links
and `?expand` with a crafted call and a granted role, and `PUT /admin/roles/:id` carries no version.

Expand Down
13 changes: 8 additions & 5 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,14 @@ advisory.
- An `nxm_` key is stored only as a hash ([`internal/auth/mcp_token.go:12-28`]). It is refused when revoked or
expired, when the workspace is retired or suspended, or when its user is no longer an active builder
([`internal/services/mcp_token_service.go:175-233`]). Logout-all and a password change revoke it
([`internal/services/auth_service_extra.go:202-222`]).
([`internal/services/auth_service_extra.go:202-222`]). Lookups of `nxm_` keys not yet seen working are throttled
per IP with the `nxk_` budget, and a working key has its own request budget
([`internal/middleware/mcp_ratelimit.go`](nexus-platform/internal/middleware/mcp_ratelimit.go)). Every per-IP
brake reads the client from X-Forwarded-For only when the peer is in `TRUSTED_PROXY_CIDRS`; behind a proxy, set
it to the proxy's network, or every client shares the proxy's bucket. The one-command demo sets it to its own
network ([`docker-compose.yml`](docker-compose.yml)). A key's thread
takes at most 200 turns and one proposal at most 256 KiB
([`internal/mcpserver/mcpserver.go`](nexus-platform/internal/mcpserver/mcpserver.go)).
- **`/mcp` and `/api/v1` are separate.** `/mcp` is mounted outside `/api/v1`, with its own bearer
([`cmd/server/main.go:1516-1518`]). `/api/v1` refuses an `nxm_` key ([`internal/services/api_key_service.go:496-500`]).
`/mcp` answers an `nxk_` key with 403 and any other non-`nxm_` credential with 401
Expand Down Expand Up @@ -112,9 +119,6 @@ session ([`nexus-web/lib/aiApply.ts:1-5`]), and a draft-class change then needs

- **Access follow-ups ([#23]).** A hidden-new table is still reachable through N-N `Link` and `ListLinked` and through
`?expand`, with a crafted call and an approved grant. `PUT /admin/roles/:id` is unversioned.
- **MCP follow-ups ([#22]).** `/mcp` has no rate limit, no brake on failed key lookups, and no cap on turns per thread.
The MCP tool filter is a naming rule, `propose_field` judges a dependent picklist against the published model, and
the MCP note misdescribes an access card.
- **404 instead of 403 ([#18]).** A record the rep can read but not edit answers `PUT` with 404. Existence is not leaked,
but the reason is misstated.
- **The cutoff's second.** Metadata timestamps have second precision. A version's cutoff names the newest definition
Expand Down Expand Up @@ -192,5 +196,4 @@ session ([`nexus-web/lib/aiApply.ts:1-5`]), and a draft-class change then needs
[#18]: https://github.com/doxuta/nexus/issues/18
[#13]: https://github.com/doxuta/nexus/issues/13
[#19]: https://github.com/doxuta/nexus/issues/19
[#22]: https://github.com/doxuta/nexus/issues/22
[#23]: https://github.com/doxuta/nexus/issues/23
12 changes: 12 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@ services:
BOOTSTRAP_ADMIN_PASSWORD: ${NEXUS_ADMIN_PASS:-Demo-Admin-2026!}
BOOTSTRAP_ADMIN_NAME: Demo Builder
BOOTSTRAP_PLATFORM_OPERATOR: "true"
# Every request reaches the API through Caddy, so without this the per-IP brakes (login, SSO, failed nxk_
# and nxm_ lookups) would see Caddy's address for every client and share ONE bucket. The API trusts
# X-Forwarded-For only from this network (Caddy writes it); the network's subnet is fixed below.
TRUSTED_PROXY_CIDRS: ${TRUSTED_PROXY_CIDRS:-${NEXUS_SUBNET:-10.213.47.0/24}}
AI_ENABLED: ${AI_ENABLED:-false}
AI_GATEWAY_BASE_URL: ${AI_GATEWAY_BASE_URL:-}
AI_GATEWAY_API_KEY: ${AI_GATEWAY_API_KEY:-}
Expand Down Expand Up @@ -102,5 +106,13 @@ services:
volumes:
- ./deploy/Caddyfile.local:/etc/caddy/Caddyfile:ro

# A fixed subnet, so TRUSTED_PROXY_CIDRS (api) can name it. NEXUS_SUBNET=… if it clashes with a network you have;
# after changing it (or pulling this file over an older stack), `docker compose down` once recreates the network.
networks:
default:
ipam:
config:
- subnet: ${NEXUS_SUBNET:-10.213.47.0/24}

volumes:
mysql-data:
5 changes: 5 additions & 0 deletions nexus-platform/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ PORT=8080
# on :3000 (`preview_start nexus-web`). Comma-separated for more than one origin.
CORS_ALLOWED_ORIGINS=http://localhost:3000

# Behind a reverse proxy (Caddy), the networks it reaches the API from, comma-separated. Only these may
# vouch for X-Forwarded-For; empty = the direct peer is the client. Behind a proxy and empty, the per-IP
# brakes (login, SSO, failed nxk_/nxm_ lookups) see one client: the proxy. docker-compose.yml sets it.
# TRUSTED_PROXY_CIDRS=10.213.47.0/24

# MySQL 8 DSN (Go format). Matches docker-compose's local dev DB. REQUIRED — the server refuses to
# start without it (there is no built-in default). loc=UTC: the DB stores timestamps in UTC, and
# loc=Local on a +07 machine labels them with the local offset → every instant 7h off (R2-03).
Expand Down
12 changes: 10 additions & 2 deletions nexus-platform/cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1518,8 +1518,16 @@ func main() {
})
})
// MCP (issue #3): agents propose, humans dispose. Outside /api/v1: its own bearer (nxm_ tokens
// only, refused everywhere else) and the SDK's stateless streamable HTTP transport.
r.Any("/mcp", gin.WrapH(mcpserver.New(mcpTokenSvc, aiAgent, aiSessionStore, tenantFreeze, logger)))
// only, refused everywhere else) and the SDK's stateless streamable HTTP transport. Issue #22: the
// API's brakes in front of it — an IP's lookups of tokens not yet seen working get the API-key
// brake's budget, each working token the data plane's per-key budget.
mcpLimiter := middleware.MCPRateLimit(middleware.MCPRateLimitConfig{
ProbeMax: cfg.APIKeyProbeMaxPerMin,
KeyMax: cfg.DataRateLimitPerMin,
Window: time.Minute,
TrustedProxyCIDRs: cfg.TrustedProxyCIDRs,
})
r.Any("/mcp", mcpLimiter, gin.WrapH(mcpserver.New(mcpTokenSvc, aiAgent, aiSessionStore, tenantFreeze, logger)))

// API v1 routes. RegisterAPIRoutes is the single wiring point shared with the integration
// tests: it mounts the PUBLIC /auth/* endpoints, then a PROTECTED sub-group fronted by
Expand Down
46 changes: 46 additions & 0 deletions nexus-platform/cmd/server/main_wiring_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,11 @@ import (
"go/printer"
"go/token"
"os"
"regexp"
"strings"
"testing"

"nexus/platform/internal/config"
)

// hardeningOptions maps each RegisterAPIRoutes option main.go must pass to the source its argument
Expand Down Expand Up @@ -236,3 +239,46 @@ func isLiteral(e ast.Expr) bool {
_, ok := e.(*ast.BasicLit)
return ok
}

// TestMainWiresTheMCPBrake (issue #22): /mcp sits outside /api/v1, so none of RegisterAPIRoutes'
// limiters reach it. Its own brake must sit in front of the handler on the route itself, with its
// budgets and the trusted proxies read from config (a zero budget switches that brake off).
func TestMainWiresTheMCPBrake(t *testing.T) {
src, err := os.ReadFile("main.go")
if err != nil {
t.Fatalf("read main.go: %v", err)
}
flat := strings.Join(strings.Fields(string(src)), "")
for _, want := range []string{
"mcpLimiter:=middleware.MCPRateLimit(middleware.MCPRateLimitConfig{",
"ProbeMax:cfg.APIKeyProbeMaxPerMin,",
"KeyMax:cfg.DataRateLimitPerMin,",
"TrustedProxyCIDRs:cfg.TrustedProxyCIDRs,",
`r.Any("/mcp",mcpLimiter,gin.WrapH(mcpserver.New(`,
} {
if !strings.Contains(flat, want) {
t.Errorf("main.go lost %q — /mcp would answer guesses and floods unbraked", want)
}
}
}

// TestComposeTrustsItsOwnNetwork (issue #22): in the one-command demo every request reaches the API through
// Caddy, so the per-IP brakes key on X-Forwarded-For only if TRUSTED_PROXY_CIDRS names the compose network.
// Its default must be the network's fixed subnet, and parse.
func TestComposeTrustsItsOwnNetwork(t *testing.T) {
src, err := os.ReadFile("../../../docker-compose.yml")
if err != nil {
t.Fatalf("read docker-compose.yml: %v", err)
}
trusted := regexp.MustCompile(`TRUSTED_PROXY_CIDRS: \$\{TRUSTED_PROXY_CIDRS:-\$\{NEXUS_SUBNET:-([^}]+)\}\}`).FindSubmatch(src)
subnet := regexp.MustCompile(`subnet: \$\{NEXUS_SUBNET:-([^}]+)\}`).FindSubmatch(src)
if trusted == nil || subnet == nil {
t.Fatalf("docker-compose.yml lost the api's TRUSTED_PROXY_CIDRS or the network's fixed subnet: every client behind Caddy shares one bucket")
}
if string(trusted[1]) != string(subnet[1]) {
t.Fatalf("TRUSTED_PROXY_CIDRS defaults to %s but the network is %s", trusted[1], subnet[1])
}
if nets, skipped := config.ParseTrustedProxyCIDRs(string(trusted[1])); len(nets) != 1 || len(skipped) != 0 {
t.Fatalf("TRUSTED_PROXY_CIDRS default %s does not parse: %v", trusted[1], skipped)
}
}
10 changes: 7 additions & 3 deletions nexus-platform/internal/ai/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -1106,8 +1106,9 @@ func (e *toolExecutor) proposeEntity(ctx context.Context, argsJSON string) strin
// config-time validator) before buffering — same parity guarantee as proposeEntity. A name the
// table already has — live, drafted with the table, or proposed earlier this turn (pendingFields) —
// is refused here with the apply path's own code (FIELD_ALREADY_EXISTS), as proposeEntity refuses a
// taken table name (#30 item 3). A table that is neither live nor drafted is left to Apply
// (ENTITY_NOT_FOUND), as before.
// taken table name (#30 item 3). A table that is neither live in this tenant nor drafted (this turn,
// or earlier in an MCP thread) is refused with Apply's ENTITY_NOT_FOUND, as propose_layout does
// (issue #22): no card is filed for a table the tenant does not have.
func (e *toolExecutor) proposeField(ctx context.Context, argsJSON string) string {
var a proposedField
// proposedField only carries the field attributes; entity is a sibling key on the same object.
Expand All @@ -1126,7 +1127,10 @@ func (e *toolExecutor) proposeField(ctx context.Context, argsJSON string) string
return toolErr("%s: %s", code, msg)
}
entity, live, fields, err := e.pendingFields(ctx, withEntity.Entity)
if err != nil && !errors.Is(err, metadata.ErrEntityNotFound) {
if errors.Is(err, metadata.ErrEntityNotFound) {
return toolErr("ENTITY_NOT_FOUND: entity %q không tồn tại và cũng chưa được propose_entity trong lượt này — propose_entity trước rồi propose_field trong CÙNG lượt", withEntity.Entity)
}
if err != nil {
return toolErr("PROPOSE_FIELD_FAILED: %v", err)
}
if i := slices.IndexFunc(fields, func(f metadata.FieldDefinition) bool { return f.Name == a.Name }); i >= 0 {
Expand Down
14 changes: 7 additions & 7 deletions nexus-platform/internal/ai/tools_field_options_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,40 +132,40 @@ func TestTools_ProposeField_OptionsValidationParity(t *testing.T) {
// ---- AI-TOOL-COVERAGE (Wave 4.6): the advanced types now on the AI surface ----
{
name: "auto_number (số chứng từ) → buffered, prefix/padding giữ nguyên",
args: `{"entity":"invoices","name":"invoice_no","label":"Số hoá đơn","fieldType":"auto_number",
args: `{"entity":"patients","name":"invoice_no","label":"Số hoá đơn","fieldType":"auto_number",
"options":{"prefix":"HĐ-","padding":5}}`,
wantOpts: map[string]any{"prefix": "HĐ-", "padding": float64(5)},
},
{
name: "formula (tổng tính toán) → buffered",
args: `{"entity":"invoice_lines","name":"line_total","label":"Thành tiền","fieldType":"formula",
args: `{"entity":"patients","name":"line_total","label":"Thành tiền","fieldType":"formula",
"options":{"formula":"quantity * unit_price","resultType":"currency"}}`,
wantOpts: map[string]any{"formula": "quantity * unit_price", "resultType": "currency"},
},
{
name: "formula thiếu biểu thức → REJECT config-time",
args: `{"entity":"invoices","name":"bad_f","label":"Bad","fieldType":"formula","options":{}}`,
args: `{"entity":"patients","name":"bad_f","label":"Bad","fieldType":"formula","options":{}}`,
wantCode: "FIELD_FORMULA_INVALID",
},
// ---- ai-builder-field-type-parity: user + polymorphic_relation on the AI surface ----
{
name: "user (người phụ trách) không options → buffered",
args: `{"entity":"crm_tasks","name":"assignee","label":"Người phụ trách","fieldType":"user"}`,
args: `{"entity":"patients","name":"assignee","label":"Người phụ trách","fieldType":"user"}`,
},
{
name: "polymorphic_relation với targetEntities → buffered, đích giữ nguyên",
args: `{"entity":"crm_tasks","name":"related_to","label":"Liên quan tới","fieldType":"polymorphic_relation",
args: `{"entity":"patients","name":"related_to","label":"Liên quan tới","fieldType":"polymorphic_relation",
"options":{"targetEntities":["crm_accounts","crm_contacts"]}}`,
wantOpts: map[string]any{"targetEntities": []any{"crm_accounts", "crm_contacts"}},
},
{
name: "polymorphic_relation thiếu targetEntities → FIELD_POLYMORPHIC_NO_TARGETS (không để tới Apply mới 422)",
args: `{"entity":"crm_tasks","name":"related_to","label":"Liên quan tới","fieldType":"polymorphic_relation"}`,
args: `{"entity":"patients","name":"related_to","label":"Liên quan tới","fieldType":"polymorphic_relation"}`,
wantCode: "FIELD_POLYMORPHIC_NO_TARGETS",
},
{
name: "polymorphic_relation tên > 21 ký tự → FIELD_POLYMORPHIC_NAME_TOO_LONG",
args: `{"entity":"crm_tasks","name":"related_record_targets","label":"Liên quan","fieldType":"polymorphic_relation",
args: `{"entity":"patients","name":"related_record_targets","label":"Liên quan","fieldType":"polymorphic_relation",
"options":{"targetEntities":["crm_accounts"]}}`,
wantCode: "FIELD_POLYMORPHIC_NAME_TOO_LONG",
},
Expand Down
92 changes: 92 additions & 0 deletions nexus-platform/internal/ai/tools_field_scope_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package ai

import (
"context"
"slices"
"strings"
"testing"

"go.uber.org/zap"

"nexus/platform/internal/config"
"nexus/platform/internal/metadata"
"nexus/platform/internal/metaversion"
)

// Issue #22 item 1: propose_field judges a dependent picklist against the model the CALLER reads (on a
// delivered project, the builder's drafts), and files no card for a table its tenant does not have.

// draftOverlayReader shows the builder's unpublished edit of tickets.status (a value "hold") only to a
// ctx that carries a ReadDraft Caller, as services.DraftFieldRepo does on a delivered project.
type draftOverlayReader struct{ *fakeMetaReader }

func (r draftOverlayReader) ListFields(ctx context.Context, tenantID, entityID string) ([]metadata.FieldDefinition, error) {
fields, err := r.fakeMetaReader.ListFields(ctx, tenantID, entityID)
if c, ok := metaversion.CallerFrom(ctx); err != nil || !ok || !c.ReadDraft {
return fields, err
}
out := slices.Clone(fields)
for i := range out {
if out[i].Name == "status" {
draft := `{"values":["open","closed","hold"]}`
out[i].Options = &draft
}
}
return out, nil
}

const holdReason = `{"entity":"tickets","name":"hold_reason","label":"Lý do chờ","fieldType":"picklist",
"options":{"values":["parts","other"],"controllingField":"status","dependentValues":{"hold":["parts"]}}}`

func TestTools_ProposeField_SiblingsAreTheCallersDraft(t *testing.T) {
builder := metaversion.WithCaller(context.Background(), metaversion.Caller{UserID: "u-b", TenantID: "tenant-A", HomeTenantID: "tenant-A", IsBuilder: true, ReadDraft: true})
reader := draftOverlayReader{editFixtureReader()}

t.Run("in-app turn", func(t *testing.T) {
e := &toolExecutor{reader: reader, tenantID: "tenant-A"}
if ok, _ := parseToolResult(t, e.execute(builder, "propose_field", holdReason)); !ok || len(e.draft) != 1 {
t.Fatalf("keyed on the builder's draft value: want buffered, got %v (draft %d)", ok, len(e.draft))
}
// The control: without the builder's Caller the published model has no "hold".
e = &toolExecutor{reader: reader, tenantID: "tenant-A"}
if res := e.execute(context.Background(), "propose_field", holdReason); !strings.Contains(res, "FIELD_DEPENDENT_PICKLIST_INVALID") {
t.Fatalf("the published model must refuse it: %s", res)
}
})

t.Run("one MCP call (RunTool)", func(t *testing.T) {
agent := NewAIBuilderAgent(config.AIConfig{}, nil, reader, nil, nil, zap.NewNop())
res, added := agent.RunTool(builder, "tenant-A", "sess-1", nil, "propose_field", holdReason)
if ok, _ := parseToolResult(t, res); !ok || len(added) != 1 {
t.Fatalf("keyed on the builder's draft value: want one proposal, got %s", res)
}
})
}

func TestTools_ProposeField_RefusesATableNotInTheTenant(t *testing.T) {
note := func(entity string) string {
return `{"entity":"` + entity + `","name":"note","label":"Ghi chú","fieldType":"text"}`
}
agent := NewAIBuilderAgent(config.AIConfig{}, nil, editFixtureReader(), nil, nil, zap.NewNop())
// "invoices" is tenant-B's table: it must read as missing to tenant-A, as any unknown name does.
for _, entity := range []string{"ghosts", "invoices"} {
e := &toolExecutor{reader: editFixtureReader(), tenantID: "tenant-A"}
if res := e.execute(context.Background(), "propose_field", note(entity)); !strings.Contains(res, "ENTITY_NOT_FOUND") || len(e.draft) != 0 {
t.Errorf("in-app propose_field on %q: %s (draft %d); want ENTITY_NOT_FOUND and no card", entity, res, len(e.draft))
}
if res, added := agent.RunTool(context.Background(), "tenant-A", "sess-1", nil, "propose_field", note(entity)); !strings.Contains(res, "ENTITY_NOT_FOUND") || len(added) != 0 {
t.Errorf("MCP propose_field on %q: %s (%d added); want ENTITY_NOT_FOUND and no card", entity, res, len(added))
}
}

// A table proposed earlier — this turn, or earlier in the MCP thread (prior) — is not missing.
e := &toolExecutor{reader: editFixtureReader(), tenantID: "tenant-A"}
e.execute(context.Background(), "propose_entity", `{"name":"ghosts","label":"Ma","fields":[{"name":"title","label":"Tên","fieldType":"text"}]}`)
if ok, _ := parseToolResult(t, e.execute(context.Background(), "propose_field", note("ghosts"))); !ok {
t.Fatal("a table drafted this turn must take a field")
}
prior := []DraftItem{{Kind: "entity", Entity: &DraftEntity{Name: "ghosts", Label: "Ma"}}}
if res, added := agent.RunTool(context.Background(), "tenant-A", "sess-1", prior, "propose_field", note("ghosts")); len(added) != 1 {
t.Fatalf("a table the thread proposed earlier must take a field: %s", res)
}
}
Loading
Loading