mirror of
https://github.com/Buriburizaem0n/nezha_domains.git
synced 2026-09-19 17:50:12 +00:00
Introduce Personal Access Tokens (nzp_*) as a stateless auth path alongside
JWT, gated per-endpoint by a scope middleware (nezha:{resource}:{verb}) with
fail-closed empty-scope defaults and a server-id whitelist. Self-management
endpoints (profile, api-tokens, oauth2 bind, refresh-token) explicitly reject
PATs to block privilege-escalation chains. A revoke registry tears down active
long-lived connections (terminal, fm, ws, transfer, mcp) the moment a PAT is
deleted, with a tombstone closing the revoke->register race.
Add an MCP endpoint that proxies tool calls (exec, fs read/write/delete,
transfer) to agents over gRPC, guarded by origin/DNS-rebinding checks, a
per-token rate limiter, audit logging, and a kill switch. Serialize all
sends through the IOStream wrapper to honour grpc-go's concurrency contract.
Add CSRF double-submit protection on unsafe cookie-authenticated methods,
exempting authenticated PAT requests by context identity (not a forgeable
Authorization header). Apply visibility/whitelist filtering consistently
across list, get-by-id, and mutate paths to enforce tenant isolation.
Migrate legacy mcp:* scopes: rewrite read/exec to nezha:* equivalents and
drop dangerous write/delete/wildcard grants.
Co-authored-by: cloudcode <cloudcode@users.noreply.github.com>
97 lines
3.0 KiB
Go
97 lines
3.0 KiB
Go
package controller
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"path/filepath"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/stretchr/testify/require"
|
|
|
|
"github.com/nezhahq/nezha/model"
|
|
"github.com/nezhahq/nezha/service/singleton"
|
|
)
|
|
|
|
// installTestConfig swaps singleton.Conf with one backed by a tmp file so
|
|
// updateConfig's Conf.Save() write-through has a real target. The caller's
|
|
// setupMCPTest will restore the original Conf when its cleanup runs.
|
|
func installTestConfig(t *testing.T) {
|
|
t.Helper()
|
|
dir := t.TempDir()
|
|
cfg := &model.Config{}
|
|
require.NoError(t, cfg.Read(filepath.Join(dir, "config.yaml"), nil))
|
|
singleton.Conf = &singleton.ConfigClass{Config: cfg}
|
|
}
|
|
|
|
func TestUpdateConfig_PersistsEnableMCPFlag(t *testing.T) {
|
|
cleanup, uid := setupMCPTest(t)
|
|
defer cleanup()
|
|
installTestConfig(t)
|
|
|
|
origTemplates := singleton.FrontendTemplates
|
|
singleton.FrontendTemplates = []model.FrontendTemplate{
|
|
{Path: "user-dist", IsAdmin: false},
|
|
}
|
|
defer func() { singleton.FrontendTemplates = origTemplates }()
|
|
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(func(c *gin.Context) {
|
|
setAuthUser(c, uid, model.RoleAdmin)
|
|
c.Next()
|
|
})
|
|
r.PATCH("/api/v1/setting", commonHandler(updateConfig))
|
|
|
|
body := map[string]any{
|
|
"site_name": "test",
|
|
"language": "en_US",
|
|
"user_template": "user-dist",
|
|
"enable_mcp": true,
|
|
}
|
|
raw, _ := json.Marshal(body)
|
|
req := httptest.NewRequest(http.MethodPatch, "/api/v1/setting", bytes.NewReader(raw))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
w := httptest.NewRecorder()
|
|
r.ServeHTTP(w, req)
|
|
|
|
success, errMsg := decodeCommonResponseError(t, w.Body.Bytes())
|
|
require.True(t, success, "PATCH /setting must succeed: %s", errMsg)
|
|
require.True(t, singleton.Conf.EnableMCP,
|
|
"enable_mcp=true in body must flip singleton.Conf.EnableMCP")
|
|
}
|
|
|
|
func TestMCPEndpoint_RefusesWhenDisabled(t *testing.T) {
|
|
cleanup, uid := setupMCPTest(t)
|
|
defer cleanup()
|
|
singleton.Conf.SetMCPEnabled(false)
|
|
tok, _ := mkToken(t, uid, []string{model.ScopeServerRead}, nil)
|
|
|
|
c, w := mcpCallCtx(t, tok, uid, jsonRPCRequest{
|
|
JSONRPC: "2.0", ID: json.RawMessage("1"), Method: "initialize",
|
|
})
|
|
mcpEndpoint(c)
|
|
var env jsonRPCResponse
|
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &env))
|
|
require.NotNil(t, env.Error, "MCP must return JSON-RPC error when disabled; body=%s", w.Body.String())
|
|
require.Equal(t, rpcErrForbidden, env.Error.Code,
|
|
"disabled MCP must surface as rpcErrForbidden so callers can distinguish from auth failure")
|
|
}
|
|
|
|
func TestMCPEndpoint_AllowsWhenEnabled(t *testing.T) {
|
|
cleanup, uid := setupMCPTest(t)
|
|
defer cleanup()
|
|
singleton.Conf.SetMCPEnabled(true)
|
|
|
|
tok, _ := mkToken(t, uid, []string{model.ScopeServerRead}, nil)
|
|
c, w := mcpCallCtx(t, tok, uid, jsonRPCRequest{
|
|
JSONRPC: "2.0", ID: json.RawMessage("1"), Method: "initialize",
|
|
})
|
|
mcpEndpoint(c)
|
|
var env jsonRPCResponse
|
|
require.NoError(t, json.Unmarshal(w.Body.Bytes(), &env))
|
|
require.Nil(t, env.Error, "MCP must process requests when enabled; got error=%+v", env.Error)
|
|
}
|