myxce/src/frontend/apiserver/middleware/whitelist_test.go
lei.chen 1691e49a05 feat(advisor): P1 outlets — findings push to SSE + MCP scheduler_advisor_findings
The advisor's findings previously lived only in its JSONL decision log on
its own host. P1 adds two observe-only outlets so diagnoses reach humans
and other agents live:

apiserver side:
- backend/broker.go: EventAdvisorFinding ("advisor.finding") event type +
  AdvisorFinding struct + Event.AdvisorFindings field.
- controllers/events.go: ReportFindings — POST /xce/v1/advisor/findings
  (generated_at/scenario/findings), publishes one broker event. Broadcast
  only: the decision log remains the store of record.
- router/routers.go: route behind RequirePermission("advisor:report").
- middleware/whitelist.go: admit /xce/v1/advisor/findings in the POST URL
  whitelist (the URL middleware 403s before the router's RBAC otherwise —
  same shape as bug-1489).
- config/rbac.yaml: advisor_agent role (advisor:report + the six *:view
  grants the snapshot needs) and advisor:report in the permission
  whitelist. mcp_readonly stays strictly *:view. New
  TestRBACYAML_AdvisorAgentRole_PinsReportSurface pins the role surface.

advisor side:
- internal/push: Pusher — best-effort POST of each round's findings, one
  retry, nil/unconfigured/empty findings are no-ops; failures log and
  never affect the observe loop.
- internal/agent: SetPusher wired after the decision-log append (the log
  is authoritative; push is a fan-out).
- internal/config + cmd: push default-on to the same XCE_API_URL with the
  same XCE_API_KEY (the key's role needs advisor:report); ADVISOR_PUSH=
  off|false|0 disables.

mcp-server side:
- internal/advisor.go: lenient JSONL reader for the advisor's decision
  log (ADVISOR_LOG env), tail-bounded, corrupt lines skipped.
- scheduler_advisor_findings tool: recent records with parsed findings;
  friendly errors when the log is missing/unconfigured. Passive reader —
  never talks to the advisor process.

Cluster verification (t1/t2/t3): redeployed apiserver closure, deployed
rbac.yaml, issued advisor_agent key. Forced-PEND job → pend_stall fired
on the real LLM (glm-5-3-flash, 19.4s, degraded=false) → 2 findings, all
evidence verbatim in the snapshot, unverified=false → SSE broadcast
captured on /xce/v1/events → MCP tool returned both records. Second PEND
job joining the stalled set fired a new decision within one round
(change-triggered semantics). Verification jobs killed; sanity job
submitted→ran→DONE; all daemons and 3 hosts healthy.

Design doc: architecture diagram gains the push branch; roadmap P1
marked done (CLI outlet not built).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-10-19 10:06:32 +00:00

87 lines
2.5 KiB
Go

package middleware
import (
"apiserver/utils"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// bug-1949: every IP-whitelist failure must stop the request before the
// handler runs.
func TestWhitelistIPMiddleware_AbortsOnFailure(t *testing.T) {
prevLog := utils.Log
utils.Log = zap.NewNop()
t.Cleanup(func() { utils.Log = prevLog })
tests := []struct {
name string
remoteAddr string
wantStatus int
}{
{"unparsable client IP", "not-an-address", http.StatusBadRequest},
{"client IP not whitelisted", "192.0.2.10:4000", http.StatusForbidden},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
handlerRan := false
r.Use(WhitelistIPMiddleware([]string{"10.0.0.0/8"}))
r.GET("/ping", func(ctx *gin.Context) {
handlerRan = true
ctx.String(http.StatusOK, "pong")
})
req := httptest.NewRequest(http.MethodGet, "/ping", nil)
req.RemoteAddr = tt.remoteAddr
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if handlerRan {
t.Errorf("handler ran after the IP whitelist rejected %q (status %d)", tt.remoteAddr, w.Code)
}
if w.Code != tt.wantStatus {
t.Errorf("status = %d, want %d", w.Code, tt.wantStatus)
}
})
}
}
func TestPathMatchesPattern(t *testing.T) {
cases := []struct {
pattern string
path string
want bool
}{
// wildcard patterns
{"/xce/v1/hosts/*", "/xce/v1/hosts/host1", true},
{"/xce/v1/jobs/*", "/xce/v1/jobs/123/control", true},
{"/xce/v1/roles/*", "/xce/v1/roles/cluster_admin", true},
{"/xce/v1/users/*", "/xce/v1/users/current", true},
{"/xce/v1/users/*", "/xce/v1/users/admin/basic_user", true},
// advisor findings (scheduler-advisor P1): the POST whitelist must
// admit the advisor's report path or the URL middleware 403s before
// the router (and its advisor:report check) is ever reached.
{"/xce/v1/advisor/findings", "/xce/v1/advisor/findings", true},
{"/xce/v1/advisor/findings", "/xce/v1/advisor/findings/extra", false},
// exact patterns
{"/xce/v1/hosts", "/xce/v1/hosts", true},
{"/xce/v1/hosts", "/xce/v1/host", false},
{"/xce/v1/roles", "/xce/v1/roles", true},
{"/xce/v1/roles", "/xce/v1/role", false},
{"/xce/v1/clusters", "/xce/v1/clusters", true},
{"/ping", "/ping", true},
{"/ping", "/pin", false},
}
for _, tc := range cases {
got := pathMatchesPattern(tc.path, tc.pattern)
if got != tc.want {
t.Errorf("pathMatchesPattern(%q, %q) = %v, want %v", tc.path, tc.pattern, got, tc.want)
}
}
}