package plugin_test import ( "context" "encoding/json" "net/http" "net/http/httptest" "os" "strings" "sync/atomic" "testing" "time" "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) } }