package plugin_test
import (
"archive/zip"
"context"
"crypto/ed25519"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Nwflower/reims-go/internal/driver"
"github.com/Nwflower/reims-go/internal/driver/reims"
"github.com/Nwflower/reims-go/internal/plugin"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
// TestHelperSidecar acts as an external L3 Sidecar executable when invoked
// with REIMS_TEST_SIDECAR=1 (using the compiled test binary itself so zero
// extra build time is needed and Windows Job Object cleanup is tested live).
func TestHelperSidecar(t *testing.T) {
if os.Getenv("REIMS_TEST_SIDECAR") != "1" {
return
}
mode := os.Getenv("REIMS_TEST_SIDECAR_MODE")
if mode == "crash" {
os.Exit(42)
}
srv := pluginsdk.New()
srv.SetCapability("linux-driver", true)
srv.Handle("command/invoke", func(ctx context.Context, raw json.RawMessage) (any, error) {
var req struct {
Command string `json:"command"`
Args map[string]any `json:"args"`
}
_ = json.Unmarshal(raw, &req)
if req.Command == "hang" {
<-ctx.Done()
return nil, ctx.Err()
}
if req.Command == "notify-host" {
_ = srv.Notify(ctx, "hello", "from sidecar")
}
return map[string]any{"echo": req.Command, "args": req.Args}, nil
})
srv.Handle("hook/vm.beforeStart", func(_ context.Context, raw json.RawMessage) (any, error) {
return plugin.StartIntent{
Args: []plugin.ArgFragment{{
Key: "sidecar-rtc",
Tokens: []string{"-rtc", "base=utc"},
}},
}, nil
})
srv.Handle("diagnostics/collect", func(_ context.Context, _ json.RawMessage) (any, error) {
return plugin.DiagnosticsEntry{
Title: "Sidecar Diag",
Text: "mac=aa:bb:cc:dd:ee:ff serial=C02SECRET1234",
}, nil
})
srv.Handle("driver/list", func(_ context.Context, _ json.RawMessage) (any, error) {
return map[string]any{
"vms": []driver.VMInfo{{
Name: "ubuntu-24",
State: "stopped",
CPUs: 4,
Memory: "8G",
DriverName: "Linux (Test Sidecar)",
}},
}, nil
})
srv.Handle("driver/show", func(_ context.Context, raw json.RawMessage) (any, error) {
var req struct{ Name string }
_ = json.Unmarshal(raw, &req)
return driver.VMInfo{Name: req.Name, State: "stopped", CPUs: 4, Memory: "8G"}, nil
})
_ = srv.Serve(context.Background())
os.Exit(0)
}
func makePluginZip(t *testing.T, files map[string][]byte, priv ed25519.PrivateKey, corruptSum bool) string {
t.Helper()
zipPath := filepath.Join(t.TempDir(), "plugin.zip")
f, err := os.Create(zipPath)
if err != nil {
t.Fatal(err)
}
zw := zip.NewWriter(f)
var sumLines []string
for rel, content := range files {
w, err := zw.Create(rel)
if err != nil {
t.Fatal(err)
}
_, _ = w.Write(content)
h := sha256.Sum256(content)
hexSum := hex.EncodeToString(h[:])
if corruptSum {
hexSum = strings.Repeat("0", 64)
}
sumLines = append(sumLines, fmt.Sprintf("%s %s", hexSum, rel))
}
sumsBytes := []byte(strings.Join(sumLines, "\n") + "\n")
w, _ := zw.Create("SHA256SUMS")
_, _ = w.Write(sumsBytes)
if len(priv) > 0 {
sig := ed25519.Sign(priv, sumsBytes)
sw, _ := zw.Create("SHA256SUMS.sig")
_, _ = sw.Write([]byte(base64.StdEncoding.EncodeToString(sig)))
}
_ = zw.Close()
_ = f.Close()
return zipPath
}
func TestStateStoreRefusesCorruptJSON(t *testing.T) {
dir := t.TempDir()
_ = os.WriteFile(filepath.Join(dir, plugin.StateFileName), []byte("{corrupt"), 0o644)
store := plugin.NewStateStore(dir)
if _, err := store.Load(); err == nil {
t.Fatal("expected error loading corrupt state.json; MUST NOT treat as empty")
}
}
func TestTransactionalInstallSigningRedlinesAndThemeDoctor(t *testing.T) {
pub, priv, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatal(err)
}
dataRoot := t.TempDir()
mgr, err := plugin.NewManager(plugin.ManagerOptions{
DataRoot: dataRoot,
HostVersion: "0.2.6",
Keyring: []plugin.SigningKey{{
KeyID: "official-1",
Publisher: "Reims-Go",
Trust: plugin.TrustOfficial,
PublicKey: pub,
}},
RedactFn: reims.RedactText,
})
if err != nil {
t.Fatal(err)
}
defer mgr.Close()
// 1. Valid signed L1 theme pack (token + style + decoration).
manifestJSON, _ := json.Marshal(plugin.Manifest{
Schema: 1,
ID: "test.theme.aurora",
Version: "1.0.0",
Name: plugin.LocalizedText{ZhCN: "极光测试主题", EnUS: "Aurora Test Theme"},
Description: plugin.LocalizedText{EnUS: "Verifies token+style+decoration theme interface"},
Publisher: "Test",
License: "MIT",
Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^1.0.0"},
Contributes: plugin.Contributes{
Themes: []plugin.ThemeContribution{{
ID: "test.theme.aurora",
Name: plugin.LocalizedText{EnUS: "Aurora"},
Appearance: "both",
Seeds: map[string]string{"accent": "#7c3aed"},
Stylesheet: "theme.css",
Decorations: []plugin.ThemeDecoration{{
ID: "mascot",
Slot: "sidebar.footer",
States: []plugin.ThemeDecorationState{
{When: "vmState==running", Asset: "mascot.svg"},
},
}},
}},
},
})
validCSS := []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`)
svgWithScript := []byte(``)
goodZip := makePluginZip(t, map[string][]byte{
"plugin.json": manifestJSON,
"theme.css": validCSS,
"mascot.svg": svgWithScript,
}, priv, false)
info, err := mgr.InstallLocalArchive(context.Background(), goodZip, plugin.PackageInstallOptions{})
if err != nil {
t.Fatalf("InstallLocalArchive valid theme: %v", err)
}
if info.Trust != plugin.TrustOfficial {
t.Fatalf("trust = %s, want official", info.Trust)
}
if err := mgr.Enable(context.Background(), "test.theme.aurora", false); err != nil {
t.Fatalf("enable theme: %v", err)
}
if err := mgr.SetActiveTheme("test.theme.aurora", ""); err != nil {
t.Fatalf("SetActiveTheme: %v", err)
}
payload := mgr.ActiveThemePayload()
if payload.ThemeID != "test.theme.aurora" || !strings.Contains(payload.CSS, ".rg-p-sidebar") {
t.Fatalf("unexpected active theme payload: %+v", payload)
}
// Verify AssetServer token gate, traversal block, and SVG script sanitization (§7.3).
reqBadTok := httptest.NewRequest(http.MethodGet, "/plugin-assets/wrongtoken/test.theme.aurora/mascot.svg", nil)
recBadTok := httptest.NewRecorder()
mgr.Assets().ServeHTTP(recBadTok, reqBadTok)
if recBadTok.Code != http.StatusForbidden {
t.Fatalf("wrong token status = %d, want 403", recBadTok.Code)
}
reqSVG := httptest.NewRequest(http.MethodGet, mgr.Assets().AssetURL("test.theme.aurora", "mascot.svg"), nil)
recSVG := httptest.NewRecorder()
mgr.Assets().ServeHTTP(recSVG, reqSVG)
if recSVG.Code != http.StatusOK {
t.Fatalf("SVG fetch status = %d, want 200", recSVG.Code)
}
if strings.Contains(recSVG.Body.String(), "