Files
nezha_domains/cmd/dashboard/controller/mcp_transfer_download_finalcheck_test.go
T
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

125 lines
4.2 KiB
Go

package controller
import (
"bytes"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"testing"
"github.com/nezhahq/nezha/model"
)
// M2 regression: download finalisation must validate the trailing NZTO
// frame's declared size AND sha256 against what was actually streamed.
// The old relay only checked the 4-byte magic, so a truncated NZTO (no
// hash) or a wrong-hash payload was silently accepted.
func TestValidateDownloadFinal_RejectsTruncatedNZTO(t *testing.T) {
buf := make([]byte, 4)
copy(buf, model.MCPFsXferMagicOK)
if err := validateDownloadFinal(buf, 0, sha256.New().Sum(nil)); err == nil {
t.Fatal("a 4-byte NZTO (magic only, no size+sha) must be rejected")
}
}
func TestValidateDownloadFinal_RejectsSizeMismatch(t *testing.T) {
h := sha256.New()
h.Write([]byte("payload"))
sum := h.Sum(nil)
buf := make([]byte, 4+8+32)
copy(buf[:4], model.MCPFsXferMagicOK)
binary.BigEndian.PutUint64(buf[4:12], 999) // declared size 999
copy(buf[12:44], sum)
if err := validateDownloadFinal(buf, int64(len("payload")), sum); err == nil {
t.Fatal("declared size mismatch with actual streamed bytes must be rejected")
}
}
func TestValidateDownloadFinal_RejectsHashMismatch(t *testing.T) {
declared := []byte("declared")
streamed := []byte("streamed-something-else")
h := sha256.New()
h.Write(declared)
declaredHash := h.Sum(nil)
streamedH := sha256.New()
streamedH.Write(streamed)
streamedHash := streamedH.Sum(nil)
buf := make([]byte, 4+8+32)
copy(buf[:4], model.MCPFsXferMagicOK)
binary.BigEndian.PutUint64(buf[4:12], uint64(len(streamed)))
copy(buf[12:44], declaredHash)
if err := validateDownloadFinal(buf, int64(len(streamed)), streamedHash); err == nil {
t.Fatal("declared sha256 != streamed sha256 must be rejected")
}
}
func TestValidateDownloadFinal_AcceptsMatchingSizeAndHash(t *testing.T) {
payload := []byte("hello world")
h := sha256.New()
h.Write(payload)
sum := h.Sum(nil)
buf := make([]byte, 4+8+32)
copy(buf[:4], model.MCPFsXferMagicOK)
binary.BigEndian.PutUint64(buf[4:12], uint64(len(payload)))
copy(buf[12:44], sum)
if err := validateDownloadFinal(buf, int64(len(payload)), sum); err != nil {
t.Fatalf("matching final header must pass, got %v", err)
}
}
// Hash skip: agent may omit the sha when the source filesystem can't
// produce one (e.g. live device). Encode as all-zero sha256; that's a
// legal but explicit "no hash" signal. Size must still match.
func TestValidateDownloadFinal_AllowsAllZeroHashAsExplicitSkip(t *testing.T) {
payload := []byte("nothash")
streamedHash, _ := hex.DecodeString("0000000000000000000000000000000000000000000000000000000000000000")
buf := make([]byte, 4+8+32)
copy(buf[:4], model.MCPFsXferMagicOK)
binary.BigEndian.PutUint64(buf[4:12], uint64(len(payload)))
// declared bytes 12-44 already zero by make()
if err := validateDownloadFinal(buf, int64(len(payload)), streamedHash); err != nil {
t.Fatalf("all-zero declared hash with matching size must pass (explicit skip), got %v", err)
}
}
// Defence-in-depth: the magic must still match. validateDownloadFinal is
// reached after the relay already checked it, but a second check costs
// nothing and survives future refactors that split the parsing.
func TestValidateDownloadFinal_RejectsWrongMagic(t *testing.T) {
buf := make([]byte, 4+8+32)
copy(buf[:4], []byte("XXXX"))
if err := validateDownloadFinal(buf, 0, sha256.New().Sum(nil)); err == nil {
t.Fatal("non-NZTO magic must be rejected")
}
}
// Defence-in-depth: bytes.Compare of slices of different length still
// returns non-zero, but Go semantics for hex.EncodeToString are wider
// than 32 bytes. Pin that the validator only inspects the first 32 hash
// bytes.
func TestValidateDownloadFinal_OnlyConsiders32HashBytes(t *testing.T) {
payload := []byte("X")
h := sha256.New()
h.Write(payload)
sum := h.Sum(nil)
buf := make([]byte, 4+8+32)
copy(buf[:4], model.MCPFsXferMagicOK)
binary.BigEndian.PutUint64(buf[4:12], uint64(len(payload)))
copy(buf[12:44], sum)
streamedHashExtra := append(bytes.Clone(sum), 0xAA, 0xBB)
if err := validateDownloadFinal(buf, int64(len(payload)), streamedHashExtra); err != nil {
t.Fatalf("validator must compare exactly the first 32 streamed hash bytes, got %v", err)
}
}