package plugins import ( "archive/zip" "context" "crypto/ed25519" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "encoding/json" "os" "path/filepath" "runtime" "testing" "github.com/miaopanel/miaopanel/internal/config" "github.com/miaopanel/miaopanel/internal/store" ) func newTestService(t *testing.T) (*Service, *store.Store, ed25519.PrivateKey, ed25519.PrivateKey) { t.Helper() dir := t.TempDir() cfg := config.Default() cfg.PanelDir = dir cfg.DataDir = filepath.Join(dir, "data") cfg.PluginsDir = filepath.Join(dir, "plugins") cfg.PluginRepoURL = "https://plugins.example.com" cfg.UpdateURL = "https://plugins.example.com" if err := cfg.EnsureDirs(); err != nil { t.Fatal(err) } db, err := store.Open(filepath.Join(cfg.DataDir, "panel.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { db.Close() }) _, platform, _ := ed25519.GenerateKey(rand.Reader) _, dev, _ := ed25519.GenerateKey(rand.Reader) svc := New(Options{Config: cfg, Store: db, Version: "1.2.3"}) return svc, db, platform, dev } func pub(p ed25519.PrivateKey) string { return sigPrefix + base64.StdEncoding.EncodeToString(p.Public().(ed25519.PublicKey)) } func buildManifest(t *testing.T, dev ed25519.PrivateKey, mutate func(map[string]any)) []byte { t.Helper() sum := sha256.Sum256([]byte("zip")) sha := hex.EncodeToString(sum[:]) m := map[string]any{ "schema": 1, "api": 1, "slug": "redis-manager", "name": "Redis 管理器", "version": "1.2.0", "channel": "stable", "summary": "管理 Redis", "category": "database", "license": "MIT", "author": map[string]any{"name": "dev", "pubkey": pub(dev)}, "panel": map[string]any{"min": "1.2.0"}, "platforms": []any{map[string]any{"os": "linux", "arch": "amd64"}}, "permissions": []any{"files:/www/server/redis", "service:redis"}, "runtime": map[string]any{"type": "script"}, "install": map[string]any{"script": "install.sh", "timeout": 600}, "artifact": map[string]any{"file": "pkg.zip", "sha256": sha, "size": 3}, } sig := ed25519.Sign(dev, artifactPayload("redis-manager", "1.2.0", m["artifact"].(map[string]any)["sha256"].(string))) m["dev_sig"] = sigPrefix + base64.StdEncoding.EncodeToString(sig) if mutate != nil { mutate(m) } raw, err := json.Marshal(m) if err != nil { t.Fatal(err) } return raw } func TestVerifyDocumentPinsPlatformKey(t *testing.T) { svc, _, platform, dev := newTestService(t) manifest := buildManifest(t, dev, nil) sig := sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest)) doc := &ManifestDoc{ Slug: "redis-manager", Version: "1.2.0", Arch: "amd64", Manifest: string(manifest), PlatformSig: sig, PlatformPubkey: pub(platform), } if _, err := svc.VerifyDocument(context.Background(), doc); err != nil { t.Fatalf("valid document rejected: %v", err) } pinned, err := svc.db.Setting(context.Background(), "plugin_platform_pubkey", "") if err != nil || pinned == "" { t.Fatalf("platform key not pinned: %q %v", pinned, err) } // A different key that re-signs the same manifest must be rejected once the // first key is pinned. _, otherPriv, _ := ed25519.GenerateKey(rand.Reader) doc2 := *doc doc2.PlatformPubkey = pub(otherPriv) doc2.PlatformSig = sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(otherPriv, manifest)) if _, err := svc.VerifyDocument(context.Background(), &doc2); err == nil { t.Fatal("roaming platform key accepted") } } func TestVerifyDocumentRejectsTampering(t *testing.T) { svc, _, platform, dev := newTestService(t) manifest := buildManifest(t, dev, nil) good := sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest)) base := ManifestDoc{ Slug: "redis-manager", Version: "1.2.0", Arch: "amd64", Manifest: string(manifest), PlatformSig: good, PlatformPubkey: pub(platform), } tampered := base tampered.Manifest = string(manifest) + " " if _, err := svc.VerifyDocument(context.Background(), &tampered); err == nil { t.Fatal("tampered manifest accepted") } // Wrong developer signature must fail even though the platform signature is // valid, because the platform only attests what was reviewed. badDev := buildManifest(t, dev, func(m map[string]any) { m["dev_sig"] = sigPrefix + base64.StdEncoding.EncodeToString(make([]byte, ed25519.SignatureSize)) }) doc := base doc.Manifest = string(badDev) doc.PlatformSig = sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, badDev)) if _, err := svc.VerifyDocument(context.Background(), &doc); err == nil { t.Fatal("bad developer signature accepted") } } func TestVerifyDocumentEnforcesPanelRange(t *testing.T) { svc, _, platform, dev := newTestService(t) manifest := buildManifest(t, dev, func(m map[string]any) { m["panel"] = map[string]any{"min": "9.0.0"} }) doc := &ManifestDoc{ Slug: "redis-manager", Version: "1.2.0", Arch: "amd64", Manifest: string(manifest), PlatformSig: sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest)), PlatformPubkey: pub(platform), } if _, err := svc.VerifyDocument(context.Background(), doc); err == nil { t.Fatal("panel range not enforced") } } func TestParseRejectsDangerousPermissions(t *testing.T) { _, _, _, dev := newTestService(t) for _, perm := range []string{"files:/etc", "files:/", "files:relative", "unknown:thing"} { manifest := buildManifest(t, dev, func(m map[string]any) { m["permissions"] = []any{perm} }) if _, err := Parse(manifest); err == nil { t.Fatalf("permission %q accepted", perm) } } } func TestParsePermissionsClassifiesRisk(t *testing.T) { list := ParsePermissions([]string{"files:/www/wwwroot/a", "service:redis", "exec:redis-cli", "nginx:http_fragment"}) if len(list) != 4 { t.Fatalf("got %d", len(list)) } if list[0].Risk != "high" || list[3].Risk != "medium" { t.Fatalf("unexpected risk: %+v", list) } } func TestExtractZipRejectsTraversal(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "bad.zip") f, _ := os.Create(path) zw := zip.NewWriter(f) w, _ := zw.Create("../evil.sh") _, _ = w.Write([]byte("rm -rf /")) _ = zw.Close() _ = f.Close() if err := extractZip(path, filepath.Join(dir, "out")); err == nil { t.Fatal("path traversal accepted") } } func TestExtractZipRejectsSymlink(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "link.zip") f, _ := os.Create(path) zw := zip.NewWriter(f) hdr := &zip.FileHeader{Name: "link"} hdr.SetMode(os.ModeSymlink | 0o777) w, _ := zw.CreateHeader(hdr) _, _ = w.Write([]byte("/etc/passwd")) _ = zw.Close() _ = f.Close() if err := extractZip(path, filepath.Join(dir, "out")); err == nil { t.Fatal("symlink accepted") } } func TestExtractZipPreservesExecutableBit(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "ok.zip") f, _ := os.Create(path) zw := zip.NewWriter(f) hdr := &zip.FileHeader{Name: "install.sh"} hdr.SetMode(0o755) w, _ := zw.CreateHeader(hdr) _, _ = w.Write([]byte("#!/bin/bash\necho ok\n")) _ = zw.Close() _ = f.Close() out := filepath.Join(dir, "out") if err := extractZip(path, out); err != nil { t.Fatal(err) } info, err := os.Stat(filepath.Join(out, "install.sh")) if err != nil { t.Fatal(err) } if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 { t.Fatalf("exec bit lost: %o", info.Mode().Perm()) } }