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 029695344c
commit e8dabf5bc6
153 changed files with 16974 additions and 244 deletions
@@ -0,0 +1,72 @@
package controller
import (
"sync"
"time"
)
// transferAnonAuditThrottle caps the number of audit rows written per
// source IP within a sliding window for transfer requests that failed
// before a valid `entry` could be loaded (bogus/expired/replayed token).
//
// Without this cap an unauthenticated attacker can POST millions of
// /mcp/upload/<random> requests; every miss invokes
// writeTransferFailureAudit which inserts into mcp_audit_log. The
// throttle keeps a small per-IP token bucket in memory and drops audit
// rows past the budget — successful and authenticated failures (entry
// != nil) bypass this gate entirely so SIEM signal is unaffected.
type transferAnonAuditThrottle struct {
mu sync.Mutex
window time.Duration
limit int
hits map[string]*anonHitBucket
clock func() time.Time
}
type anonHitBucket struct {
firstAt time.Time
count int
}
func newTransferAnonAuditThrottle(window time.Duration, perWindow int) *transferAnonAuditThrottle {
return &transferAnonAuditThrottle{
window: window,
limit: perWindow,
hits: make(map[string]*anonHitBucket),
clock: time.Now,
}
}
// shouldRecord reports whether the anonymous failure for this IP should
// land in the audit table. Empty ip is treated as "always record" since
// suppressing it would silently lose signal in test/headless contexts.
func (t *transferAnonAuditThrottle) shouldRecord(ip string) bool {
if ip == "" {
return true
}
t.mu.Lock()
defer t.mu.Unlock()
now := t.clock()
t.pruneLocked(now)
b, ok := t.hits[ip]
if !ok || now.Sub(b.firstAt) >= t.window {
t.hits[ip] = &anonHitBucket{firstAt: now, count: 1}
return true
}
if b.count >= t.limit {
return false
}
b.count++
return true
}
func (t *transferAnonAuditThrottle) pruneLocked(now time.Time) {
for ip, b := range t.hits {
if now.Sub(b.firstAt) >= t.window {
delete(t.hits, ip)
}
}
}
var transferAnonAuditThrottleShared = newTransferAnonAuditThrottle(time.Minute, 5)