miaopanel
1package plugins
2
3import (
4 "archive/zip"
5 "context"
6 "crypto/ed25519"
7 "crypto/rand"
8 "crypto/sha256"
9 "encoding/base64"
10 "encoding/hex"
11 "encoding/json"
12 "os"
13 "path/filepath"
14 "runtime"
15 "testing"
16
17 "github.com/miaopanel/miaopanel/internal/config"
18 "github.com/miaopanel/miaopanel/internal/store"
19)
20
21func newTestService(t *testing.T) (*Service, *store.Store, ed25519.PrivateKey, ed25519.PrivateKey) {
22 t.Helper()
23 dir := t.TempDir()
24 cfg := config.Default()
25 cfg.PanelDir = dir
26 cfg.DataDir = filepath.Join(dir, "data")
27 cfg.PluginsDir = filepath.Join(dir, "plugins")
28 cfg.PluginRepoURL = "https://plugins.example.com"
29 cfg.UpdateURL = "https://plugins.example.com"
30 if err := cfg.EnsureDirs(); err != nil {
31 t.Fatal(err)
32 }
33 db, err := store.Open(filepath.Join(cfg.DataDir, "panel.db"))
34 if err != nil {
35 t.Fatal(err)
36 }
37 t.Cleanup(func() { db.Close() })
38 _, platform, _ := ed25519.GenerateKey(rand.Reader)
39 _, dev, _ := ed25519.GenerateKey(rand.Reader)
40 svc := New(Options{Config: cfg, Store: db, Version: "1.2.3"})
41 return svc, db, platform, dev
42}
43
44func pub(p ed25519.PrivateKey) string {
45 return sigPrefix + base64.StdEncoding.EncodeToString(p.Public().(ed25519.PublicKey))
46}
47
48func buildManifest(t *testing.T, dev ed25519.PrivateKey, mutate func(map[string]any)) []byte {
49 t.Helper()
50 sum := sha256.Sum256([]byte("zip"))
51 sha := hex.EncodeToString(sum[:])
52 m := map[string]any{
53 "schema": 1, "api": 1, "slug": "redis-manager", "name": "Redis 管理器",
54 "version": "1.2.0", "channel": "stable", "summary": "管理 Redis",
55 "category": "database", "license": "MIT",
56 "author": map[string]any{"name": "dev", "pubkey": pub(dev)},
57 "panel": map[string]any{"min": "1.2.0"},
58 "platforms": []any{map[string]any{"os": "linux", "arch": "amd64"}},
59 "permissions": []any{"files:/www/server/redis", "service:redis"},
60 "runtime": map[string]any{"type": "script"},
61 "install": map[string]any{"script": "install.sh", "timeout": 600},
62 "artifact": map[string]any{"file": "pkg.zip", "sha256": sha, "size": 3},
63 }
64 sig := ed25519.Sign(dev, artifactPayload("redis-manager", "1.2.0", m["artifact"].(map[string]any)["sha256"].(string)))
65 m["dev_sig"] = sigPrefix + base64.StdEncoding.EncodeToString(sig)
66 if mutate != nil {
67 mutate(m)
68 }
69 raw, err := json.Marshal(m)
70 if err != nil {
71 t.Fatal(err)
72 }
73 return raw
74}
75
76func TestVerifyDocumentPinsPlatformKey(t *testing.T) {
77 svc, _, platform, dev := newTestService(t)
78 manifest := buildManifest(t, dev, nil)
79 sig := sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest))
80 doc := &ManifestDoc{
81 Slug: "redis-manager", Version: "1.2.0", Arch: "amd64",
82 Manifest: string(manifest), PlatformSig: sig, PlatformPubkey: pub(platform),
83 }
84 if _, err := svc.VerifyDocument(context.Background(), doc); err != nil {
85 t.Fatalf("valid document rejected: %v", err)
86 }
87 pinned, err := svc.db.Setting(context.Background(), "plugin_platform_pubkey", "")
88 if err != nil || pinned == "" {
89 t.Fatalf("platform key not pinned: %q %v", pinned, err)
90 }
91 // A different key that re-signs the same manifest must be rejected once the
92 // first key is pinned.
93 _, otherPriv, _ := ed25519.GenerateKey(rand.Reader)
94 doc2 := *doc
95 doc2.PlatformPubkey = pub(otherPriv)
96 doc2.PlatformSig = sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(otherPriv, manifest))
97 if _, err := svc.VerifyDocument(context.Background(), &doc2); err == nil {
98 t.Fatal("roaming platform key accepted")
99 }
100}
101
102func TestVerifyDocumentRejectsTampering(t *testing.T) {
103 svc, _, platform, dev := newTestService(t)
104 manifest := buildManifest(t, dev, nil)
105 good := sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest))
106 base := ManifestDoc{
107 Slug: "redis-manager", Version: "1.2.0", Arch: "amd64",
108 Manifest: string(manifest), PlatformSig: good, PlatformPubkey: pub(platform),
109 }
110 tampered := base
111 tampered.Manifest = string(manifest) + " "
112 if _, err := svc.VerifyDocument(context.Background(), &tampered); err == nil {
113 t.Fatal("tampered manifest accepted")
114 }
115 // Wrong developer signature must fail even though the platform signature is
116 // valid, because the platform only attests what was reviewed.
117 badDev := buildManifest(t, dev, func(m map[string]any) {
118 m["dev_sig"] = sigPrefix + base64.StdEncoding.EncodeToString(make([]byte, ed25519.SignatureSize))
119 })
120 doc := base
121 doc.Manifest = string(badDev)
122 doc.PlatformSig = sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, badDev))
123 if _, err := svc.VerifyDocument(context.Background(), &doc); err == nil {
124 t.Fatal("bad developer signature accepted")
125 }
126}
127
128func TestVerifyDocumentEnforcesPanelRange(t *testing.T) {
129 svc, _, platform, dev := newTestService(t)
130 manifest := buildManifest(t, dev, func(m map[string]any) {
131 m["panel"] = map[string]any{"min": "9.0.0"}
132 })
133 doc := &ManifestDoc{
134 Slug: "redis-manager", Version: "1.2.0", Arch: "amd64",
135 Manifest: string(manifest), PlatformSig: sigPrefix + base64.StdEncoding.EncodeToString(ed25519.Sign(platform, manifest)),
136 PlatformPubkey: pub(platform),
137 }
138 if _, err := svc.VerifyDocument(context.Background(), doc); err == nil {
139 t.Fatal("panel range not enforced")
140 }
141}
142
143func TestParseRejectsDangerousPermissions(t *testing.T) {
144 _, _, _, dev := newTestService(t)
145 for _, perm := range []string{"files:/etc", "files:/", "files:relative", "unknown:thing"} {
146 manifest := buildManifest(t, dev, func(m map[string]any) {
147 m["permissions"] = []any{perm}
148 })
149 if _, err := Parse(manifest); err == nil {
150 t.Fatalf("permission %q accepted", perm)
151 }
152 }
153}
154
155func TestParsePermissionsClassifiesRisk(t *testing.T) {
156 list := ParsePermissions([]string{"files:/www/wwwroot/a", "service:redis", "exec:redis-cli", "nginx:http_fragment"})
157 if len(list) != 4 {
158 t.Fatalf("got %d", len(list))
159 }
160 if list[0].Risk != "high" || list[3].Risk != "medium" {
161 t.Fatalf("unexpected risk: %+v", list)
162 }
163}
164
165func TestExtractZipRejectsTraversal(t *testing.T) {
166 dir := t.TempDir()
167 path := filepath.Join(dir, "bad.zip")
168 f, _ := os.Create(path)
169 zw := zip.NewWriter(f)
170 w, _ := zw.Create("../evil.sh")
171 _, _ = w.Write([]byte("rm -rf /"))
172 _ = zw.Close()
173 _ = f.Close()
174 if err := extractZip(path, filepath.Join(dir, "out")); err == nil {
175 t.Fatal("path traversal accepted")
176 }
177}
178
179func TestExtractZipRejectsSymlink(t *testing.T) {
180 dir := t.TempDir()
181 path := filepath.Join(dir, "link.zip")
182 f, _ := os.Create(path)
183 zw := zip.NewWriter(f)
184 hdr := &zip.FileHeader{Name: "link"}
185 hdr.SetMode(os.ModeSymlink | 0o777)
186 w, _ := zw.CreateHeader(hdr)
187 _, _ = w.Write([]byte("/etc/passwd"))
188 _ = zw.Close()
189 _ = f.Close()
190 if err := extractZip(path, filepath.Join(dir, "out")); err == nil {
191 t.Fatal("symlink accepted")
192 }
193}
194
195func TestExtractZipPreservesExecutableBit(t *testing.T) {
196 dir := t.TempDir()
197 path := filepath.Join(dir, "ok.zip")
198 f, _ := os.Create(path)
199 zw := zip.NewWriter(f)
200 hdr := &zip.FileHeader{Name: "install.sh"}
201 hdr.SetMode(0o755)
202 w, _ := zw.CreateHeader(hdr)
203 _, _ = w.Write([]byte("#!/bin/bash\necho ok\n"))
204 _ = zw.Close()
205 _ = f.Close()
206 out := filepath.Join(dir, "out")
207 if err := extractZip(path, out); err != nil {
208 t.Fatal(err)
209 }
210 info, err := os.Stat(filepath.Join(out, "install.sh"))
211 if err != nil {
212 t.Fatal(err)
213 }
214 if runtime.GOOS != "windows" && info.Mode().Perm()&0o111 == 0 {
215 t.Fatalf("exec bit lost: %o", info.Mode().Perm())
216 }
217}