feat(auth): add PAT auth, scoped REST/MCP access, CSRF, and tenant isolation

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>
This commit is contained in:
naiba
2026-05-30 15:56:44 +00:00
co-authored by cloudcode
parent 58c1ea7b0b
commit ab25662ddd
153 changed files with 16974 additions and 244 deletions
@@ -0,0 +1,99 @@
package controller
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"github.com/nezhahq/nezha/model"
"github.com/nezhahq/nezha/service/singleton"
)
func newTriggerTaskCtxWithPAT(viewer *model.User, tok *model.APIToken) *gin.Context {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/service", http.NoBody)
if viewer != nil {
c.Set(model.CtxKeyAuthorizedUser, viewer)
}
if tok != nil {
c.Set(model.CtxKeyAPIToken, tok)
c.Set(apiTokenCtxKey, tok)
}
return c
}
// 注册一个用户 1 拥有的触发任务,使 CronShared.CheckPermission 通过,
// 从而隔离出「PAT 缺少 cron:exec」这一条裁决路径。
func registerOwnerTriggerTask(t *testing.T, id uint64) {
t.Helper()
singleton.CronShared.Update(&model.Cron{
Common: model.Common{ID: id, UserID: 1},
Name: "trigger",
TaskType: model.CronTypeTriggerTask,
Cover: model.CronCoverAll,
})
}
func TestValidateServersPATTriggerTaskRequiresCronExec(t *testing.T) {
setupAlertRuleFanoutFixture(t)
registerOwnerTriggerTask(t, 100)
viewer := &model.User{Common: model.Common{ID: 1}, Role: model.RoleAdmin}
noExec := &model.APIToken{ID: 10, UserID: 1}
noExec.SetScopes([]string{model.ScopeServiceWrite})
svc := &model.Service{
Common: model.Common{UserID: 1},
EnableTriggerTask: true,
FailTriggerTasks: []uint64{100},
}
require.Error(t, validateServers(newTriggerTaskCtxWithPAT(viewer, noExec), svc),
"service:write PAT must not bind a trigger task without cron:exec")
withExec := &model.APIToken{ID: 11, UserID: 1}
withExec.SetScopes([]string{model.ScopeServiceWrite, model.ScopeCronExec})
require.NoError(t, validateServers(newTriggerTaskCtxWithPAT(viewer, withExec), svc),
"service:write + cron:exec PAT may bind a trigger task")
}
func TestValidateRulePATTriggerTaskRequiresCronExec(t *testing.T) {
setupAlertRuleFanoutFixture(t)
registerOwnerTriggerTask(t, 200)
viewer := &model.User{Common: model.Common{ID: 1}, Role: model.RoleAdmin}
noExec := &model.APIToken{ID: 12, UserID: 1}
noExec.SetScopes([]string{model.ScopeAlertRuleWrite})
rule := &model.AlertRule{
Common: model.Common{UserID: 1},
Name: "r",
Rules: []*model.Rule{{Type: "offline", Cover: model.RuleCoverAll, Duration: 10, Ignore: map[uint64]bool{}}},
RecoverTriggerTasks: []uint64{200},
}
require.Error(t, validateRule(newTriggerTaskCtxWithPAT(viewer, noExec), rule),
"alertrule:write PAT must not bind a trigger task without cron:exec")
withExec := &model.APIToken{ID: 13, UserID: 1}
withExec.SetScopes([]string{model.ScopeAlertRuleWrite, model.ScopeCronExec})
require.NoError(t, validateRule(newTriggerTaskCtxWithPAT(viewer, withExec), rule),
"alertrule:write + cron:exec PAT may bind a trigger task")
}
// JWT 调用者(无 PAT)不受 cron:exec 收口影响。
func TestValidateServersJWTUnaffectedByTriggerTaskScope(t *testing.T) {
setupAlertRuleFanoutFixture(t)
registerOwnerTriggerTask(t, 300)
viewer := &model.User{Common: model.Common{ID: 1}, Role: model.RoleAdmin}
svc := &model.Service{
Common: model.Common{UserID: 1},
EnableTriggerTask: true,
FailTriggerTasks: []uint64{300},
}
require.NoError(t, validateServers(newTriggerTaskCtxWithPAT(viewer, nil), svc),
"JWT caller must not be gated by cron:exec")
}