mirror of
https://github.com/Buriburizaem0n/nezha_domains.git
synced 2026-09-19 17:50:12 +00:00
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:
@@ -5,6 +5,9 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
@@ -115,6 +118,9 @@ func serverStream(c *gin.Context) (any, error) {
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
deregisterPAT := registerPATConnection(c, func() { _ = conn.Close() })
|
||||
defer deregisterPAT()
|
||||
|
||||
userIp := c.GetString(model.CtxKeyRealIPStr)
|
||||
if userIp == "" {
|
||||
userIp = c.RemoteIP()
|
||||
@@ -130,6 +136,7 @@ func serverStream(c *gin.Context) (any, error) {
|
||||
userId = user.ID
|
||||
isAdmin = user.Role.IsAdmin()
|
||||
}
|
||||
patAccessor, patCacheKey := patStreamContext(c)
|
||||
|
||||
singleton.AddOnlineUser(connId, &model.OnlineUser{
|
||||
UserID: userId,
|
||||
@@ -141,7 +148,7 @@ func serverStream(c *gin.Context) (any, error) {
|
||||
|
||||
count := 0
|
||||
for {
|
||||
stat, err := getServerStat(count == 0, userId, isAdmin)
|
||||
stat, err := getServerStat(count == 0, userId, isAdmin, patAccessor, patCacheKey)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
@@ -167,12 +174,15 @@ var requestGroup singleflight.Group
|
||||
// depends on per-server ownership: prior to GHSA-hvv7-hfrh-7gxj this function
|
||||
// used a single isMember flag and leaked HideForGuest servers plus full Host
|
||||
// (PlatformVersion, agent Version, GPU) to every authenticated user.
|
||||
func getServerStat(withPublicNote bool, viewerUserID uint64, viewerIsAdmin bool) ([]byte, error) {
|
||||
cacheKey := fmt.Sprintf("serverStats::%t::%t::%d", withPublicNote, viewerIsAdmin, viewerUserID)
|
||||
//
|
||||
// patCacheKey distinguishes PATs with disjoint server_ids whitelists so two
|
||||
// limited tokens for the same user do not share a singleflight projection.
|
||||
func getServerStat(withPublicNote bool, viewerUserID uint64, viewerIsAdmin bool, pat model.APITokenAccessor, patCacheKey string) ([]byte, error) {
|
||||
cacheKey := fmt.Sprintf("serverStats::%t::%t::%d::%s", withPublicNote, viewerIsAdmin, viewerUserID, patCacheKey)
|
||||
v, err, _ := requestGroup.Do(cacheKey, func() (any, error) {
|
||||
servers := filterServersForViewer(
|
||||
singleton.ServerShared.GetSortedList(),
|
||||
viewerUserID, viewerIsAdmin, withPublicNote,
|
||||
viewerUserID, viewerIsAdmin, withPublicNote, pat,
|
||||
)
|
||||
return json.Marshal(model.StreamServerData{
|
||||
Now: time.Now().Unix() * 1000,
|
||||
@@ -184,17 +194,40 @@ func getServerStat(withPublicNote bool, viewerUserID uint64, viewerIsAdmin bool)
|
||||
return v.([]byte), err
|
||||
}
|
||||
|
||||
// patStreamContext extracts the PAT accessor + a deterministic cache key
|
||||
// fragment for the singleflight projection. Returns (nil, "jwt") for JWT
|
||||
// requests so two callers from the same user collapse onto one frame.
|
||||
func patStreamContext(c *gin.Context) (model.APITokenAccessor, string) {
|
||||
tok := APITokenFromContext(c)
|
||||
if tok == nil {
|
||||
return nil, "jwt"
|
||||
}
|
||||
ids := tok.ServerIDs()
|
||||
slices.Sort(ids)
|
||||
parts := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
parts = append(parts, strconv.FormatUint(id, 10))
|
||||
}
|
||||
return tok, fmt.Sprintf("pat:%d:%s", tok.ID, strings.Join(parts, ","))
|
||||
}
|
||||
|
||||
// filterServersForViewer projects the global server list down to what a single
|
||||
// viewer is allowed to see. The rules are:
|
||||
// - HideForGuest servers are visible only to their owner and to admins.
|
||||
// - Non-owner / non-admin viewers (including authenticated members) get
|
||||
// Host.Filter() output, which drops PlatformVersion and agent Version.
|
||||
// - Admins are unconstrained.
|
||||
// - A non-nil pat whitelist narrows visibility further; servers outside its
|
||||
// allow-list are dropped even from admins/owners (a PAT scoped to a
|
||||
// subset must never widen via its caller's role).
|
||||
//
|
||||
// viewerUserID == 0 represents an unauthenticated guest.
|
||||
func filterServersForViewer(servers []*model.Server, viewerUserID uint64, viewerIsAdmin bool, withPublicNote bool) []model.StreamServer {
|
||||
func filterServersForViewer(servers []*model.Server, viewerUserID uint64, viewerIsAdmin bool, withPublicNote bool, pat model.APITokenAccessor) []model.StreamServer {
|
||||
out := make([]model.StreamServer, 0, len(servers))
|
||||
for _, server := range servers {
|
||||
if pat != nil && !pat.CanAccessServer(server.ID) {
|
||||
continue
|
||||
}
|
||||
isOwnerOrAdmin := viewerIsAdmin || (viewerUserID != 0 && server.GetUserID() == viewerUserID)
|
||||
if server.HideForGuest && !isOwnerOrAdmin {
|
||||
continue
|
||||
|
||||
Reference in New Issue
Block a user