package plugin_test import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "strings" "sync/atomic" "testing" "time" "github.com/Nwflower/reims-go/internal/downloader" "github.com/Nwflower/reims-go/internal/fetch" "github.com/Nwflower/reims-go/internal/plugin" ) func TestMarketFetchCacheAndFallback(t *testing.T) { var fail atomic.Bool srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if fail.Load() { w.WriteHeader(http.StatusServiceUnavailable) return } idx := plugin.MarketIndex{ Schema: 1, UpdatedAt: "2026-11-30T00:00:00Z", Plugins: []plugin.MarketEntry{{ ID: "community.theme.nord", Version: "1.2.0", Name: plugin.LocalizedText{ZhCN: "北欧主题", EnUS: "Nord Theme"}, Description: plugin.LocalizedText{EnUS: "Cool blue palette"}, Publisher: "nord", License: "MIT", Channel: "stable", Kind: "theme", Trust: plugin.TrustVerified, DownloadURL: "https://example.invalid/nord.zip", SHA256: strings.Repeat("a", 64), }}, } _ = json.NewEncoder(w).Encode(idx) })) defer srv.Close() dataRoot := t.TempDir() layout := plugin.NewPluginsLayout(dataRoot) mc := plugin.NewMarketClient(plugin.MarketClientOptions{ Layout: layout, HostVersion: "0.2.8", URLs: []string{srv.URL + "/index.json"}, CacheTTL: time.Minute, AllowInsecureLocalhost: true, }) // 1. Fresh remote fetch succeeds and populates disk cache. idx, src, stale, err := mc.LoadIndex(context.Background(), false) if err != nil || src != "remote" || stale || len(idx.Plugins) != 1 { t.Fatalf("first LoadIndex = (src=%s stale=%v len=%d err=%v)", src, stale, len(idx.Plugins), err) } if _, statErr := os.Stat(layout.IndexCachePath()); statErr != nil { t.Fatalf("expected disk cache at %s: %v", layout.IndexCachePath(), statErr) } // 2. Second load within TTL hits memory cache cleanly. _, src2, stale2, err2 := mc.LoadIndex(context.Background(), false) if err2 != nil || src2 != "cache" || stale2 { t.Fatalf("cached LoadIndex = (src=%s stale=%v err=%v)", src2, stale2, err2) } // 3. Server goes down + forceRefresh: must retain valid disk/mem cache with stale=true. fail.Store(true) mcFresh := plugin.NewMarketClient(plugin.MarketClientOptions{ Layout: layout, HostVersion: "0.2.8", URLs: []string{srv.URL + "/index.json"}, AllowInsecureLocalhost: true, }) idx3, src3, stale3, err3 := mcFresh.LoadIndex(context.Background(), true) if err3 == nil || src3 != "cache" || !stale3 || len(idx3.Plugins) != 1 { t.Fatalf("stale fallback LoadIndex = (src=%s stale=%v len=%d err=%v)", src3, stale3, len(idx3.Plugins), err3) } } func TestMarketBrowseAndInstallGates(t *testing.T) { // Prepare valid L1 theme zip and smuggled-script L1 zip. goodManifest, _ := json.Marshal(plugin.Manifest{ Schema: 1, ID: "community.theme.mist", Version: "1.1.0", Name: plugin.LocalizedText{ZhCN: "薄雾主题", EnUS: "Mist Theme"}, Description: plugin.LocalizedText{EnUS: "Clean L1 theme"}, Publisher: "mist-author", License: "MIT", Engines: plugin.Engines{ReimsGo: ">=0.2.0", PluginAPI: "^1.0.0"}, Contributes: plugin.Contributes{ Themes: []plugin.ThemeContribution{{ ID: "community.theme.mist", Name: plugin.LocalizedText{EnUS: "Mist"}, Stylesheet: "theme.css", }}, }, }) goodZip := makePluginZip(t, map[string][]byte{ "plugin.json": goodManifest, "theme.css": []byte(`.rg-p-sidebar { background: var(--surface-sidebar); }`), }, nil, false) goodBytes, _ := os.ReadFile(goodZip) goodSum, _ := fetch.FileSHA256(goodZip) evilManifest, _ := json.Marshal(plugin.Manifest{ Schema: 1, ID: "community.theme.evil", Version: "1.0.0", Name: plugin.LocalizedText{EnUS: "Evil Theme"}, }) evilZip := makePluginZip(t, map[string][]byte{ "plugin.json": evilManifest, "steal.ps1": []byte(`Write-Host "boom"`), }, nil, false) evilBytes, _ := os.ReadFile(evilZip) evilSum, _ := fetch.FileSHA256(evilZip) var srvURL string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/mist.zip": w.Header().Set("Content-Type", "application/zip") _, _ = w.Write(goodBytes) case "/evil.zip": w.Header().Set("Content-Type", "application/zip") _, _ = w.Write(evilBytes) case "/index.json": idx := plugin.MarketIndex{ Schema: 1, UpdatedAt: "2026-11-30T00:00:00Z", Plugins: []plugin.MarketEntry{ { ID: "community.theme.mist", Version: "1.1.0", Name: plugin.LocalizedText{ZhCN: "薄雾主题", EnUS: "Mist Theme"}, Description: plugin.LocalizedText{EnUS: "Clean L1 theme"}, Publisher: "mist-author", License: "MIT", Channel: "stable", Kind: "theme", Tier: plugin.TierL1, Trust: plugin.TrustCommunity, Engines: plugin.Engines{ReimsGo: ">=0.2.0", PluginAPI: "^1.0.0"}, DownloadURL: srvURL + "/mist.zip", SHA256: goodSum, SizeBytes: int64(len(goodBytes)), }, { ID: "community.theme.mist", Version: "1.2.0-alpha.1", Name: plugin.LocalizedText{EnUS: "Mist Alpha"}, Channel: "alpha", Kind: "theme", Trust: plugin.TrustCommunity, DownloadURL: srvURL + "/mist.zip", SHA256: goodSum, }, { ID: "community.theme.incompat", Version: "2.0.0", Name: plugin.LocalizedText{EnUS: "Future Theme"}, Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Engines: plugin.Engines{ReimsGo: ">=9.0.0"}, DownloadURL: srvURL + "/never-downloaded.zip", SHA256: strings.Repeat("b", 64), }, { ID: "community.theme.badhash", Version: "1.0.0", Name: plugin.LocalizedText{EnUS: "Bad Hash"}, Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, DownloadURL: srvURL + "/mist.zip", SHA256: strings.Repeat("0", 64), }, { ID: "community.theme.evil", Version: "1.0.0", Name: plugin.LocalizedText{EnUS: "Evil Theme"}, Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, DownloadURL: srvURL + "/evil.zip", SHA256: evilSum, }, }, Withdrawn: []plugin.MarketWithdrawal{{ ID: "community.old.tool", Reason: plugin.LocalizedText{ZhCN: "已合并进新插件", EnUS: "Merged into new plugin"}, InsteadID: "community.theme.mist", InsteadName: "Mist Theme", }}, } _ = json.NewEncoder(w).Encode(idx) default: w.WriteHeader(http.StatusNotFound) } })) defer srv.Close() srvURL = srv.URL dataRoot := t.TempDir() mgr, err := plugin.NewManager(plugin.ManagerOptions{ DataRoot: dataRoot, HostVersion: "0.2.8", }) if err != nil { t.Fatalf("NewManager: %v", err) } defer mgr.Close() mc := plugin.NewMarketClient(plugin.MarketClientOptions{ Layout: mgr.Layout(), HostVersion: "0.2.8", URLs: []string{srvURL + "/index.json"}, AllowInsecureLocalhost: true, }) // Browse stable only: should pick 1.1.0 (not 1.2.0-alpha.1) and surface WithdrawnInstalled. res := mc.Browse(context.Background(), []plugin.PluginInfo{ {ID: "community.old.tool", Version: "0.9.0"}, {ID: "community.theme.mist", Version: "1.0.0"}, }, plugin.MarketBrowseOptions{}) if len(res.WithdrawnInstalled) != 1 || res.WithdrawnInstalled[0].InsteadID != "community.theme.mist" { t.Fatalf("expected withdrawn installed advisory, got %+v", res.WithdrawnInstalled) } var mistItem *plugin.MarketCatalogItem for i := range res.Items { if res.Items[i].Entry.ID == "community.theme.mist" { mistItem = &res.Items[i] } } if mistItem == nil || mistItem.Entry.Version != "1.1.0" || !mistItem.UpdateAvailable || !mistItem.Compatible { t.Fatalf("unexpected mist catalog item: %+v", mistItem) } // Withdrawn plugin install refused with replacement hint. if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.old.tool", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "withdrawn") { t.Fatalf("expected withdrawn refusal, got: %v", err) } // Incompatible plugin refused BEFORE download. if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.incompat", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "incompatible") { t.Fatalf("expected incompatible refusal, got: %v", err) } // SHA-256 mismatch refused. if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.badhash", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") { t.Fatalf("expected SHA256 mismatch refusal, got: %v", err) } // Smuggled .ps1 in L1 zip refused by static security gate even when archive SHA-256 matches. if _, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.evil", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "static security gate") { t.Fatalf("expected static gate refusal for smuggled .ps1, got: %v", err) } // Valid market plugin installs cleanly with SourceMarket. info, err := mc.InstallFromMarket(context.Background(), mgr, "community.theme.mist", plugin.MarketInstallOptions{}) if err != nil { t.Fatalf("InstallFromMarket valid plugin: %v", err) } if info.ID != "community.theme.mist" || info.Version != "1.1.0" || info.Source != plugin.SourceMarket { t.Fatalf("unexpected installed info: %+v", info) } } func TestCheckMarketCompatibilityUnified(t *testing.T) { base := plugin.MarketEntry{ ID: "community.theme.compat", Version: "1.0.0", Engines: plugin.Engines{PluginAPI: "^1.0.0", UIAPI: "^2.0.0", BridgeAPI: "^1.0.0", ReimsGo: ">=0.2.10"}, } for _, plats := range [][]string{nil, {"*"}, {"any"}, {"ANY"}, {"windows-x64", "linux-x64", "darwin-arm64", "darwin-x64"}, {"windows/amd64", "linux/amd64", "darwin/arm64", "darwin/amd64"}} { e := base e.Platforms = plats if ok, reason := plugin.CheckMarketCompatibility(e, "0.2.11"); !ok { t.Fatalf("platforms=%v expected compatible, got: %s", plats, reason) } } // Dev host builds skip engines.reims-go just like ValidateManifest. if ok, reason := plugin.CheckMarketCompatibility(base, "dev"); !ok { t.Fatalf("dev host expected compatible, got: %s", reason) } // Unsupported platform rejected. badPlat := base badPlat.Platforms = []string{"solaris-sparc"} if ok, _ := plugin.CheckMarketCompatibility(badPlat, "0.2.11"); ok { t.Fatal("expected unsupported platform to be incompatible") } // Incompatible bridgeApi rejected before download. badBridge := base badBridge.Engines.BridgeAPI = "^9.0.0" if ok, reason := plugin.CheckMarketCompatibility(badBridge, "0.2.11"); ok || !strings.Contains(reason, "bridgeApi") { t.Fatalf("expected bridgeApi incompatibility, got ok=%v reason=%q", ok, reason) } } func TestMarketSecurityGatesSearchExtraAndConcurrentCache(t *testing.T) { var srvURL string srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { case "/index.json": idx := plugin.MarketIndex{ Schema: 1, UpdatedAt: "2026-12-02T00:00:00Z", Plugins: []plugin.MarketEntry{ { ID: "evil.theme.traversal", Version: "../../escape", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Traversal"}, DownloadURL: srvURL + "/pkg.zip", SHA256: strings.Repeat("a", 64), }, { ID: "evil.theme.spacesver", Version: " 1.0.0 ", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Spaces Version"}, DownloadURL: srvURL + "/pkg.zip", SHA256: strings.Repeat("a", 64), }, { ID: "evil.theme.oversize-body", Version: "1.0.0", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Oversize Body"}, DownloadURL: srvURL + "/oversize.zip", SHA256: strings.Repeat("e", 64), SizeBytes: 64, }, { ID: "evil.theme.stall", Version: "1.0.0", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Stall"}, DownloadURL: srvURL + "/stall.zip", SHA256: strings.Repeat("f", 64), SizeBytes: 0, }, { ID: "evil.theme.huge", Version: "1.0.0", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Huge"}, DownloadURL: srvURL + "/pkg.zip", SHA256: strings.Repeat("b", 64), SizeBytes: 1 << 30, }, { ID: "evil.theme.downgrade", Version: "1.0.0", Channel: "stable", Kind: "theme", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{EnUS: "Downgrade"}, DownloadURL: srvURL + "/redirect-http", SHA256: strings.Repeat("c", 64), }, { ID: "community.locale.ja", Version: "1.0.0", Channel: "stable", Kind: "locale", Trust: plugin.TrustCommunity, Name: plugin.LocalizedText{ EnUS: "Japanese Pack", Extra: map[string]string{"ja-JP": "日本語パック"}, }, Description: plugin.LocalizedText{ EnUS: "UI translation", Extra: map[string]string{"ko-KR": "한국어 설명"}, }, DownloadURL: srvURL + "/pkg.zip", SHA256: strings.Repeat("d", 64), }, }, } _ = json.NewEncoder(w).Encode(idx) case "/redirect-http": http.Redirect(w, r, "http://example.com/downgraded.zip", http.StatusFound) case "/oversize.zip": w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(strings.Repeat("Z", 1024))) case "/stall.zip": fl, _ := w.(http.Flusher) w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("slow")) if fl != nil { fl.Flush() } <-r.Context().Done() default: http.NotFound(w, r) } })) defer srv.Close() srvURL = srv.URL mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: t.TempDir(), HostVersion: "0.2.11"}) if err != nil { t.Fatalf("NewManager: %v", err) } defer mgr.Close() mc := plugin.NewMarketClient(plugin.MarketClientOptions{ Layout: mgr.Layout(), HostVersion: "0.2.11", URLs: []string{srvURL + "/index.json"}, DownloadStallTimeout: 150 * time.Millisecond, AllowInsecureLocalhost: true, }) // Register default ParallelDownloader (matching desktop app startup) to // prove market downloads bypass it and still enforce CheckRedirect & MaxBytes. parallel := downloader.NewParallelDownloader(func() downloader.ParallelOptions { return downloader.ParallelOptions{ID: "builtin.downloader.parallel", Connections: 2, ProxyMode: "direct"} }) fetch.SetDefaultDownloader(func() downloader.Provider { return parallel }) t.Cleanup(func() { fetch.SetDefaultDownloader(nil) }) // 1. Path traversal or surrounding whitespace in entry.Version must be rejected. if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.traversal", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") { t.Fatalf("expected invalid version error for traversal, got: %v", err) } if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.spacesver", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid version") { t.Fatalf("expected invalid version error for whitespace version, got: %v", err) } // 2. Oversized declared SizeBytes and oversized actual stream must both be rejected. if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.huge", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "invalid archive size") { t.Fatalf("expected invalid archive size error, got: %v", err) } if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.oversize-body", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "exceeds 64 byte limit") { t.Fatalf("expected actual stream byte limit error, got: %v", err) } // 3. Stalled market stream aborts via DownloadStallTimeout. if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.stall", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "stalled") { t.Fatalf("expected stalled error, got: %v", err) } // 4. Redirect to non-localhost plain HTTP must still be blocked even with ParallelDownloader active. if _, err := mc.InstallFromMarket(context.Background(), mgr, "evil.theme.downgrade", plugin.MarketInstallOptions{}); err == nil || !strings.Contains(err.Error(), "only HTTPS") { t.Fatalf("expected HTTPS-only redirect refusal with active ParallelDownloader, got: %v", err) } // 4. Market search matches localized Name.Extra and Description.Extra. resName := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "日本語"}) if len(resName.Items) != 1 || resName.Items[0].Entry.ID != "community.locale.ja" { t.Fatalf("expected Name.Extra search match, got %+v", resName.Items) } resDesc := mc.Browse(context.Background(), nil, plugin.MarketBrowseOptions{Query: "한국어"}) if len(resDesc.Items) != 1 || resDesc.Items[0].Entry.ID != "community.locale.ja" { t.Fatalf("expected Description.Extra search match, got %+v", resDesc.Items) } // 5. Concurrent force refreshes writing disk cache must not race or corrupt cache JSON. done := make(chan error, 8) for i := 0; i < 8; i++ { go func() { _, src, stale, ferr := mc.LoadIndex(context.Background(), true) if ferr != nil || src != "remote" || stale { done <- ferr return } done <- nil }() } for i := 0; i < 8; i++ { if err := <-done; err != nil { t.Fatalf("concurrent LoadIndex error: %v", err) } } raw, err := os.ReadFile(mgr.Layout().IndexCachePath()) if err != nil { t.Fatalf("read disk cache: %v", err) } var cached plugin.MarketIndex if err := json.Unmarshal(raw, &cached); err != nil || len(cached.Plugins) != 7 { t.Fatalf("corrupted disk cache after concurrent writes: err=%v len=%d", err, len(cached.Plugins)) } }