Plugins that need their own UI and richer themes should not force breaking contract changes later, so the full shape is published now (uiApi 2.0, bridgeApi 1.0) and every entry is marked stable or experimental: - docs/plugin-architecture.md: plugin-owned views (sidebar, vm.tab, settings, dialog) and the bridge methods (§5.6), the finer theme contract with slot catalogue, layers, layout and icons (§5.1), and the contract evolution rules (§6.3). - ui-contract.ts and the new bridgeContract.ts list stable and experimental entries; the build fails if a stable entry is not emitted or an emitted entry is still experimental, and writes bridge-contract.json next to ui-contract.json. - internal/plugin/contract.go mirrors them as catalogs (contribution points, slots with accepted content, view locations, layers, layout, icons, bridge methods and events) and derives HostFeatures; tests keep Go and TypeScript identical and require every contributes field to be catalogued. - Manifests gain views, theme layout and engines.bridgeApi. Unknown slots, locations, layout values and icon names are rejected; experimental use, unknown fields and missing engines ranges are doctor warnings. Declared-but-unrendered entries (vmCards, statusItems, settingsPages, vmTemplates, runtimeSources, runtimes, uiScripts, diagnostics, theme icons and brandMark, panels outside settings.plugin) are now marked experimental. - The panel bridge resolves methods through the catalog, adds hello and refuses experimental methods; panels get theme.changed and locale.changed events; the Sidecar handshake and the Go SDK carry uiApi, bridgeApi and features. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
401 lines
13 KiB
Go
401 lines
13 KiB
Go
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/macos/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: "^2.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); }`)
|
|
cleanSVG := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><circle r="4"/></svg>`)
|
|
goodZip := makePluginZip(t, map[string][]byte{
|
|
"plugin.json": manifestJSON,
|
|
"theme.css": validCSS,
|
|
"mascot.svg": cleanSVG,
|
|
}, 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)
|
|
}
|
|
|
|
// Verify plugin doctor validates CSS against UI contract (§5.1).
|
|
contract := &plugin.UIContract{
|
|
UIAPI: "1.0.0",
|
|
Parts: []string{"rg-p-sidebar"},
|
|
Tokens: []string{"--surface-sidebar"},
|
|
}
|
|
findings := plugin.DoctorDirectory(info.InstallDir, "0.2.6", contract)
|
|
for _, f := range findings {
|
|
if f.Severity == "error" || f.Severity == "warn" {
|
|
t.Fatalf("unexpected doctor finding on valid theme: %+v", f)
|
|
}
|
|
}
|
|
|
|
// Verify defense-in-depth AssetServer SVG sanitization even if an SVG on disk is tampered with (§7.3).
|
|
svgWithScript := []byte(`<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><circle onclick="evil()" r="4"/></svg>`)
|
|
if err := os.WriteFile(filepath.Join(info.InstallDir, "mascot.svg"), svgWithScript, 0o644); err != nil {
|
|
t.Fatalf("write tampered svg: %v", err)
|
|
}
|
|
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(), "<script") || strings.Contains(recSVG.Body.String(), "onclick") {
|
|
t.Fatalf("SVG was not sanitized: %s", recSVG.Body.String())
|
|
}
|
|
if recSVG.Header().Get("X-Content-Type-Options") != "nosniff" {
|
|
t.Fatal("missing X-Content-Type-Options: nosniff")
|
|
}
|
|
|
|
// 2. Corrupt checksum zip must be rejected before touching disk/state.
|
|
badSumZip := makePluginZip(t, map[string][]byte{"plugin.json": manifestJSON, "theme.css": validCSS}, nil, true)
|
|
if _, err := mgr.InstallLocalArchive(context.Background(), badSumZip, plugin.PackageInstallOptions{}); err == nil {
|
|
t.Fatal("expected corrupt SHA256SUMS zip to be rejected")
|
|
}
|
|
|
|
// 3. Incompatible pluginApi zip must be rejected before install.
|
|
incompatManifest, _ := json.Marshal(plugin.Manifest{
|
|
Schema: 1,
|
|
ID: "test.incompat.pkg",
|
|
Version: "1.0.0",
|
|
Name: plugin.LocalizedText{EnUS: "Incompat"},
|
|
Engines: plugin.Engines{PluginAPI: "^9.0.0"},
|
|
})
|
|
incompatZip := makePluginZip(t, map[string][]byte{"plugin.json": incompatManifest}, nil, false)
|
|
if _, err := mgr.InstallLocalArchive(context.Background(), incompatZip, plugin.PackageInstallOptions{}); err == nil {
|
|
t.Fatal("expected incompatible pluginApi zip to be rejected")
|
|
}
|
|
|
|
// 4. Market redline: reject Apple .ipsw inside zip.
|
|
redlineZip := makePluginZip(t, map[string][]byte{
|
|
"plugin.json": manifestJSON,
|
|
"Universal.ipsw": []byte("nope"),
|
|
}, nil, false)
|
|
if _, err := mgr.InstallLocalArchive(context.Background(), redlineZip, plugin.PackageInstallOptions{}); err == nil {
|
|
t.Fatal("expected Apple .ipsw zip to be rejected by redline")
|
|
}
|
|
|
|
// 5. Anti-swap ID check.
|
|
if _, err := mgr.InstallLocalArchive(context.Background(), goodZip, plugin.PackageInstallOptions{ExpectedID: "other.id"}); err == nil {
|
|
t.Fatal("expected anti-swap ID mismatch error")
|
|
}
|
|
}
|
|
|
|
func TestSidecarSupervisionReverseHostAPIDriverAndCrashIsolation(t *testing.T) {
|
|
exePath, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
dataRoot := t.TempDir()
|
|
layout := plugin.NewPluginsLayout(dataRoot)
|
|
reg := plugin.NewRegistry(nil)
|
|
broker := plugin.NewBroker(layout, reg, reims.RedactText)
|
|
|
|
notified := make(chan string, 1)
|
|
broker.SetNotifier(func(pid, title, body string) {
|
|
notified <- pid + ":" + title
|
|
})
|
|
|
|
t.Setenv("REIMS_TEST_SIDECAR", "1")
|
|
t.Setenv("REIMS_TEST_SIDECAR_MODE", "")
|
|
|
|
sup := plugin.NewSidecarSupervisor(plugin.SidecarOptions{
|
|
PluginID: "test.sidecar.linux",
|
|
ExePath: exePath,
|
|
Args: []string{"-test.run=^TestHelperSidecar$"},
|
|
DataDir: layout.DataDir("test.sidecar.linux"),
|
|
Broker: broker,
|
|
Registry: reg,
|
|
})
|
|
defer sup.Stop()
|
|
|
|
_ = reg.Register(plugin.PluginDef{
|
|
Manifest: plugin.Manifest{
|
|
ID: "test.sidecar.linux",
|
|
Version: "1.0.0",
|
|
Permissions: []string{"ui:notify", "driver:vm", "vm:intent"},
|
|
},
|
|
Source: plugin.SourceLocal,
|
|
Trust: plugin.TrustVerified,
|
|
Desired: true,
|
|
Activate: func(_ context.Context, sc *plugin.Scope) error {
|
|
sc.OnDispose(func() { sup.Stop() })
|
|
drv := driver.NewSidecarDriver(plugin.GuestDriverContribution{
|
|
ID: "test.driver.linux",
|
|
Name: plugin.LocalizedText{EnUS: "Linux"},
|
|
RuntimeKind: "qemu-ovmf",
|
|
}, sup)
|
|
reg.RegisterGuestDriver(sc, "test.driver.linux", drv)
|
|
reg.RegisterDiagnostics(sc, plugin.DiagnosticsContribution{
|
|
ID: "sidecar-diag",
|
|
Title: plugin.LocalizedText{EnUS: "Sidecar Diag"},
|
|
}, func(ctx context.Context, vm string) (plugin.DiagnosticsEntry, error) {
|
|
var e plugin.DiagnosticsEntry
|
|
err := sup.Call(ctx, "diagnostics/collect", map[string]any{"vm": vm}, &e)
|
|
return e, err
|
|
})
|
|
return nil
|
|
},
|
|
})
|
|
reg.Reconcile(context.Background())
|
|
|
|
// 1. Driver proxy lists VMs from Sidecar over JSON-RPC 2.0.
|
|
router := driver.NewRouter(reg, nil)
|
|
vms, err := router.ListAllVMs(context.Background())
|
|
if err != nil || len(vms) != 1 || vms[0].Name != "ubuntu-24" {
|
|
t.Fatalf("SidecarDriver ListAllVMs = %+v, err=%v", vms, err)
|
|
}
|
|
|
|
// 2. Command invocation + reverse Host API notification.
|
|
var cmdOut map[string]any
|
|
if err := sup.Call(context.Background(), "command/invoke", map[string]any{"command": "notify-host"}, &cmdOut); err != nil {
|
|
t.Fatalf("command/invoke: %v", err)
|
|
}
|
|
select {
|
|
case msg := <-notified:
|
|
if msg != "test.sidecar.linux:hello" {
|
|
t.Fatalf("unexpected notify msg: %q", msg)
|
|
}
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("timed out waiting for reverse Host API notification")
|
|
}
|
|
|
|
// 3. Diagnostics collection enforces host redaction of MAC & serial (§4.2, §7.1).
|
|
diags := reg.CollectDiagnostics(context.Background(), "ubuntu-24", reims.RedactText)
|
|
if len(diags) != 1 {
|
|
t.Fatalf("expected 1 diag entry, got %d", len(diags))
|
|
}
|
|
if strings.Contains(diags[0].Text, "aa:bb:cc") || strings.Contains(diags[0].Text, "C02SECRET") {
|
|
t.Fatalf("sensitive fields leaked in plugin diagnostics: %q", diags[0].Text)
|
|
}
|
|
|
|
// 4. Hung command is cancellable by timeout without hanging host!
|
|
hangCtx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
|
|
defer cancel()
|
|
if err := sup.Call(hangCtx, "command/invoke", map[string]any{"command": "hang"}, nil); err == nil {
|
|
t.Fatal("expected hang call to time out cleanly")
|
|
}
|
|
|
|
// 5. Stop terminates Sidecar cleanly (zero orphan process).
|
|
sup.Stop()
|
|
if sup.IsRunning() {
|
|
t.Fatal("expected Sidecar stopped with zero orphan process")
|
|
}
|
|
|
|
// 6. Crashing Sidecar trips circuit breaker without crashing host.
|
|
t.Setenv("REIMS_TEST_SIDECAR_MODE", "crash")
|
|
crashSup := plugin.NewSidecarSupervisor(plugin.SidecarOptions{
|
|
PluginID: "test.sidecar.crash",
|
|
ExePath: exePath,
|
|
Args: []string{"-test.run=^TestHelperSidecar$"},
|
|
DataDir: layout.DataDir("test.sidecar.crash"),
|
|
Broker: broker,
|
|
Registry: reg,
|
|
MaxRestarts: 2,
|
|
})
|
|
defer crashSup.Stop()
|
|
if err := crashSup.EnsureStarted(context.Background()); err == nil {
|
|
t.Fatal("expected crashing sidecar handshake error")
|
|
}
|
|
}
|