Files
nezha_domains/model/service_ignoreall_false_test.go
naibaandcloudcode e8dabf5bc6 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>
2026-05-30 15:56:44 +00:00

52 lines
1.5 KiB
Go

package model
import (
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func adminPATCtx(tok *APIToken) *gin.Context {
gin.SetMode(gin.TestMode)
c, _ := gin.CreateTestContext(httptest.NewRecorder())
c.Request = httptest.NewRequest("GET", "/", nil)
c.Set(CtxKeyAuthorizedUser, &User{Common: Common{ID: 1}, Role: RoleAdmin})
c.Set(CtxKeyAPIToken, tok)
return c
}
// ServiceCoverIgnoreAll permission must only consider SkipServers entries
// whose value is true (the allow-set actually dispatched at runtime). A
// `{2: false}` entry has no dispatch effect, so a PAT scoped to {1} must
// still be allowed to manage this service.
func TestServiceHasPermissionIgnoreAllSkipsFalseEntries(t *testing.T) {
tok := &APIToken{ID: 1, UserID: 1}
tok.SetServerIDs([]uint64{1})
svc := &Service{
Common: Common{ID: 10, UserID: 1},
Cover: ServiceCoverIgnoreAll,
SkipServers: map[uint64]bool{1: true, 2: false},
}
if !svc.HasPermission(adminPATCtx(tok)) {
t.Fatal("a `{2: false}` allow-set entry must not block a PAT scoped to {1}")
}
}
func TestServiceHasPermissionIgnoreAllRejectsForeignTrueEntry(t *testing.T) {
tok := &APIToken{ID: 1, UserID: 1}
tok.SetServerIDs([]uint64{1})
svc := &Service{
Common: Common{ID: 10, UserID: 1},
Cover: ServiceCoverIgnoreAll,
SkipServers: map[uint64]bool{2: true},
}
if svc.HasPermission(adminPATCtx(tok)) {
t.Fatal("a true allow-set entry on server 2 must reject a PAT scoped to {1}")
}
}