diff --git a/cmd/internal/check_provider_update.go b/cmd/internal/check_provider_update.go index aa0eaf5c60..403934393d 100644 --- a/cmd/internal/check_provider_update.go +++ b/cmd/internal/check_provider_update.go @@ -135,7 +135,7 @@ func loadLatestProvider( if err != nil { return nil, fmt.Errorf("resolve provider: %w", err) } - providerConfig, err := provider.ParseProvider(bytes.NewReader(providerRaw)) + providerConfig, err := provider.ParseAuthorProvider(bytes.NewReader(providerRaw)) if err != nil { return nil, fmt.Errorf("parse provider: %w", err) } diff --git a/cmd/internal/get_provider_name.go b/cmd/internal/get_provider_name.go index bfd4db160d..b5a3b352fe 100644 --- a/cmd/internal/get_provider_name.go +++ b/cmd/internal/get_provider_name.go @@ -40,7 +40,7 @@ func (cmd *GetProviderNameCmd) Run(ctx context.Context, args []string) error { return fmt.Errorf("resolve provider: %w", err) } - providerConfig, err := provider.ParseProvider(bytes.NewReader(providerRaw)) + providerConfig, err := provider.ParseAuthorProvider(bytes.NewReader(providerRaw)) if err != nil { return fmt.Errorf("parse provider: %w", err) } diff --git a/cmd/provider/add.go b/cmd/provider/add.go index 1c088a3003..d7cb7e739e 100644 --- a/cmd/provider/add.go +++ b/cmd/provider/add.go @@ -187,7 +187,7 @@ func (cmd *AddCmd) resolveAddSource( if providerName != "" { return resolvedAddSource{raw: raw, source: source, name: providerName}, nil } - parsed, err := provider.ParseProvider(bytes.NewReader(raw)) + parsed, err := provider.ParseAuthorProvider(bytes.NewReader(raw)) if err != nil { return resolvedAddSource{}, err } diff --git a/cmd/provider/add_test.go b/cmd/provider/add_test.go index 9a0c9f0204..082840b2c7 100644 --- a/cmd/provider/add_test.go +++ b/cmd/provider/add_test.go @@ -48,12 +48,20 @@ func (s *addDeprecationSuite) SetupTest() { client := devsyhttp.GetHTTPClient() previousTransport := client.Transport client.Transport = providerAddRoundTripper(func(req *http.Request) (*http.Response, error) { - const manifestURL = "https://github.com/devsy-org/devsy-provider-microsandbox/" + - "releases/latest/download/provider.yaml" - if req.URL.String() != manifestURL { - s.T().Fatalf("unexpected source request: %s", req.URL) + const ( + latestReleaseURL = "https://api.github.com/repos/devsy-org/" + + "devsy-provider-microsandbox/releases/latest" + manifestURL = "https://github.com/devsy-org/devsy-provider-microsandbox/" + + "releases/download/v0.1.8/provider.yaml" + ) + switch req.URL.String() { + case latestReleaseURL: + return providerAddResponse(req, `{"tag_name":"v0.1.8"}`), nil + case manifestURL: + return providerAddResponse(req, externalMicrosandboxManifest), nil } - return providerAddResponse(req, externalMicrosandboxManifest), nil + s.T().Fatalf("unexpected source request: %s", req.URL) + return nil, nil }) s.T().Cleanup(func() { client.Transport = previousTransport }) } @@ -76,6 +84,7 @@ func (s *addDeprecationSuite) TestMicrosandboxAliasUsesLatestExternalProvider() s.Require().Equal(tc.want, resolved.name) s.Require().Equal("github.com/devsy-org/devsy-provider-microsandbox", resolved.source.Raw) s.Require().Equal("devsy-org/devsy-provider-microsandbox", resolved.source.Github) + s.Require().Equal("v0.1.8", resolved.source.ResolvedRef) parsed, err := providerpkg.ParseProvider(bytes.NewReader(resolved.raw)) s.Require().NoError(err) s.Require().Equal(providerpkg.ExternalDriver, parsed.Agent.Driver) diff --git a/cmd/provider/icon.go b/cmd/provider/icon.go new file mode 100644 index 0000000000..54433c390e --- /dev/null +++ b/cmd/provider/icon.go @@ -0,0 +1,107 @@ +package provider + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "io/fs" + "os" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/config" + cliflags "github.com/devsy-org/devsy/pkg/flags" + "github.com/devsy-org/devsy/pkg/flags/names" + "github.com/devsy-org/devsy/pkg/output" + "github.com/devsy-org/devsy/pkg/provider" + "github.com/devsy-org/devsy/pkg/telemetry" + "github.com/spf13/cobra" +) + +const ( + iconThemeLight = "light" + iconThemeDark = "dark" +) + +// IconCmd holds the icon cmd flags. +type IconCmd struct { + *flags.GlobalFlags + + Theme string +} + +// NewIconCmd creates a new command. +func NewIconCmd(flags *flags.GlobalFlags) *cobra.Command { + cmd := &IconCmd{ + GlobalFlags: flags, + } + iconCmd := &cobra.Command{ + Use: "icon [name]", + Short: "Print an installed provider's cached icon as JSON", + Long: "Reads the icon cached for an installed provider. The result is always JSON: " + + "{revision, mimeType, dataBase64} for an image or {revision, missing: true} " + + "when the provider has no usable image for the theme. Never uses the network.", + Args: cobra.ExactArgs(1), + Annotations: telemetry.SkipInUIAnnotation(), + RunE: func(_ *cobra.Command, args []string) error { + if cmd.Context != "" { + if err := config.ValidateContextPathName(cmd.Context); err != nil { + return fmt.Errorf("invalid provider icon context: %w", err) + } + } + devsyConfig, err := config.LoadConfig(cmd.Context, cmd.Provider) + if err != nil { + return err + } + + return cmd.Run(devsyConfig, args[0], os.Stdout) + }, + } + + cliflags.Add( + iconCmd, + cliflags.String(&cmd.Theme, names.Theme, iconThemeLight, "Icon variant: light or dark"), + ) + + return iconCmd +} + +// Run prints the cached icon of the installed provider for the selected theme. +func (cmd *IconCmd) Run(devsyConfig *config.Config, providerName string, out io.Writer) error { + if err := cmd.validate(devsyConfig.DefaultContext, providerName); err != nil { + return err + } + + providerConfig, err := provider.LoadProviderConfig(devsyConfig.DefaultContext, providerName) + if errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("provider with name %s not found", providerName) + } + if err != nil { + return fmt.Errorf("load provider %s: %w", providerName, err) + } + + result, err := provider.ReadProviderIcon(devsyConfig.DefaultContext, providerConfig, cmd.Theme) + if err != nil { + return fmt.Errorf("read icon of provider %s: %w", providerName, err) + } + + return json.NewEncoder(out).Encode(result) +} + +func (cmd *IconCmd) validate(defaultContext, providerName string) error { + if err := config.ValidateContextPathName(defaultContext); err != nil { + return fmt.Errorf("invalid provider icon context: %w", err) + } + if err := validateProviderName(providerName); err != nil { + return err + } + if cmd.Theme != iconThemeLight && cmd.Theme != iconThemeDark { + return fmt.Errorf("unexpected theme %q, choose light or dark", cmd.Theme) + } + // The icon is a data contract for machine consumers, but an invalid + // format must still fail like it does for every other command. + if _, err := output.ResolveMode(cmd.ResultFormat); err != nil { + return err + } + return nil +} diff --git a/cmd/provider/icon_test.go b/cmd/provider/icon_test.go new file mode 100644 index 0000000000..b75c960208 --- /dev/null +++ b/cmd/provider/icon_test.go @@ -0,0 +1,236 @@ +package provider + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/devsy-org/devsy/cmd/flags" + "github.com/devsy-org/devsy/pkg/config" + providerpkg "github.com/devsy-org/devsy/pkg/provider" + "github.com/devsy-org/devsy/pkg/workspace" + "github.com/stretchr/testify/suite" + "sigs.k8s.io/yaml" +) + +const ( + iconProviderName = "icon-provider" + iconLightPath = "assets/light.svg" + iconDarkPath = "assets/dark.svg" + iconLightSVG = `` + + `` + iconDarkSVG = `` + + `` + iconResultFormatJSON = "json" +) + +type providerIconCmdSuite struct { + suite.Suite + + devsyConfig *config.Config +} + +func TestProviderIconCmdSuite(t *testing.T) { + suite.Run(t, new(providerIconCmdSuite)) +} + +func (s *providerIconCmdSuite) SetupTest() { + s.T().Setenv("DEVSY_HOME", s.T().TempDir()) + s.devsyConfig = setupProviderOperationTest(s.T()) +} + +func (s *providerIconCmdSuite) TestPrintsCachedImagePerTheme() { + added := s.installWithIcons() + want := map[string]string{"light": iconLightSVG, "dark": iconDarkSVG} + + for theme, svg := range want { + out, err := s.run(iconProviderName, theme) + s.Require().NoError(err) + + var result providerpkg.ProviderIconResult + s.Require().NoError(json.Unmarshal([]byte(out), &result)) + s.Require().Equal(added.IconRevision, result.Revision) + s.Require().Equal("image/svg+xml", result.MimeType) + s.Require().False(result.Missing) + decoded, err := base64.StdEncoding.DecodeString(result.DataBase64) + s.Require().NoError(err) + s.Require().Equal(svg, string(decoded)) + } +} + +func (s *providerIconCmdSuite) TestMissingVariantIsANormalResult() { + s.install( + iconProviderName, + &providerpkg.ProviderConfig{Icon: iconLightPath, IconDark: iconDarkPath}, + map[string]string{iconLightPath: iconLightSVG}, + ) + + out, err := s.run(iconProviderName, "dark") + s.Require().NoError(err) + + var raw map[string]any + s.Require().NoError(json.Unmarshal([]byte(out), &raw)) + s.Require().Equal(true, raw["missing"]) + s.Require().NotContains(raw, "dataBase64") + s.Require().NotEmpty(raw["revision"]) +} + +func (s *providerIconCmdSuite) TestProviderWithoutIconsIsMissing() { + s.install(iconProviderName, &providerpkg.ProviderConfig{}, nil) + + out, err := s.run(iconProviderName, "light") + s.Require().NoError(err) + + var result providerpkg.ProviderIconResult + s.Require().NoError(json.Unmarshal([]byte(out), &result)) + s.Require().True(result.Missing) + s.Require().Empty(result.DataBase64) +} + +func (s *providerIconCmdSuite) TestRejectsUnknownProvider() { + _, err := s.run("does-not-exist", "light") + + s.Require().ErrorContains(err, "not found") +} + +func (s *providerIconCmdSuite) TestRejectsInvalidTheme() { + s.installWithIcons() + + _, err := s.run(iconProviderName, "sepia") + + s.Require().ErrorContains(err, "theme") +} + +func (s *providerIconCmdSuite) TestRejectsInvalidProviderIdentityBeforeDiskRead() { + for _, name := range []string{ + "../" + iconProviderName, + "/tmp/provider", + `..\provider`, + "bad\x00name", + strings.Repeat("a", 33), + "", + } { + s.Run(name, func() { + out, err := s.run(name, "light") + s.Require().ErrorContains(err, "provider name") + s.Require().Empty(out) + s.Require().NotContains(err.Error(), "not found") + }) + } +} + +func (s *providerIconCmdSuite) TestRejectsUnsafeContextBeforeConfigRead() { + configPath := s.T().TempDir() + s.T().Setenv(config.EnvConfig, configPath) + + for _, contextName := range []string{ + "../../other", + `..\target`, + `C:\target`, + strings.Repeat("a", 256), + } { + global := &flags.GlobalFlags{Context: contextName, ResultFormat: iconResultFormatJSON} + command := NewIconCmd(global) + err := command.RunE(command, []string{iconProviderName}) + s.ErrorContains(err, "invalid provider icon context") + } +} + +func (s *providerIconCmdSuite) TestAcceptsSafeUnicodeLegacyContext() { + const legacyContext = "legacy-\u6771\u4eac" + s.devsyConfig.DefaultContext = legacyContext + s.devsyConfig.Contexts[legacyContext] = &config.ContextConfig{ + Providers: map[string]*config.ProviderConfig{}, + } + s.installWithIcons() + + out, err := s.run(iconProviderName, "light") + + s.Require().NoError(err) + s.NotEmpty(out) +} + +func (s *providerIconCmdSuite) TestDoesNotInitializeProvider() { + s.installWithIcons() + + _, err := s.run(iconProviderName, "light") + s.Require().NoError(err) + + stored, err := config.LoadConfig(s.devsyConfig.DefaultContext, "") + s.Require().NoError(err) + state := stored.Current().Providers[iconProviderName] + s.Require().NotNil(state) + s.Require().False(state.Initialized) + s.Require().False(state.InitAttempted) +} + +func (s *providerIconCmdSuite) TestListKeepsIconMetadataWithoutImageBytes() { + added := s.installWithIcons() + reloaded, err := config.LoadConfig(s.devsyConfig.DefaultContext, "") + s.Require().NoError(err) + providers, err := workspace.LoadAllProviders(reloaded) + s.Require().NoError(err) + + cmd := &ListCmd{} + output := captureProviderListOutput(s.T(), func() error { + return cmd.renderInstalledJSON(reloaded, reloaded.Current().Providers, providers) + }) + s.Require().NoError(output.err) + + var result map[string]struct { + Config map[string]any `json:"config"` + } + s.Require().NoError(json.Unmarshal([]byte(output.text), &result)) + entry := result[iconProviderName].Config + s.Require().Equal(iconLightPath, entry["icon"]) + s.Require().Equal(iconDarkPath, entry["iconDark"]) + s.Require().Equal(added.IconRevision, entry["iconRevision"]) + s.Require().NotEmpty(entry["iconRevision"]) + s.Require().NotContains(output.text, "dataBase64") + s.Require().NotContains(output.text, base64.StdEncoding.EncodeToString([]byte(iconLightSVG))) +} + +func (s *providerIconCmdSuite) install( + name string, manifest *providerpkg.ProviderConfig, + assets map[string]string, +) *providerpkg.ProviderConfig { + dir := s.T().TempDir() + manifest.Name = name + manifest.Version = "1.0.0" + manifest.Exec = providerpkg.ProviderCommands{Command: []string{"true"}} + raw, err := yaml.Marshal(manifest) + s.Require().NoError(err) + source := filepath.Join(dir, "provider.yaml") + s.Require().NoError(os.WriteFile(source, raw, 0o600)) + for assetName, content := range assets { + target := filepath.Join(dir, filepath.FromSlash(assetName)) + s.Require().NoError(os.MkdirAll(filepath.Dir(target), 0o700)) + s.Require().NoError(os.WriteFile(target, []byte(content), 0o600)) + } + added, err := workspace.AddProvider(context.Background(), s.devsyConfig, name, source) + s.Require().NoError(err) + return added +} + +func (s *providerIconCmdSuite) installWithIcons() *providerpkg.ProviderConfig { + return s.install( + iconProviderName, + &providerpkg.ProviderConfig{Icon: iconLightPath, IconDark: iconDarkPath}, + map[string]string{iconLightPath: iconLightSVG, iconDarkPath: iconDarkSVG}, + ) +} + +func (s *providerIconCmdSuite) run(name, theme string) (string, error) { + cmd := &IconCmd{ + GlobalFlags: &flags.GlobalFlags{ResultFormat: iconResultFormatJSON}, + Theme: theme, + } + var out bytes.Buffer + err := cmd.Run(s.devsyConfig, name, &out) + return out.String(), err +} diff --git a/cmd/provider/provider.go b/cmd/provider/provider.go index 7b268bb330..562990fe02 100644 --- a/cmd/provider/provider.go +++ b/cmd/provider/provider.go @@ -15,6 +15,7 @@ func NewProviderCmd(flags *flags.GlobalFlags) *cobra.Command { providerCmd.AddCommand(NewAddCmd(flags)) providerCmd.AddCommand(NewDeleteCmd(flags)) providerCmd.AddCommand(NewGetCmd(flags)) + providerCmd.AddCommand(NewIconCmd(flags)) providerCmd.AddCommand(NewInitCmd(flags)) providerCmd.AddCommand(NewListCmd(flags)) providerCmd.AddCommand(NewRenameCmd(flags)) diff --git a/cmd/workspace/import.go b/cmd/workspace/import.go index bce4b5b2de..86eec98fbf 100644 --- a/cmd/workspace/import.go +++ b/cmd/workspace/import.go @@ -299,6 +299,9 @@ func (cmd *ImportCmd) importProvider( return fmt.Errorf("load provider config: %w", err) } providerConfig.Name = cmd.ProviderID + // The icon cache is local to the exporting machine's context; the imported + // provider falls back to bundled artwork until it is next updated. + providerConfig.IconRevision = "" // save provider config err = provider.SaveProviderConfig(devsyConfig.DefaultContext, providerConfig) diff --git a/desktop/src/main/__tests__/cli.test.ts b/desktop/src/main/__tests__/cli.test.ts index e06dbcfc4f..a80279aefa 100644 --- a/desktop/src/main/__tests__/cli.test.ts +++ b/desktop/src/main/__tests__/cli.test.ts @@ -154,6 +154,20 @@ describe("CliRunner", () => { ) }) + it("raises the stdout cap of run() only when asked to", async () => { + const mock = vi.mocked(execFile) as unknown as ReturnType + mock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, callback: ExecCb) => + callback(null, { stdout: "{}", stderr: "" }), + ) + + await cli.run(["provider", "list"]) + await cli.run(["provider", "icon", "harvester"], { maxBuffer: 4096 }) + + expect(mock.mock.calls[0][2]).not.toHaveProperty("maxBuffer") + expect(mock.mock.calls[1][2].maxBuffer).toBe(4096) + }) + it.each(["run", "runRaw"] as const)( "%s preserves unlock errors without invoking the handler when prompting is disabled", async (method) => { diff --git a/desktop/src/main/__tests__/ipc-provider-icon.test.ts b/desktop/src/main/__tests__/ipc-provider-icon.test.ts new file mode 100644 index 0000000000..e44fbcc946 --- /dev/null +++ b/desktop/src/main/__tests__/ipc-provider-icon.test.ts @@ -0,0 +1,264 @@ +// @vitest-environment node +import { join } from "node:path" +import { pathToFileURL } from "node:url" +import { beforeEach, describe, expect, it, vi } from "vitest" +import { registerIpcHandlers } from "../ipc.js" +import { ProviderJobs } from "../provider-jobs.js" +import { DaemonState } from "../state.js" + +const handlers = new Map unknown>() +let trustedEvent: unknown +let foreignEvent: unknown + +vi.mock("electron", () => ({ + app: { + getPath: () => "/tmp", + getAppPath: () => "/tmp", + getVersion: () => "0.0.0", + }, + dialog: {}, + ipcMain: { + handle: (channel: string, fn: (...args: unknown[]) => unknown) => { + handlers.set(channel, fn) + }, + on: () => undefined, + }, +})) + +vi.mock("../analytics.js", () => ({ + hashWorkspaceRef: (v: string) => v, + trackEvent: () => undefined, +})) + +const ICON = { + revision: "rev-a", + mimeType: "image/png", + dataBase64: Buffer.from("png").toString("base64"), +} + +function setup() { + const cli = { + setUnlockHandler: vi.fn(), + run: vi.fn(async (_args: string[]) => ICON), + runRaw: vi.fn(async () => ""), + runStreaming: vi.fn( + async ( + _args: string[], + _onLine: (line: string, stream: string) => void, + onExit: (code: number) => void, + ) => onExit(0), + ), + } + const state = new DaemonState() + const mainFrame = { + url: pathToFileURL(join(__dirname, "../../renderer/index.html")).href, + isDestroyed: () => false, + } + const webContents = { send: vi.fn(), mainFrame, isDestroyed: () => false } + const win = { webContents, isDestroyed: () => false } + trustedEvent = { sender: webContents, senderFrame: mainFrame } + foreignEvent = { + sender: webContents, + senderFrame: { ...mainFrame, url: "https://example.com/" }, + } + registerIpcHandlers({ + cli, + state, + providerJobs: new ProviderJobs(), + getMainWindow: () => win, + } as never) + return { cli, state } +} + +function invoke( + event: unknown, + channel: string, + args: Record, +) { + const handler = handlers.get(channel) + if (!handler) throw new Error(`${channel} not registered`) + return handler(event, args) +} + +const iconArgs = { + providerName: "harvester", + context: "default", + theme: "light", + expectedRevision: "rev-a", +} + +describe("provider_icon IPC", () => { + beforeEach(() => { + vi.stubEnv("ELECTRON_RENDERER_URL", "") + handlers.clear() + vi.clearAllMocks() + }) + + it("returns the data URL for a trusted sender", async () => { + const { cli } = setup() + + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).resolves.toEqual({ + revision: "rev-a", + dataUrl: `data:image/png;base64,${ICON.dataBase64}`, + }) + expect(cli.run).toHaveBeenCalledTimes(1) + }) + + it("rejects a sender that is not the main application document", async () => { + const { cli } = setup() + + await expect( + invoke(foreignEvent, "provider_icon", iconArgs), + ).rejects.toThrow(/main application window/) + await expect(invoke(undefined, "provider_icon", iconArgs)).rejects.toThrow() + expect(cli.run).not.toHaveBeenCalled() + }) + + it("falls back to the active context when the caller sends none", async () => { + const { cli, state } = setup() + state.updateContexts([{ name: "work" }], "work") + + await invoke(trustedEvent, "provider_icon", { ...iconArgs, context: "" }) + + const args = cli.run.mock.calls[0][0] + expect(args[args.indexOf("--context") + 1]).toBe("work") + }) + + it("drops cached images when the provider is deleted", async () => { + const { cli } = setup() + await invoke(trustedEvent, "provider_icon", iconArgs) + await invoke(trustedEvent, "provider_icon", iconArgs) + expect(cli.run).toHaveBeenCalledTimes(1) + + await invoke(trustedEvent, "provider_delete", { name: "harvester" }) + await invoke(trustedEvent, "provider_icon", iconArgs) + + expect(cli.run).toHaveBeenCalledTimes(2) + }) + + it("drops cached images when the provider is renamed", async () => { + const { cli } = setup() + await invoke(trustedEvent, "provider_icon", iconArgs) + + await invoke(trustedEvent, "provider_rename", { + name: "harvester", + newName: "harvester-2", + }) + await invoke(trustedEvent, "provider_icon", iconArgs) + + expect(cli.run).toHaveBeenCalledTimes(2) + }) + + it("drops cached images for every provider on context switch", async () => { + const { cli } = setup() + await invoke(trustedEvent, "provider_icon", iconArgs) + + await invoke(trustedEvent, "context_use", { name: "work" }) + await invoke(trustedEvent, "provider_icon", iconArgs) + + expect(cli.run).toHaveBeenCalledTimes(2) + }) + + it("drops cached images after a provider update", async () => { + const { cli } = setup() + await invoke(trustedEvent, "provider_icon", iconArgs) + + await invoke(trustedEvent, "provider_update", { name: "harvester" }) + await invoke(trustedEvent, "provider_icon", iconArgs) + + expect(cli.run).toHaveBeenCalledTimes(2) + }) + + it("preserves a pending image when an unrelated provider is deleted", async () => { + const { cli, state } = setup() + state.updateProviders([ + { name: "harvester", iconRevision: "rev-a" }, + { name: "other", iconRevision: "other-a" }, + ]) + const { promise, resolve: finish } = Promise.withResolvers() + cli.run.mockImplementationOnce(() => promise) + const pending = invoke(trustedEvent, "provider_icon", iconArgs) + + await invoke(trustedEvent, "provider_delete", { name: "other" }) + state.updateProviders([{ name: "harvester", iconRevision: "rev-a" }]) + finish(ICON) + + const expected = { + revision: "rev-a", + dataUrl: `data:image/png;base64,${ICON.dataBase64}`, + } + await expect(pending).resolves.toEqual(expected) + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).resolves.toEqual(expected) + expect(cli.run).toHaveBeenCalledTimes(1) + }) + + it("rejects cached bytes after polling observes an external source replacement", async () => { + const { cli, state } = setup() + state.updateProviders([{ name: "harvester", iconRevision: "rev-a" }]) + await invoke(trustedEvent, "provider_icon", iconArgs) + + state.updateProviders([{ name: "harvester", iconRevision: "rev-b" }]) + cli.run.mockResolvedValue({ ...ICON, revision: "rev-b" }) + + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).resolves.toEqual({ revision: "rev-b", stale: true }) + }) + + it("does not serve cached bytes after polling observes deletion", async () => { + const { cli, state } = setup() + state.updateProviders([{ name: "harvester", iconRevision: "rev-a" }]) + await invoke(trustedEvent, "provider_icon", iconArgs) + + state.updateProviders([]) + cli.run.mockRejectedValue(new Error("provider not found")) + + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).rejects.toThrow("provider not found") + }) + + it("does not retain an old context's bytes across externally observed switches", async () => { + const { cli, state } = setup() + state.updateContexts([{ name: "default" }, { name: "work" }], "default") + await invoke(trustedEvent, "provider_icon", iconArgs) + + state.updateContexts([{ name: "default" }, { name: "work" }], "work") + state.updateContexts([{ name: "default" }, { name: "work" }], "default") + cli.run.mockRejectedValue(new Error("provider no longer installed")) + + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).rejects.toThrow("provider no longer installed") + }) + + it.each(["replacement", "deletion", "context"] as const)( + "revokes pending bytes after an externally observed %s without refilling stale cache", + async (transition) => { + const { cli, state } = setup() + state.updateProviders([{ name: "harvester", iconRevision: "rev-a" }]) + const { promise, resolve: finish } = Promise.withResolvers() + cli.run.mockImplementationOnce(() => promise) + const pending = invoke(trustedEvent, "provider_icon", iconArgs) + + if (transition === "replacement") + state.updateProviders([{ name: "harvester", iconRevision: "rev-b" }]) + else if (transition === "deletion") state.updateProviders([]) + else state.updateContexts([{ name: "default" }, { name: "work" }], "work") + finish(ICON) + + await expect(pending).resolves.toEqual({ + revision: transition === "replacement" ? "rev-b" : "", + stale: true, + }) + cli.run.mockRejectedValueOnce(new Error("new installed read failed")) + await expect( + invoke(trustedEvent, "provider_icon", iconArgs), + ).rejects.toThrow("new installed read failed") + }, + ) +}) diff --git a/desktop/src/main/__tests__/provider-icons.test.ts b/desktop/src/main/__tests__/provider-icons.test.ts new file mode 100644 index 0000000000..8ff9d313ca --- /dev/null +++ b/desktop/src/main/__tests__/provider-icons.test.ts @@ -0,0 +1,318 @@ +// @vitest-environment node +import { describe, expect, it, vi } from "vitest" +import { PROVIDER_ICON_MAX_BYTES } from "../../shared/provider-icon.js" +import { ProviderIconReader, toObservedIcon } from "../provider-icons.js" + +const SVG_BASE64 = Buffer.from( + "", +).toString("base64") + +function cached(revision: string, overrides: Record = {}) { + return { + revision, + mimeType: "image/svg+xml", + dataBase64: SVG_BASE64, + ...overrides, + } +} + +function makeReader(run: (args: string[]) => Promise) { + const cli = { run: vi.fn((args: string[]) => run(args)) } + return { reader: new ProviderIconReader(cli as never), cli } +} + +function request(overrides: Record = {}) { + return { + providerName: "harvester", + context: "default", + theme: "light" as const, + expectedRevision: "rev-a", + ...overrides, + } +} + +describe("ProviderIconReader", () => { + it("reads the installed provider through the icon command and builds a data URL", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + + await expect(reader.read(request())).resolves.toEqual({ + revision: "rev-a", + dataUrl: `data:image/svg+xml;base64,${SVG_BASE64}`, + }) + expect(cli.run).toHaveBeenCalledWith( + [ + "provider", + "icon", + "harvester", + "--theme", + "light", + "--context", + "default", + "--result-format", + "json", + ], + { maxBuffer: expect.any(Number) }, + ) + const [, options] = cli.run.mock.calls[0] as unknown as [ + string[], + { maxBuffer: number }, + ] + // A maximum-size image encodes to ~1.4 MB of base64, above Node's default cap. + expect(options.maxBuffer).toBeGreaterThan(PROVIDER_ICON_MAX_BYTES * 1.4) + }) + + it("caches by context, provider, revision and theme", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + + await reader.read(request()) + await reader.read(request()) + expect(cli.run).toHaveBeenCalledTimes(1) + + await reader.read(request({ theme: "dark" })) + await reader.read(request({ context: "other" })) + await reader.read(request({ providerName: "sibling" })) + expect(cli.run).toHaveBeenCalledTimes(4) + }) + + it("coalesces concurrent identical reads into one CLI call", async () => { + const gate = Promise.withResolvers() + const { reader, cli } = makeReader(() => gate.promise) + + const first = reader.read(request()) + const second = reader.read(request()) + gate.resolve(cached("rev-a")) + + expect(await first).toEqual(await second) + expect(cli.run).toHaveBeenCalledTimes(1) + }) + + it("returns the observed revision, never old bytes, for a stale expectedRevision", async () => { + const { reader, cli } = makeReader(async () => cached("rev-b")) + + const stale = await reader.read(request({ expectedRevision: "rev-a" })) + + expect(stale).toEqual({ revision: "rev-b", stale: true }) + expect(stale).not.toHaveProperty("dataUrl") + + // The observed revision is cached, so the caller's retry does not hit the CLI. + await expect( + reader.read(request({ expectedRevision: "rev-b" })), + ).resolves.toMatchObject({ revision: "rev-b", dataUrl: expect.any(String) }) + expect(cli.run).toHaveBeenCalledTimes(1) + }) + + it("never serves a cached revision A image for a request expecting revision B", async () => { + const revisions = ["rev-a", "rev-b"] + const { reader } = makeReader(async () => cached(revisions.shift() ?? "")) + + await reader.read(request({ expectedRevision: "rev-a" })) + const reply = await reader.read(request({ expectedRevision: "rev-b" })) + + expect(reply).toEqual({ revision: "rev-b", dataUrl: expect.any(String) }) + }) + + it("reports a missing variant as a normal, cached result", async () => { + const { reader, cli } = makeReader(async () => ({ + revision: "rev-a", + missing: true, + })) + + await expect(reader.read(request())).resolves.toEqual({ + revision: "rev-a", + missing: true, + }) + await reader.read(request()) + expect(cli.run).toHaveBeenCalledTimes(1) + }) + + it("answers an installation without icons with an empty-revision missing result and does not cache it", async () => { + const { reader, cli } = makeReader(async () => ({ missing: true })) + + const reply = await reader.read(request({ expectedRevision: "" })) + await reader.read(request({ expectedRevision: "" })) + + expect(reply).toEqual({ revision: "", missing: true }) + expect(cli.run).toHaveBeenCalledTimes(2) + }) + + it("does not cache failures", async () => { + let calls = 0 + const { reader } = makeReader(async () => { + if (++calls === 1) throw new Error("disk error") + return cached("rev-a") + }) + + await expect(reader.read(request())).rejects.toThrow("disk error") + await expect(reader.read(request())).resolves.toMatchObject({ + dataUrl: expect.any(String), + }) + }) + + it("refetches a provider after it is invalidated, leaving other providers cached", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + await reader.read(request()) + await reader.read(request({ providerName: "sibling" })) + + reader.invalidateProvider("harvester") + await reader.read(request()) + await reader.read(request({ providerName: "sibling" })) + + expect(cli.run).toHaveBeenCalledTimes(3) + }) + + it("clears every provider on context switch", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + await reader.read(request()) + await reader.read(request({ providerName: "sibling" })) + + reader.invalidateAll() + await reader.read(request()) + await reader.read(request({ providerName: "sibling" })) + + expect(cli.run).toHaveBeenCalledTimes(4) + }) + + it.each(["provider", "context"] as const)( + "returns stale without old bytes after pending-read %s invalidation", + async (scope) => { + const gates = [ + Promise.withResolvers(), + Promise.withResolvers(), + ] + let next = 0 + const { reader } = makeReader(() => gates[next++].promise) + const newData = Buffer.from("").toString("base64") + const newImage = `data:image/svg+xml;base64,${newData}` + + const inFlight = reader.read(request()) + if (scope === "provider") reader.invalidateProvider("harvester") + else reader.invalidateAll() + const after = reader.read(request({ expectedRevision: "rev-b" })) + gates[1].resolve(cached("rev-b", { dataBase64: newData })) + await expect(after).resolves.toEqual({ + revision: "rev-b", + dataUrl: newImage, + }) + + gates[0].resolve(cached("rev-a")) + const stale = await inFlight + expect(stale).toEqual({ revision: "rev-a", stale: true }) + expect(stale).not.toHaveProperty("dataUrl") + await expect( + reader.read(request({ expectedRevision: "rev-b" })), + ).resolves.toEqual({ revision: "rev-b", dataUrl: newImage }) + }, + ) + + it.each([ + ["theme", { theme: "sepia" }], + ["provider name", { providerName: "" }], + ["flag-like provider name", { providerName: "--help" }], + ["context", { context: "" }], + ["dot traversal context", { context: "../../other" }], + ["slash context", { context: "default/other" }], + ["backslash context", { context: String.raw`default\other` }], + ["drive-shaped context", { context: "C:other" }], + ["oversized context", { context: "a".repeat(256) }], + ["provider path", { providerName: "../harvester" }], + ["uppercase provider", { providerName: "Harvester" }], + ["oversized provider", { providerName: "a".repeat(33) }], + ["NUL provider", { providerName: "harvester\0other" }], + ["NUL context", { context: "default\0other" }], + ["NUL revision", { expectedRevision: "rev-a\0other" }], + ])( + "rejects an invalid %s without invoking the CLI", + async (_label, overrides) => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + + await expect(reader.read(request(overrides))).rejects.toThrow() + expect(cli.run).not.toHaveBeenCalled() + }, + ) + it("accepts safe Unicode legacy contexts", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + const context = "legacy-\u6771\u4eac" + + await reader.read(request({ context })) + + expect(cli.run).toHaveBeenCalledTimes(1) + const args = cli.run.mock.calls[0][0] + expect(args[args.indexOf("--context") + 1]).toBe(context) + }) + + it("rejects embedded context separators without exposing existing cached bytes", async () => { + const { reader, cli } = makeReader(async () => cached("rev-a")) + await reader.read(request()) + + // Cache key fields must not contain another identity's separator. + await expect( + reader.read( + request({ + context: "default\0harvester", + providerName: "rev-a", + expectedRevision: "", + }), + ), + ).rejects.toThrow(/valid context/) + expect(cli.run).toHaveBeenCalledTimes(1) + await expect(reader.read(request())).resolves.toMatchObject({ + revision: "rev-a", + dataUrl: `data:image/svg+xml;base64,${SVG_BASE64}`, + }) + }) +}) + +describe("toObservedIcon bounds", () => { + it.each(["image/png", "image/jpeg", "image/webp", "image/svg+xml"])( + "accepts %s", + (mimeType) => { + expect(toObservedIcon(cached("rev", { mimeType }))).toEqual({ + revision: "rev", + dataUrl: `data:${mimeType};base64,${SVG_BASE64}`, + }) + }, + ) + + it.each([ + "text/html", + "image/gif", + "image/svg+xml;charset=utf-8", + "image/png,evil", + "", + ])("rejects unsupported MIME type %j", (mimeType) => { + expect(() => toObservedIcon(cached("rev", { mimeType }))).toThrow( + /unsupported image type/, + ) + }) + + it("accepts exactly the size limit and rejects one byte more", () => { + const atLimit = Buffer.alloc(PROVIDER_ICON_MAX_BYTES, 1).toString("base64") + const overLimit = Buffer.alloc(PROVIDER_ICON_MAX_BYTES + 1, 1).toString( + "base64", + ) + + expect( + toObservedIcon(cached("rev", { dataBase64: atLimit })), + ).toMatchObject({ revision: "rev" }) + expect(() => + toObservedIcon(cached("rev", { dataBase64: overLimit })), + ).toThrow(/too large/) + }) + + it.each([ + ["empty data", ""], + ["non-base64 characters", "not base64!"], + ["unpadded data", "QUJD1"], + ["data URL injection", `${SVG_BASE64}"onerror="x`], + ["non-string data", 42], + ])("rejects %s", (_label, dataBase64) => { + expect(() => toObservedIcon(cached("rev", { dataBase64 }))).toThrow( + /invalid or too large/, + ) + }) + + it("rejects a result that is not an object", () => { + expect(() => toObservedIcon("nope")).toThrow() + expect(() => toObservedIcon(null)).toThrow() + }) +}) diff --git a/desktop/src/main/__tests__/state.test.ts b/desktop/src/main/__tests__/state.test.ts index 46e77ce458..f5d3a4d4eb 100644 --- a/desktop/src/main/__tests__/state.test.ts +++ b/desktop/src/main/__tests__/state.test.ts @@ -79,6 +79,16 @@ describe("DaemonState", () => { ).toBe(true) }) + it("publishes a provider whose only change is its icon revision", () => { + const state = new DaemonState() + state.updateProviders([{ name: "harvester", iconRevision: "rev-a" }]) + + expect( + state.updateProviders([{ name: "harvester", iconRevision: "rev-b" }]), + ).toBe(true) + expect(state.providerList()[0]).toMatchObject({ iconRevision: "rev-b" }) + }) + it("confirms provider mode changes without mutating other cached data", () => { const state = new DaemonState() const provider = { diff --git a/desktop/src/main/__tests__/watcher.test.ts b/desktop/src/main/__tests__/watcher.test.ts index 1c1b3db868..0302d1c122 100644 --- a/desktop/src/main/__tests__/watcher.test.ts +++ b/desktop/src/main/__tests__/watcher.test.ts @@ -1,8 +1,16 @@ +import { readFileSync } from "node:fs" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" import { describe, expect, it, vi } from "vitest" import { DaemonState } from "../state.js" import { parseProviderEntries, Watcher } from "../watcher.js" import { WorkspaceJobs } from "../workspace-jobs.js" +const fixtureDir = join( + dirname(fileURLToPath(import.meta.url)), + "../../../test-fixtures/provider-icons", +) + function makeWatcher( runProviderList: () => Promise>, workspaces: Array<{ id: string; status?: string }> = [], @@ -66,6 +74,33 @@ describe("parseProviderEntries", () => { expect(legacy).toMatchObject({ name: "legacy-provider", deprecated: false }) expect(external).toMatchObject({ name: "microsandbox", deprecated: false }) }) + + it("carries provider-owned icon fields from the CLI list JSON to renderer fields", () => { + const raw = JSON.parse( + readFileSync(join(fixtureDir, "provider-list.json"), "utf8"), + ) + + const [provider] = parseProviderEntries(raw) + + expect(provider).toMatchObject({ + name: "my-docker-fleet", + icon: "assets/light.svg", + iconDark: "assets/dark.svg", + iconRevision: "rev-a", + }) + }) + + it("defaults icon fields to empty strings for providers without icons", () => { + const [provider] = parseProviderEntries({ + plain: { config: { name: "plain" } }, + }) + + expect(provider).toMatchObject({ + icon: "", + iconDark: "", + iconRevision: "", + }) + }) }) describe("Watcher.refreshProviders", () => { diff --git a/desktop/src/main/cli.ts b/desktop/src/main/cli.ts index 9cc8433c8b..f936523098 100644 --- a/desktop/src/main/cli.ts +++ b/desktop/src/main/cli.ts @@ -49,6 +49,8 @@ export interface CliInvocationOptions { allowUnlockPrompt?: boolean /** Internal retry guard: never repeatedly prompt for one invocation. */ unlockRetried?: boolean + /** Raises the stdout cap of run() above Node's 1 MiB default. */ + maxBuffer?: number } export interface CliInvocationPolicy { @@ -367,6 +369,9 @@ export class CliRunner { ? ( await execFile(this.execPath, fullArgs, { env: this.invocationEnv(args, options), + ...(options.maxBuffer === undefined + ? {} + : { maxBuffer: options.maxBuffer }), }) ).stdout : await this.spawnWithStdin( diff --git a/desktop/src/main/ipc.ts b/desktop/src/main/ipc.ts index 0f41d0f617..3424114559 100644 --- a/desktop/src/main/ipc.ts +++ b/desktop/src/main/ipc.ts @@ -13,6 +13,7 @@ import { normalizeOperationStatus, parseCliEnvelope, } from "../shared/cli-error.js" +import type { ProviderIconRequest } from "../shared/provider-icon.js" import type { WorkspaceActivity } from "../shared/workspace-operation.js" import { hashWorkspaceRef, trackEvent } from "./analytics.js" import type { AppNavigationController } from "./app-navigation.js" @@ -23,6 +24,7 @@ import type { LogStore } from "./log-store.js" import { mainLog } from "./logging.js" import type { MachineDiagnosticsManager } from "./machine-diagnostics-manager.js" import type { MachineDiagnosticsStore } from "./machine-diagnostics-store.js" +import { ProviderIconReader } from "./provider-icons.js" import type { ProviderActivity, ProviderJobs } from "./provider-jobs.js" import type { PtyManager } from "./pty.js" import { sendRendererEvent } from "./renderer-events.js" @@ -366,6 +368,9 @@ export function registerIpcHandlers(deps: IpcDependencies): { getMainWindow, } = deps const secretSession = new SecretSession(deps.secretSessionTimeoutMs) + const providerIcons = new ProviderIconReader(cli) + let providerIconContextRevision = -1 + const providerIconIdentityRevisions = new Map() // Clearing the session revokes cache updates from protection operations already in flight. let secretCacheGeneration = 0 const requestSecretUnlock = async () => { @@ -985,6 +990,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { try { result = await fn() } catch (error) { + providerIcons.invalidateProvider(name) const cliError = (error as { cliError?: CLIError }).cliError ? redactCLIError((error as { cliError: CLIError }).cliError) : undefined @@ -998,6 +1004,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { ) throw error } + providerIcons.invalidateProvider(name) await providerJobs.finish(name) return result } @@ -1167,6 +1174,57 @@ export function registerIpcHandlers(deps: IpcDependencies): { return state.providerList() }) + // Installed-asset reader only: the renderer names a provider and theme, never + // a URL or path. Same top-level-document sender policy as secret IPC. + ipcMain.handle("provider_icon", async (event, args: ProviderIconRequest) => { + if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) + throw new Error("Provider icons require the main application window.") + const context = args?.context || state.currentContext() + const contextRevision = state.providerIconContextReadRevision() + if (contextRevision !== providerIconContextRevision) { + providerIcons.invalidateAll() + providerIconContextRevision = contextRevision + } + const providerName = args.providerName + const identityKey = `${context}\0${providerName}` + const identityRevision = state.providerIconIdentityReadRevision( + context, + providerName, + ) + const previousIdentityRevision = + providerIconIdentityRevisions.get(identityKey) + if ( + previousIdentityRevision !== undefined && + previousIdentityRevision !== identityRevision + ) + providerIcons.invalidateProvider(providerName) + providerIconIdentityRevisions.set(identityKey, identityRevision) + + const result = await providerIcons.read({ ...args, context }) + const currentContextRevision = state.providerIconContextReadRevision() + if (currentContextRevision !== contextRevision) { + providerIcons.invalidateAll() + providerIconContextRevision = currentContextRevision + return { revision: "", stale: true } + } + + const currentIdentityRevision = state.providerIconIdentityReadRevision( + context, + providerName, + ) + if (currentIdentityRevision !== identityRevision) { + providerIcons.invalidateProvider(providerName) + const current = + context === state.currentContext() + ? state + .providerList() + .find((provider) => provider.name === providerName) + : undefined + return { revision: current?.iconRevision ?? "", stale: true } + } + return result + }) + ipcMain.handle( "provider_add", async ( @@ -1201,6 +1259,8 @@ export function registerIpcHandlers(deps: IpcDependencies): { ), ) throw error + } finally { + providerIcons.invalidateProvider(args.name) } }, ) @@ -1208,6 +1268,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { ipcMain.handle("provider_delete", async (_event, args: { name: string }) => { trackEvent("provider_delete") await cli.runRaw(["provider", "delete", args.name]) + providerIcons.invalidateProvider(args.name) // Drop any retained failure so a re-added provider starts clean. providerJobs.clear(args.name) }) @@ -1404,6 +1465,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { message: errorMessage(error), } } + providerIcons.invalidateProvider(args.name) try { await providerJobs.finish( args.name, @@ -1509,6 +1571,8 @@ export function registerIpcHandlers(deps: IpcDependencies): { "provider_rename", async (_event, args: { name: string; newName: string }) => { await cli.runRaw(["provider", "rename", args.name, args.newName]) + providerIcons.invalidateProvider(args.name) + providerIcons.invalidateProvider(args.newName) }, ) @@ -1673,6 +1737,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { ipcMain.handle("context_use", async (_event, args: { name: string }) => { await cli.runRaw(["context", "use", args.name]) + providerIcons.invalidateAll() }) ipcMain.handle( @@ -1710,6 +1775,7 @@ export function registerIpcHandlers(deps: IpcDependencies): { if (!isTrustedSecretIpcSender(event, getMainWindow(), secretDocumentURL)) return secretRequestDenied await cli.runRaw(["context", "delete", args.name]) + providerIcons.invalidateAll() }) function variableContextArgs(context: string | undefined): string[] { diff --git a/desktop/src/main/provider-icons.ts b/desktop/src/main/provider-icons.ts new file mode 100644 index 0000000000..7a792cbb6a --- /dev/null +++ b/desktop/src/main/provider-icons.ts @@ -0,0 +1,255 @@ +import { + PROVIDER_ICON_MAX_BYTES, + PROVIDER_ICON_MIME_TYPES, + type ProviderIconReply, + type ProviderIconRequest, + type ProviderIconTheme, +} from "../shared/provider-icon.js" +import type { CliRunner } from "./cli.js" + +// Base64 of the 1 MiB image cap plus the JSON envelope must fit in stdout. +const CLI_MAX_STDOUT_BYTES = 2 * 1024 * 1024 +const MAX_BASE64_LENGTH = Math.ceil(PROVIDER_ICON_MAX_BYTES / 3) * 4 +const MAX_CACHE_ENTRIES = 128 +const MAX_CONTEXT_PATH_BYTES = 255 +const INVALID_CONTEXT_PATH_CHARACTERS = /[\\/:<>"|?*]/u +const BASE64_PATTERN = + /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/ + +interface CliProviderIconResult { + revision?: unknown + mimeType?: unknown + dataBase64?: unknown + missing?: unknown +} + +type ObservedIcon = + | { revision: string; dataUrl: string } + | { revision: string; missing: true } + +function requireIdentifier(value: unknown, label: string): string { + // A leading dash would be parsed as a CLI flag. + if ( + typeof value !== "string" || + value.trim() === "" || + value.startsWith("-") || + value.includes("\0") + ) + throw new Error(`A valid ${label} is required.`) + return value +} + +function requireContext(value: unknown): string { + if ( + typeof value !== "string" || + value.trim() === "" || + hasContextControlCharacter(value) || + value.startsWith("-") || + value === "." || + value === ".." || + value.endsWith(".") || + value.endsWith(" ") || + Buffer.byteLength(value, "utf8") > MAX_CONTEXT_PATH_BYTES || + INVALID_CONTEXT_PATH_CHARACTERS.test(value) || + (process.platform === "win32" && isReservedWindowsContextName(value)) + ) + throw new Error("A valid context is required.") + return value +} + +function hasContextControlCharacter(value: string): boolean { + for (let index = 0; index < value.length; index++) { + const code = value.charCodeAt(index) + if (code < 0x20 || code === 0x7f) return true + } + return false +} + +function isReservedWindowsContextName(value: string): boolean { + const basename = value.split(".", 1)[0].toUpperCase() + return /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/.test(basename) +} + +function requireTheme(value: unknown): ProviderIconTheme { + if (value !== "light" && value !== "dark") + throw new Error("Icon theme must be light or dark.") + return value +} + +/** Re-checks type and size of the CLI payload and builds the internal data URL. */ +export function toObservedIcon(raw: unknown): ObservedIcon { + if (!raw || typeof raw !== "object") + throw new Error("Provider icon result is not an object.") + const result = raw as CliProviderIconResult + const revision = typeof result.revision === "string" ? result.revision : "" + if (result.missing === true) return { revision, missing: true } + + const mimeType = result.mimeType + if ( + typeof mimeType !== "string" || + !(PROVIDER_ICON_MIME_TYPES as readonly string[]).includes(mimeType) + ) + throw new Error("Provider icon has an unsupported image type.") + + const data = result.dataBase64 + if ( + typeof data !== "string" || + data.length === 0 || + data.length > MAX_BASE64_LENGTH || + data.length % 4 !== 0 || + !BASE64_PATTERN.test(data) + ) + throw new Error("Provider icon data is invalid or too large.") + if (Buffer.from(data, "base64").length > PROVIDER_ICON_MAX_BYTES) + throw new Error("Provider icon data is too large.") + + return { revision, dataUrl: `data:${mimeType};base64,${data}` } +} + +/** + * Reads installed provider icons through the CLI. Results are cached by + * context, provider, revision and theme; concurrent identical reads share one + * CLI invocation. The cache only ever holds bytes the CLI reported for the + * revision in the key, so a stale caller can never receive another revision's + * image. + */ +export class ProviderIconReader { + private cache = new Map() + private inFlight = new Map>() + private providerEpochs = new Map() + private epoch = 0 + + constructor(private cli: Pick) {} + + async read(request: ProviderIconRequest): Promise { + const providerName = requireIdentifier(request?.providerName, "provider") + if (!/^[a-z0-9-]{1,32}$/.test(providerName)) + throw new Error("A valid provider is required.") + const context = requireContext(request.context) + const theme = requireTheme(request.theme) + const expectedRevision = + typeof request.expectedRevision === "string" + ? request.expectedRevision + : "" + if (expectedRevision.includes("\0")) + throw new Error("A valid icon revision is required.") + + const scope = `${context}\0${providerName}` + const epoch = this.epoch + const providerEpoch = this.providerEpochs.get(scope) ?? 0 + const requestKey = cacheKey(context, providerName, expectedRevision, theme) + const cached = expectedRevision ? this.touch(requestKey) : undefined + const observed = cached ?? (await this.load(requestKey, request)) + if ( + epoch !== this.epoch || + providerEpoch !== (this.providerEpochs.get(scope) ?? 0) || + observed.revision !== expectedRevision + ) + return { revision: observed.revision, stale: true } + return observed + } + + invalidateProvider(providerName: string): void { + const marker = `\0${providerName}\0` + const keys = [...this.cache.keys(), ...this.inFlight.keys()].filter((key) => + key.includes(marker), + ) + for (const key of keys) { + const [context, name] = key.split("\0") + const scope = `${context}\0${name}` + this.providerEpochs.set(scope, (this.providerEpochs.get(scope) ?? 0) + 1) + this.cache.delete(key) + this.inFlight.delete(key) + } + } + + invalidateAll(): void { + this.epoch++ + this.inFlight.clear() + this.cache.clear() + this.providerEpochs.clear() + } + + private touch(key: string): ObservedIcon | undefined { + const hit = this.cache.get(key) + if (hit) { + this.cache.delete(key) + this.cache.set(key, hit) + } + return hit + } + + private load( + requestKey: string, + request: ProviderIconRequest, + ): Promise { + const pending = this.inFlight.get(requestKey) + if (pending) return pending + + const scope = `${request.context}\0${request.providerName}` + const epoch = this.epoch + const providerEpoch = this.providerEpochs.get(scope) ?? 0 + const run = this.fetch(request).then((observed) => { + if ( + epoch === this.epoch && + providerEpoch === (this.providerEpochs.get(scope) ?? 0) && + observed.revision + ) { + this.store( + cacheKey( + request.context, + request.providerName, + observed.revision, + request.theme, + ), + observed, + ) + } + return observed + }) + this.inFlight.set(requestKey, run) + const release = () => { + if (this.inFlight.get(requestKey) === run) + this.inFlight.delete(requestKey) + } + run.then(release, release) + return run + } + + private async fetch(request: ProviderIconRequest): Promise { + const raw = await this.cli.run( + [ + "provider", + "icon", + request.providerName, + "--theme", + request.theme, + "--context", + request.context, + "--result-format", + "json", + ], + { maxBuffer: CLI_MAX_STDOUT_BYTES }, + ) + return toObservedIcon(raw) + } + + private store(key: string, value: ObservedIcon): void { + this.cache.delete(key) + this.cache.set(key, value) + while (this.cache.size > MAX_CACHE_ENTRIES) { + const oldest = this.cache.keys().next().value + if (oldest === undefined) break + this.cache.delete(oldest) + } + } +} + +function cacheKey( + context: string, + providerName: string, + revision: string, + theme: ProviderIconTheme, +): string { + return `${context}\0${providerName}\0${revision}\0${theme}` +} diff --git a/desktop/src/main/state.ts b/desktop/src/main/state.ts index 8880eedbc2..bcc3856f39 100644 --- a/desktop/src/main/state.ts +++ b/desktop/src/main/state.ts @@ -9,6 +9,9 @@ export interface Workspace { export interface Provider { name: string + icon?: string + iconDark?: string + iconRevision?: string state?: { singleMachine?: boolean; [key: string]: unknown } [key: string]: unknown } @@ -27,6 +30,8 @@ export class DaemonState { private workspaces = new Map() private providers = new Map() private providerWriteRevision = 0 + private providerIconIdentityRevisions = new Map() + private providerIconContextRevision = 0 private machines = new Map() private contexts: Context[] = [] private activeContext = "" @@ -68,13 +73,46 @@ export class DaemonState { return this.providerWriteRevision } + providerIconContextReadRevision(): number { + return this.providerIconContextRevision + } + + providerIconIdentityReadRevision( + context: string, + providerName: string, + ): number { + return ( + this.providerIconIdentityRevisions.get(`${context}\0${providerName}`) ?? 0 + ) + } + updateProviders( list: Provider[], readRevision = this.providerWriteRevision, ): boolean { if (readRevision < this.providerWriteRevision) return false - const newMap = new Map(list.map((p) => [p.name, p])) + const newMap = new Map(list.map((provider) => [provider.name, provider])) if (this.mapsEqual(this.providers, newMap)) return false + + const context = this.currentContext() + const names = new Set([...this.providers.keys(), ...newMap.keys()]) + for (const name of names) { + const previous = this.providers.get(name) + const next = newMap.get(name) + if ( + !previous || + !next || + previous.icon !== next.icon || + previous.iconDark !== next.iconDark || + previous.iconRevision !== next.iconRevision + ) { + const key = `${context}\0${name}` + this.providerIconIdentityRevisions.set( + key, + (this.providerIconIdentityRevisions.get(key) ?? 0) + 1, + ) + } + } this.providers = newMap return true } @@ -105,6 +143,9 @@ export class DaemonState { const currentJson = JSON.stringify(this.contexts) if (contextsJson === currentJson && active === this.activeContext) return false + if (active !== this.activeContext) { + this.providerIconContextRevision++ + } this.contexts = contexts this.activeContext = active return true diff --git a/desktop/src/main/watcher.ts b/desktop/src/main/watcher.ts index 9fe4af6f7a..1eb63ac8cd 100644 --- a/desktop/src/main/watcher.ts +++ b/desktop/src/main/watcher.ts @@ -31,6 +31,8 @@ export interface ProviderEntry { name?: string version?: string icon?: string + iconDark?: string + iconRevision?: string description?: string source?: Record options?: Record @@ -47,6 +49,8 @@ export function parseProviderEntries(raw: Record) { name: entry.config.name ?? "", version: entry.config.version ?? "", icon: entry.config.icon ?? "", + iconDark: entry.config.iconDark ?? "", + iconRevision: entry.config.iconRevision ?? "", description: entry.config.description ?? "", source: entry.config.source ?? {}, options: entry.config.options ?? {}, diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderCard.svelte b/desktop/src/renderer/src/lib/components/provider/ProviderCard.svelte index b328ee7035..e052800b92 100644 --- a/desktop/src/renderer/src/lib/components/provider/ProviderCard.svelte +++ b/desktop/src/renderer/src/lib/components/provider/ProviderCard.svelte @@ -25,7 +25,13 @@ let status = $derived(providerStatus(provider, $providerJobs[provider.name])) {/if}
- +

{provider.name}

{#if provider.isDefault} diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderCard.test.ts b/desktop/src/renderer/src/lib/components/provider/ProviderCard.test.ts index 9838fbcd90..8bbcbef089 100644 --- a/desktop/src/renderer/src/lib/components/provider/ProviderCard.test.ts +++ b/desktop/src/renderer/src/lib/components/provider/ProviderCard.test.ts @@ -1,5 +1,6 @@ -import { render } from "@testing-library/svelte" +import { render, waitFor } from "@testing-library/svelte" import { describe, expect, it, vi } from "vitest" +import type * as Commands from "$lib/ipc/commands.js" import type { Provider } from "$lib/types/index.js" vi.mock("$lib/stores/providerVersions.js", async () => { @@ -13,6 +14,13 @@ vi.mock("$lib/stores/providerVersions.js", async () => { } }) +const { providerIcon } = vi.hoisted(() => ({ providerIcon: vi.fn() })) + +vi.mock("$lib/ipc/commands.js", async (importOriginal) => ({ + ...(await importOriginal()), + providerIcon, +})) + import { providerJobs } from "$lib/stores/providers.js" import ProviderCard from "./ProviderCard.svelte" @@ -151,4 +159,22 @@ describe("ProviderCard", () => { ) unmount() }) + + it("renders the provider's own icon from the installed icon metadata", async () => { + const dataUrl = "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=" + providerIcon.mockResolvedValue({ revision: "rev-a", dataUrl }) + const { container, unmount } = render(ProviderCard, { + props: { + provider: makeProvider("my-docker-fleet", { + icon: "assets/logo.svg", + iconRevision: "rev-a", + }), + }, + }) + + await waitFor(() => + expect(container.querySelector("img")?.getAttribute("src")).toBe(dataUrl), + ) + unmount() + }) }) diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderIcon.svelte b/desktop/src/renderer/src/lib/components/provider/ProviderIcon.svelte index bcdf29c971..7931facbb4 100644 --- a/desktop/src/renderer/src/lib/components/provider/ProviderIcon.svelte +++ b/desktop/src/renderer/src/lib/components/provider/ProviderIcon.svelte @@ -1,6 +1,24 @@ -{name} icon +{name} icon diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderIcon.test.ts b/desktop/src/renderer/src/lib/components/provider/ProviderIcon.test.ts new file mode 100644 index 0000000000..1b85876558 --- /dev/null +++ b/desktop/src/renderer/src/lib/components/provider/ProviderIcon.test.ts @@ -0,0 +1,610 @@ +import { cleanup, fireEvent, render, waitFor } from "@testing-library/svelte" +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" +import { activeContext } from "$lib/stores/contexts.js" +import { effectiveTheme } from "$lib/stores/settings.js" +import { clearProviderIconLoader } from "$lib/utils/provider-icon-loader.js" +import type { ProviderIconReply } from "$shared/provider-icon.js" +import darkSVG from "../../../../../../test-fixtures/provider-icons/assets/dark.svg?raw" +import lightSVG from "../../../../../../test-fixtures/provider-icons/assets/light.svg?raw" + +const { providerIcon } = vi.hoisted(() => ({ providerIcon: vi.fn() })) + +vi.mock("$lib/ipc/commands.js", () => ({ providerIcon })) + +import ProviderIcon from "./ProviderIcon.svelte" + +const LIGHT = `data:image/svg+xml;base64,${btoa(lightSVG)}` +const DARK = `data:image/svg+xml;base64,${btoa(darkSVG)}` +const PLACEHOLDER = "./icons/providers/provider_placeholder.svg" +const DOCKER = "./icons/providers/docker.svg" +const LIMA = "./icons/providers/lima.svg" + +/** Answers provider_icon requests per theme; a variant not listed is missing. */ +function serveIcons( + revision: string, + images: Partial>, +) { + providerIcon.mockImplementation( + async ({ + theme, + }: { + theme: "light" | "dark" + }): Promise => { + const image = images[theme] + if (image instanceof Error) throw image + if (image === undefined) return { revision, missing: true } + return { revision, dataUrl: image } + }, + ) +} + +function image(container: HTMLElement): HTMLImageElement { + const img = container.querySelector("img") + if (!img) throw new Error("no rendered") + return img +} + +const custom = { + name: "harvester", + icon: "assets/light.svg", + iconDark: "assets/dark.svg", + iconRevision: "rev-a", +} + +describe("ProviderIcon", () => { + beforeEach(() => { + providerIcon.mockReset() + clearProviderIconLoader() + activeContext.set("work") + effectiveTheme.set("light") + }) + + afterEach(() => { + cleanup() + }) + + describe("without provider-owned icons", () => { + it("keeps the bundled mapping for name-only catalog entries", () => { + const { container } = render(ProviderIcon, { props: { name: "docker" } }) + + expect(image(container).getAttribute("src")).toBe(DOCKER) + expect(providerIcon).not.toHaveBeenCalled() + }) + + it("uses the placeholder for unknown names", () => { + const { container } = render(ProviderIcon, { + props: { name: "something-else" }, + }) + + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + }) + + it("does not request an image when the provider has no icon revision", () => { + const { container } = render(ProviderIcon, { + props: { + name: "harvester", + icon: "assets/light.svg", + iconDark: "assets/dark.svg", + }, + }) + + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + expect(providerIcon).not.toHaveBeenCalled() + }) + }) + + describe("light theme", () => { + it("shows the custom light image and asks only for the light variant", async () => { + serveIcons("rev-a", { light: LIGHT, dark: DARK }) + const { container } = render(ProviderIcon, { props: custom }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + expect(providerIcon).toHaveBeenCalledTimes(1) + expect(providerIcon).toHaveBeenCalledWith({ + providerName: "harvester", + context: "work", + theme: "light", + expectedRevision: "rev-a", + }) + }) + + it("never shows the dark image, falling back to the bundled mapping", async () => { + serveIcons("rev-a", { dark: DARK }) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "docker-cloud" }, + }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DOCKER), + ) + }) + }) + + describe("dark theme", () => { + beforeEach(() => effectiveTheme.set("dark")) + + it("prefers the custom dark image", async () => { + serveIcons("rev-a", { light: LIGHT, dark: DARK }) + const { container } = render(ProviderIcon, { props: custom }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + }) + + it("falls back to the custom light image when the dark variant is missing", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container } = render(ProviderIcon, { props: custom }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("uses the light image when the manifest declares no dark icon", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container } = render(ProviderIcon, { + props: { ...custom, iconDark: "" }, + }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + expect(providerIcon).toHaveBeenCalledTimes(1) + }) + + it("falls back to the bundled mapping and then the placeholder when both variants are unusable", async () => { + serveIcons("rev-a", { light: new Error("disk"), dark: new Error("disk") }) + const mapped = render(ProviderIcon, { + props: { ...custom, name: "my-docker-fleet" }, + }) + await waitFor(() => + expect(image(mapped.container).getAttribute("src")).toBe(DOCKER), + ) + mapped.unmount() + + const unmapped = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(unmapped.container).getAttribute("src")).toBe(PLACEHOLDER), + ) + }) + }) + + describe("custom registration names", () => { + it("shows the bundled fallback while loading, then lets the custom image win", async () => { + const pending = Promise.withResolvers() + providerIcon.mockImplementation(() => pending.promise) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "my-docker-fleet" }, + }) + + expect(image(container).getAttribute("src")).toBe(DOCKER) + pending.resolve({ revision: "rev-a", dataUrl: LIGHT }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("still falls back to the substring match when the custom image is missing", async () => { + serveIcons("rev-a", {}) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "my-docker-fleet" }, + }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DOCKER), + ) + }) + }) + + describe("live updates", () => { + it("switches between light and dark images when the effective theme changes", async () => { + serveIcons("rev-a", { light: LIGHT, dark: DARK }) + const { container } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + + effectiveTheme.set("dark") + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + + effectiveTheme.set("light") + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("does not show a previous revision's image while the new revision loads", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container, rerender } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + + const next = Promise.withResolvers() + providerIcon.mockImplementation(() => next.promise) + await rerender({ ...custom, iconRevision: "rev-b" }) + + expect(image(container).getAttribute("src")).not.toBe(LIGHT) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + + next.resolve({ revision: "rev-b", dataUrl: DARK }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + }) + + it("drops a delayed response that arrives after the provider was renamed", async () => { + const first = Promise.withResolvers() + providerIcon.mockImplementationOnce(() => first.promise) + const { container, rerender } = render(ProviderIcon, { props: custom }) + + serveIcons("rev-a", { light: DARK }) + await rerender({ ...custom, name: "renamed" }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + + first.resolve({ revision: "rev-a", dataUrl: LIGHT }) + await first.promise + await Promise.resolve() + + expect(image(container).getAttribute("src")).toBe(DARK) + }) + + it("bounds repeated stale replies and leaves unavailable lookups uncached", async () => { + let requests = 0 + providerIcon.mockImplementation(() => { + requests += 1 + if (requests <= 2) { + return Promise.resolve({ revision: "rev-b", stale: true }) + } + return Promise.resolve({ revision: "rev-a", dataUrl: LIGHT }) + }) + const unavailable = render(ProviderIcon, { props: custom }) + + await waitFor(() => expect(requests).toBe(2)) + expect(image(unavailable.container).getAttribute("src")).toBe(PLACEHOLDER) + unavailable.unmount() + + const recovered = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(recovered.container).getAttribute("src")).toBe(LIGHT), + ) + expect(requests).toBe(3) + }) + + it("re-requests images after the active context changes", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + + activeContext.set("other") + await waitFor(() => expect(providerIcon).toHaveBeenCalledTimes(2)) + expect(providerIcon).toHaveBeenLastCalledWith( + expect.objectContaining({ context: "other" }), + ) + }) + + it("recovers an icon after an A-B-A switch during a pending read", async () => { + const firstA = Promise.withResolvers() + const freshA = Promise.withResolvers() + const freshAStarted = Promise.withResolvers() + let contextACalls = 0 + providerIcon.mockImplementation( + ({ context }: { context: string }): Promise => { + if (context === "work") { + contextACalls += 1 + if (contextACalls === 1) return firstA.promise + freshAStarted.resolve() + return freshA.promise + } + return Promise.resolve({ revision: "rev-a", dataUrl: DARK }) + }, + ) + const { container } = render(ProviderIcon, { props: custom }) + + activeContext.set("other") + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + + const paintedSources: string[] = [] + const observer = new MutationObserver((records) => { + for (const record of records) { + if (record.attributeName === "src") { + paintedSources.push( + (record.target as HTMLImageElement).getAttribute("src") ?? "", + ) + } + } + }) + observer.observe(container, { + attributes: true, + subtree: true, + attributeFilter: ["src"], + }) + + activeContext.set("work") + firstA.resolve({ revision: "rev-a", dataUrl: DARK, stale: true }) + + await freshAStarted.promise + await firstA.promise + await Promise.resolve() + await Promise.resolve() + expect(paintedSources).not.toContain(DARK) + observer.disconnect() + + freshA.resolve({ revision: "rev-a", dataUrl: LIGHT }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("reloads the icon after a pending provider is deleted and re-added", async () => { + const revokedRequest = Promise.withResolvers() + const firstRequestStarted = Promise.withResolvers() + let requests = 0 + providerIcon.mockImplementation(() => { + requests += 1 + if (requests === 1) { + firstRequestStarted.resolve() + return revokedRequest.promise + } + return Promise.resolve({ revision: "rev-a", dataUrl: LIGHT }) + }) + const removed = render(ProviderIcon, { props: custom }) + await firstRequestStarted.promise + removed.unmount() + const current = render(ProviderIcon, { props: custom }) + const paintedSources: string[] = [] + const observer = new MutationObserver((records) => { + for (const record of records) { + if (record.attributeName === "src") { + paintedSources.push( + (record.target as HTMLImageElement).getAttribute("src") ?? "", + ) + } + } + }) + observer.observe(current.container, { + attributes: true, + subtree: true, + attributeFilter: ["src"], + }) + + revokedRequest.resolve({ + revision: "rev-a", + dataUrl: DARK, + stale: true, + }) + await waitFor(() => + expect(image(current.container).getAttribute("src")).toBe(LIGHT), + ) + await Promise.resolve() + await Promise.resolve() + expect(paintedSources).not.toContain(DARK) + observer.disconnect() + }) + + it("recovers a remounted icon after other lookups evict its pending result", async () => { + const revokedRequest = Promise.withResolvers() + const firstRequestStarted = Promise.withResolvers() + let originalRequests = 0 + providerIcon.mockImplementation( + ({ providerName }: { providerName: string }) => { + if (providerName === custom.name) { + originalRequests += 1 + if (originalRequests === 1) { + firstRequestStarted.resolve() + return revokedRequest.promise + } + } + return Promise.resolve({ revision: "rev-a", dataUrl: LIGHT }) + }, + ) + const removed = render(ProviderIcon, { props: custom }) + await firstRequestStarted.promise + removed.unmount() + const current = render(ProviderIcon, { props: custom }) + const paintedSources: string[] = [] + const observer = new MutationObserver((records) => { + for (const record of records) { + if (record.attributeName === "src") { + paintedSources.push( + (record.target as HTMLImageElement).getAttribute("src") ?? "", + ) + } + } + }) + observer.observe(current.container, { + attributes: true, + subtree: true, + attributeFilter: ["src"], + }) + + const otherIcons = Array.from({ length: 64 }, (_, index) => + render(ProviderIcon, { + props: { ...custom, name: `other-${index}` }, + }), + ) + await waitFor(() => { + for (const other of otherIcons) { + expect(image(other.container).getAttribute("src")).toBe(LIGHT) + } + }) + + revokedRequest.resolve({ + revision: "rev-a", + dataUrl: DARK, + stale: true, + }) + await waitFor(() => + expect(image(current.container).getAttribute("src")).toBe(LIGHT), + ) + await Promise.resolve() + await Promise.resolve() + expect(paintedSources).not.toContain(DARK) + observer.disconnect() + }) + + it("shares a pending lookup across cards without leaking another revision", async () => { + const pending = Promise.withResolvers() + providerIcon.mockImplementation(() => pending.promise) + const first = render(ProviderIcon, { props: custom }) + const second = render(ProviderIcon, { props: custom }) + expect(providerIcon).toHaveBeenCalledTimes(1) + + serveIcons("rev-b", { light: DARK }) + const replacement = render(ProviderIcon, { + props: { ...custom, iconRevision: "rev-b" }, + }) + await waitFor(() => + expect(image(replacement.container).getAttribute("src")).toBe(DARK), + ) + + pending.resolve({ revision: "rev-a", dataUrl: LIGHT }) + await waitFor(() => { + expect(image(first.container).getAttribute("src")).toBe(LIGHT) + expect(image(second.container).getAttribute("src")).toBe(LIGHT) + expect(image(replacement.container).getAttribute("src")).toBe(DARK) + }) + }) + }) + + describe("failed images", () => { + it("advances one candidate per failure and never requests a broken source again", async () => { + effectiveTheme.set("dark") + serveIcons("rev-a", { light: LIGHT, dark: DARK }) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "my-docker-fleet" }, + }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + const requests = providerIcon.mock.calls.length + + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(LIGHT) + + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(DOCKER) + + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + + // Errors on the placeholder are terminal: no loop, no new request. + await fireEvent.error(image(container)) + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + expect(providerIcon).toHaveBeenCalledTimes(requests) + }) + + it("advances a broken bundled fallback while the custom request is pending", async () => { + const pending = Promise.withResolvers() + providerIcon.mockImplementation(() => pending.promise) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "my-docker-fleet" }, + }) + expect(image(container).getAttribute("src")).toBe(DOCKER) + + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + + pending.resolve({ revision: "rev-a", dataUrl: LIGHT }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("resets failure state when the revision changes", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container, rerender } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + + serveIcons("rev-b", { light: LIGHT }) + await rerender({ ...custom, iconRevision: "rev-b" }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + }) + + it("resets failure state when the effective theme changes", async () => { + serveIcons("rev-a", { light: LIGHT, dark: DARK }) + const { container } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + await fireEvent.error(image(container)) + expect(image(container).getAttribute("src")).toBe(PLACEHOLDER) + + effectiveTheme.set("dark") + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + }) + }) + + describe("Lima inversion", () => { + it("inverts the bundled Lima logo", () => { + const { container } = render(ProviderIcon, { props: { name: "lima" } }) + + expect(image(container).getAttribute("src")).toBe(LIMA) + expect(image(container).classList.contains("dark:invert")).toBe(true) + }) + + it("never inverts a supplied custom image, even for a Lima-named provider", async () => { + effectiveTheme.set("dark") + serveIcons("rev-a", { dark: DARK }) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "lima-fleet" }, + }) + + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(DARK), + ) + expect(image(container).classList.contains("dark:invert")).toBe(false) + }) + + it("inverts again once the custom image fails and the bundled Lima logo is selected", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container } = render(ProviderIcon, { + props: { ...custom, name: "lima-fleet" }, + }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + + await fireEvent.error(image(container)) + + expect(image(container).getAttribute("src")).toBe(LIMA) + expect(image(container).classList.contains("dark:invert")).toBe(true) + }) + }) + + it("renders only an with alt text for downloaded content", async () => { + serveIcons("rev-a", { light: LIGHT }) + const { container } = render(ProviderIcon, { props: custom }) + await waitFor(() => + expect(image(container).getAttribute("src")).toBe(LIGHT), + ) + + expect(image(container).getAttribute("alt")).toBe("harvester icon") + expect(container.querySelector("object, embed, iframe, svg")).toBeNull() + }) +}) diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderWizard.svelte b/desktop/src/renderer/src/lib/components/provider/ProviderWizard.svelte index 87bedfb2d2..66e25c9254 100644 --- a/desktop/src/renderer/src/lib/components/provider/ProviderWizard.svelte +++ b/desktop/src/renderer/src/lib/components/provider/ProviderWizard.svelte @@ -137,6 +137,11 @@ let availableProvidersError = $state("") // Step 2 state let providerName = $state("") +// Undefined until the provider's manifest is installed, so setup shows the +// bundled fallback first and the provider's own icon afterwards. +let installedProvider = $derived( + $providers.find((p) => p.name === providerName), +) let options = $state>({}) let optionValues = $state>({}) let editedOptionKeys = $state>({}) @@ -758,19 +763,28 @@ function handleDone() { {:else if currentStep === "initialize"}
-
-

Initializing {providerName}

-

- {#if initRunning} - Running provider initialization... - {:else if initError} - Initialization encountered an issue. - {:else if initSucceeded} - Initialization complete. - {:else} - Initialization has not completed. - {/if} -

+
+ +
+

Initializing {providerName}

+

+ {#if initRunning} + Running provider initialization... + {:else if initError} + Initialization encountered an issue. + {:else if initSucceeded} + Initialization complete. + {:else} + Initialization has not completed. + {/if} +

+
{#if initStartError} @@ -824,11 +838,17 @@ function handleDone() {
- +
{providerName}
- {get(providers).find((p) => p.name === providerName)?.state?.initialized + {installedProvider?.state?.initialized ? "Initialized" : "Not initialized"}
diff --git a/desktop/src/renderer/src/lib/components/provider/ProviderWizard.test.ts b/desktop/src/renderer/src/lib/components/provider/ProviderWizard.test.ts index 2ee7f5b5c3..0e4df23e95 100644 --- a/desktop/src/renderer/src/lib/components/provider/ProviderWizard.test.ts +++ b/desktop/src/renderer/src/lib/components/provider/ProviderWizard.test.ts @@ -15,6 +15,7 @@ const { providerAvailable, providerInitStreaming, providerList, + providerIcon, providerOptions, providerReleaseJob, providerSetOptions, @@ -24,6 +25,7 @@ const { providerAvailable: vi.fn(), providerInitStreaming: vi.fn(), providerList: vi.fn(), + providerIcon: vi.fn(), providerOptions: vi.fn(), providerReleaseJob: vi.fn(), providerSetOptions: vi.fn(), @@ -35,6 +37,7 @@ vi.mock("$lib/ipc/commands.js", () => ({ providerAvailable, providerInitStreaming, providerList, + providerIcon, providerOptions, providerReleaseJob, providerSetOptions, @@ -416,6 +419,54 @@ describe("ProviderWizard", () => { page.unmount() }) + it("shows the bundled fallback until the manifest is installed, then the provider's own icon", async () => { + const dataUrl = "data:image/svg+xml;base64,PHN2Zz48L3N2Zz4=" + providerInitStreaming.mockRejectedValueOnce(new Error("worker unavailable")) + providerIcon.mockResolvedValue({ revision: "rev-a", dataUrl }) + const page = renderWizard() + await fireEvent.click( + screen.getByRole("button", { name: /docker Local Docker/ }), + ) + await fireEvent.click(screen.getByRole("button", { name: "Continue" })) + await screen.findByText(/Failed to start initialization/) + + expect(screen.getByAltText("docker icon").getAttribute("src")).toBe( + "./icons/providers/docker.svg", + ) + expect(providerIcon).not.toHaveBeenCalled() + + const installed = { + ...makeProvider("docker"), + icon: "assets/logo.svg", + iconRevision: "rev-a", + } + providerList.mockResolvedValue([installed]) + providers.set([installed]) + + await waitFor(() => + expect(screen.getByAltText("docker icon").getAttribute("src")).toBe( + dataUrl, + ), + ) + expect(providerIcon).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + providerName: "docker", + theme: "light", + expectedRevision: "rev-a", + }), + ) + await fireEvent.click( + screen.getByRole("button", { name: "Skip initialization" }), + ) + await screen.findByText(/was added but is not initialized yet/) + await waitFor(() => + expect(screen.getByAltText("docker icon").getAttribute("src")).toBe( + dataUrl, + ), + ) + page.unmount() + }) + it("shows enum defaults but submits only explicitly selected options", async () => { providerOptions.mockResolvedValue({ SIZE: { diff --git a/desktop/src/renderer/src/lib/ipc/commands.ts b/desktop/src/renderer/src/lib/ipc/commands.ts index a931b1cc07..f51944f4a0 100644 --- a/desktop/src/renderer/src/lib/ipc/commands.ts +++ b/desktop/src/renderer/src/lib/ipc/commands.ts @@ -19,6 +19,10 @@ import type { } from "$lib/types/index.js" import type { AppNavigationAcknowledgment } from "$shared/app-route.js" import type { MachineDiagnosticsCache } from "$shared/machine-diagnostics-types.js" +import type { + ProviderIconReply, + ProviderIconRequest, +} from "$shared/provider-icon.js" import { invoke } from "./bridge.js" type CommandEnvelope = @@ -130,6 +134,12 @@ export async function providerList(): Promise { return invoke("provider_list") } +export async function providerIcon( + request: ProviderIconRequest, +): Promise { + return invoke("provider_icon", { ...request }) +} + export async function providerAdd( name: string, source?: string, diff --git a/desktop/src/renderer/src/lib/stores/settings.test.ts b/desktop/src/renderer/src/lib/stores/settings.test.ts index c83dc18e13..a80506a665 100644 --- a/desktop/src/renderer/src/lib/stores/settings.test.ts +++ b/desktop/src/renderer/src/lib/stores/settings.test.ts @@ -1,12 +1,14 @@ import { get } from "svelte/store" -import { beforeEach, describe, expect, it } from "vitest" +import { afterEach, beforeEach, describe, expect, it } from "vitest" import { applyTheme, CONTEXT_OPTION_KEYS, cycleTheme, DEFAULT_CONTEXT_OPTIONS, + effectiveTheme, getWorkspaceRecoveryState, + initSettings, parseContextOptions, setWorkspaceRecoveryState, theme, @@ -49,6 +51,101 @@ describe("settings store", () => { }) }) + describe("effectiveTheme", () => { + const realMatchMedia = window.matchMedia + let osDark = false + let osListeners: Array<() => void> = [] + + function setOsDark(value: boolean) { + osDark = value + for (const listener of osListeners) listener() + } + + beforeEach(() => { + osDark = false + osListeners = [] + window.matchMedia = ((query: string) => ({ + get matches() { + return osDark + }, + media: query, + addEventListener: (_type: string, listener: () => void) => { + osListeners.push(listener) + }, + removeEventListener: (_type: string, listener: () => void) => { + osListeners = osListeners.filter((entry) => entry !== listener) + }, + })) as unknown as typeof window.matchMedia + }) + + afterEach(() => { + window.matchMedia = realMatchMedia + }) + + it("follows an explicit override regardless of the OS preference", () => { + osDark = false + applyTheme("dark") + expect(get(effectiveTheme)).toBe("dark") + + osDark = true + applyTheme("light") + expect(get(effectiveTheme)).toBe("light") + }) + + it("resolves system to the current OS preference", () => { + osDark = true + applyTheme("system") + expect(get(effectiveTheme)).toBe("dark") + + osDark = false + applyTheme("system") + expect(get(effectiveTheme)).toBe("light") + }) + + it("tracks live OS transitions while the setting stays system, through the single media-query listener", () => { + theme.set("system") + const dispose = initSettings() + try { + expect(osListeners).toHaveLength(1) + expect(get(effectiveTheme)).toBe("light") + + setOsDark(true) + expect(get(theme)).toBe("system") + expect(get(effectiveTheme)).toBe("dark") + expect(document.documentElement.classList.contains("dark")).toBe(true) + + setOsDark(false) + expect(get(effectiveTheme)).toBe("light") + } finally { + dispose() + } + expect(osListeners).toHaveLength(0) + }) + + it("ignores OS transitions while an explicit theme is set", () => { + theme.set("light") + const dispose = initSettings() + try { + setOsDark(true) + expect(get(effectiveTheme)).toBe("light") + } finally { + dispose() + } + }) + + it("follows theme changes made through the theme store", () => { + const dispose = initSettings() + try { + theme.set("light") + expect(get(effectiveTheme)).toBe("light") + theme.set("dark") + expect(get(effectiveTheme)).toBe("dark") + } finally { + dispose() + } + }) + }) + describe("cycleTheme", () => { it("cycles light -> dark", () => { theme.set("light") diff --git a/desktop/src/renderer/src/lib/stores/settings.ts b/desktop/src/renderer/src/lib/stores/settings.ts index 0c0b234790..310aa25b32 100644 --- a/desktop/src/renderer/src/lib/stores/settings.ts +++ b/desktop/src/renderer/src/lib/stores/settings.ts @@ -19,6 +19,7 @@ const browser = typeof window !== "undefined" // ── UI Settings (localStorage) ────────────────────────────────────── export type Theme = "light" | "dark" | "system" +export type EffectiveTheme = "light" | "dark" export type ColorScheme = "default" | "emerald" | "purple" export type UIScale = "xs" | "sm" | "md" | "lg" | "xl" export type SidebarPosition = "left" | "right" @@ -74,18 +75,29 @@ export const theme = writable( getStored(STORAGE_KEY, ["light", "dark", "system"] as const, "dark"), ) +function resolveEffectiveTheme(value: Theme): EffectiveTheme { + if (value !== "system") return value + if (!browser) return "dark" + return window.matchMedia("(prefers-color-scheme: dark)").matches + ? "dark" + : "light" +} + +// The theme actually painted: an explicit override, or the OS preference when +// the setting is "system". Written only by applyTheme so the media-query +// listener in initSettings stays the single owner of OS theme changes. +export const effectiveTheme = writable( + resolveEffectiveTheme( + getStored(STORAGE_KEY, ["light", "dark", "system"] as const, "dark"), + ), +) + export function applyTheme(value: Theme) { if (!browser) return localStorage.setItem(STORAGE_KEY, value) - const root = document.documentElement - if (value === "system") { - const prefersDark = window.matchMedia( - "(prefers-color-scheme: dark)", - ).matches - root.classList.toggle("dark", prefersDark) - } else { - root.classList.toggle("dark", value === "dark") - } + const resolved = resolveEffectiveTheme(value) + document.documentElement.classList.toggle("dark", resolved === "dark") + effectiveTheme.set(resolved) } export function cycleTheme() { diff --git a/desktop/src/renderer/src/lib/types/index.ts b/desktop/src/renderer/src/lib/types/index.ts index 345f85cc2c..43f045b26c 100644 --- a/desktop/src/renderer/src/lib/types/index.ts +++ b/desktop/src/renderer/src/lib/types/index.ts @@ -86,6 +86,12 @@ export interface Provider { name: string version?: string source?: ProviderSource + /** Manifest-authored light icon reference; never rendered directly. */ + icon?: string + /** Manifest-authored dark icon reference; never rendered directly. */ + iconDark?: string + /** Selects the immutable cached icon revision; changes on asset/source update. */ + iconRevision?: string description?: string options?: Record optionGroups?: ProviderOptionGroup[] diff --git a/desktop/src/renderer/src/lib/utils/provider-icon-loader.ts b/desktop/src/renderer/src/lib/utils/provider-icon-loader.ts new file mode 100644 index 0000000000..677931088f --- /dev/null +++ b/desktop/src/renderer/src/lib/utils/provider-icon-loader.ts @@ -0,0 +1,147 @@ +import { providerIcon } from "$lib/ipc/commands.js" +import { activeContext } from "$lib/stores/contexts.js" +import type { ProviderIconTheme } from "$shared/provider-icon.js" + +const MAX_ENTRIES = 64 + +export interface ProviderIconLookup { + providerName: string + context: string + theme: ProviderIconTheme + revision: string +} + +interface LookupEntry { + context: string + promise: Promise +} + +// Only definitive answers are kept: transport errors wait for the next lookup; +// stale replies get one fresh read while their context remains active. +const pendingLookups = new Map() +const settledLookups = new Map>() +let currentContext: string | undefined + +// Main revokes pending reads from the context that is no longer active. +activeContext.subscribe((context) => { + if (currentContext !== undefined && currentContext !== context) { + for (const [key, entry] of pendingLookups) { + if (entry.context === currentContext) { + pendingLookups.delete(key) + } + } + } + currentContext = context +}) + +function lookupKey({ + context, + providerName, + revision, + theme, +}: ProviderIconLookup): string { + return `${context}\0${providerName}\0${revision}\0${theme}` +} + +/** Resolves to a `data:` URL, or null when the image is missing or unavailable. */ +export function loadProviderIcon( + lookup: ProviderIconLookup, +): Promise { + const key = lookupKey(lookup) + const cached = settledLookups.get(key) + if (cached) return cached + const existing = pendingLookups.get(key) + if (existing) return existing.promise + + let entry: LookupEntry | undefined + const pending = providerIcon({ + providerName: lookup.providerName, + context: lookup.context, + theme: lookup.theme, + expectedRevision: lookup.revision, + }).then( + (reply) => { + if ("stale" in reply) { + if (!isCurrentLookup(key, lookup, entry)) { + if (entry && pendingLookups.get(key) === entry) { + pendingLookups.delete(key) + } + return null + } + return retryStaleProviderIcon(lookup, key, entry) + } + const result = "dataUrl" in reply ? reply.dataUrl : null + cacheSettledProviderIcon(key, lookup, entry, result) + return result + }, + () => { + if (entry && pendingLookups.get(key) === entry) { + pendingLookups.delete(key) + } + return null + }, + ) + entry = { context: lookup.context, promise: pending } + pendingLookups.set(key, entry) + return pending +} + +function isCurrentLookup( + key: string, + lookup: ProviderIconLookup, + entry: LookupEntry | undefined, +): entry is LookupEntry { + return ( + entry !== undefined && + pendingLookups.get(key) === entry && + currentContext === lookup.context + ) +} + +function cacheSettledProviderIcon( + key: string, + lookup: ProviderIconLookup, + entry: LookupEntry | undefined, + result: string | null, +): void { + if (!isCurrentLookup(key, lookup, entry)) return + pendingLookups.delete(key) + settledLookups.set(key, Promise.resolve(result)) + while (settledLookups.size > MAX_ENTRIES) { + const oldest = settledLookups.keys().next().value + if (oldest === undefined) break + settledLookups.delete(oldest) + } +} + +function retryStaleProviderIcon( + lookup: ProviderIconLookup, + key: string, + entry: LookupEntry, +): Promise { + return providerIcon({ + providerName: lookup.providerName, + context: lookup.context, + theme: lookup.theme, + expectedRevision: lookup.revision, + }).then( + (reply) => { + if ("stale" in reply) { + if (pendingLookups.get(key) === entry) pendingLookups.delete(key) + return null + } + const result = "dataUrl" in reply ? reply.dataUrl : null + cacheSettledProviderIcon(key, lookup, entry, result) + return result + }, + () => { + if (pendingLookups.get(key) === entry) pendingLookups.delete(key) + return null + }, + ) +} + +export function clearProviderIconLoader(): void { + pendingLookups.clear() + settledLookups.clear() +} diff --git a/desktop/src/shared/provider-icon.ts b/desktop/src/shared/provider-icon.ts new file mode 100644 index 0000000000..3f82c0c71c --- /dev/null +++ b/desktop/src/shared/provider-icon.ts @@ -0,0 +1,28 @@ +export type ProviderIconTheme = "light" | "dark" + +export interface ProviderIconRequest { + providerName: string + context: string + theme: ProviderIconTheme + /** The iconRevision the caller's provider list entry carries. */ + expectedRevision: string +} + +/** + * `dataUrl` and `missing` are mutually exclusive. `stale` means the installed + * revision no longer matches `expectedRevision`: no image bytes are returned, + * and `revision` is the newly observed revision to wait for in the provider list. + */ +export type ProviderIconReply = + | { revision: string; dataUrl: string } + | { revision: string; missing: true } + | { revision: string; stale: true } + +export const PROVIDER_ICON_MAX_BYTES = 1024 * 1024 + +export const PROVIDER_ICON_MIME_TYPES = [ + "image/png", + "image/jpeg", + "image/webp", + "image/svg+xml", +] as const diff --git a/desktop/test-fixtures/provider-icons/assets/dark.svg b/desktop/test-fixtures/provider-icons/assets/dark.svg new file mode 100644 index 0000000000..e5e7756572 --- /dev/null +++ b/desktop/test-fixtures/provider-icons/assets/dark.svg @@ -0,0 +1 @@ +Dark fixture icon diff --git a/desktop/test-fixtures/provider-icons/assets/light.svg b/desktop/test-fixtures/provider-icons/assets/light.svg new file mode 100644 index 0000000000..c3167cd446 --- /dev/null +++ b/desktop/test-fixtures/provider-icons/assets/light.svg @@ -0,0 +1 @@ +Light fixture icon diff --git a/desktop/test-fixtures/provider-icons/provider-list.json b/desktop/test-fixtures/provider-icons/provider-list.json new file mode 100644 index 0000000000..0de26e5cff --- /dev/null +++ b/desktop/test-fixtures/provider-icons/provider-list.json @@ -0,0 +1,13 @@ +{ + "my-docker-fleet": { + "config": { + "name": "my-docker-fleet", + "version": "v1.0.0", + "icon": "assets/light.svg", + "iconDark": "assets/dark.svg", + "iconRevision": "rev-a" + }, + "state": { "initialized": true }, + "default": false + } +} diff --git a/desktop/test-fixtures/provider-icons/provider.yaml b/desktop/test-fixtures/provider-icons/provider.yaml new file mode 100644 index 0000000000..29acf6a1af --- /dev/null +++ b/desktop/test-fixtures/provider-icons/provider.yaml @@ -0,0 +1,7 @@ +name: my-docker-fleet +version: v1.0.0 +description: Minimal provider whose manifest owns its icons +icon: assets/light.svg +iconDark: assets/dark.svg +exec: + command: echo diff --git a/go.mod b/go.mod index 7b5ebb2c81..68d7e2090d 100644 --- a/go.mod +++ b/go.mod @@ -72,6 +72,7 @@ require ( go.uber.org/goleak v1.3.0 go.uber.org/zap v1.28.0 golang.org/x/crypto v0.57.0 + golang.org/x/image v0.41.0 golang.org/x/mod v0.41.0 golang.org/x/sync v0.24.0 golang.org/x/sys v0.48.0 diff --git a/pkg/config/context_deletion.go b/pkg/config/context_deletion.go index 86b7432a79..97df01c3b0 100644 --- a/pkg/config/context_deletion.go +++ b/pkg/config/context_deletion.go @@ -339,6 +339,23 @@ func validDeletionContextName(name string) bool { (runtime.GOOS != "windows" || !reservedWindowsContextName(name)) } +const maxContextPathComponentBytes = 255 + +// ValidateContextPathName accepts safe legacy context names while rejecting +// values that could escape the context directory when used as one path part. +func ValidateContextPathName(name string) error { + if invalidContextPathName(name) { + return errors.New("context name must be a safe path component") + } + if len(name) > maxContextPathComponentBytes { + return errors.New("context name exceeds the path component limit") + } + if runtime.GOOS == "windows" && reservedWindowsContextName(name) { + return errors.New("context name is a reserved Windows device name") + } + return nil +} + // ValidateContextName applies portable creation rules so a new context can be // deleted safely on every supported platform. func ValidateContextName(name string) error { diff --git a/pkg/config/context_deletion_test.go b/pkg/config/context_deletion_test.go index 0043049e82..6e896c27a0 100644 --- a/pkg/config/context_deletion_test.go +++ b/pkg/config/context_deletion_test.go @@ -260,3 +260,32 @@ func TestContextDeletionIntentAllowsLegacyWindowsReservedNameOnPosix(t *testing. require.NoError(t, WriteContextDeletionIntent(intent)) require.NoError(t, ClearContextDeletionIntent()) } + +func TestValidateContextPathName(t *testing.T) { + for _, name := range []string{ + DefaultContext, + "Legacy.Context_Name_That_Is_Over_48_Characters_Long", + "\u6771\u4eac-legacy", + } { + require.NoError(t, ValidateContextPathName(name), name) + } + + for _, name := range []string{ + "", + ".", + "..", + "../other", + `..\target`, + `C:\target`, + "name.", + "name ", + "bad\x00name", + strings.Repeat("a", maxContextPathComponentBytes+1), + } { + require.Error(t, ValidateContextPathName(name), name) + } + + if runtime.GOOS == localContextDeletionTestWindows { + require.Error(t, ValidateContextPathName("CON")) + } +} diff --git a/pkg/flags/names/names.go b/pkg/flags/names/names.go index 647276968f..e3bade3f63 100644 --- a/pkg/flags/names/names.go +++ b/pkg/flags/names/names.go @@ -261,6 +261,7 @@ const ( FromExisting = "from-existing" Prerelease = "prerelease" ProviderSource = "provider-source" + Theme = "theme" Use = "use" Version = "version" ) diff --git a/pkg/flags/names/names_test.go b/pkg/flags/names/names_test.go index 06ae0068cd..d2f4a7756a 100644 --- a/pkg/flags/names/names_test.go +++ b/pkg/flags/names/names_test.go @@ -186,6 +186,7 @@ var wireNames = []struct { {names.FromExisting, "from-existing"}, {names.Prerelease, "prerelease"}, {names.ProviderSource, "provider-source"}, + {names.Theme, "theme"}, {names.Use, "use"}, {names.Version, "version"}, {names.Channel, "channel"}, diff --git a/pkg/provider/assets.go b/pkg/provider/assets.go new file mode 100644 index 0000000000..c551187d35 --- /dev/null +++ b/pkg/provider/assets.go @@ -0,0 +1,347 @@ +package provider + +import ( + "context" + "errors" + "fmt" + "net/url" + "os" + "path" + "path/filepath" + "strings" + "sync" + + "github.com/devsy-org/devsy/pkg/log" +) + +// githubRawBaseURL serves repository content at a tag; tests point it at a local server. +var githubRawBaseURL = "https://raw.githubusercontent.com" + +const ( + iconSchemeHTTP = "http" + iconSchemeHTTPS = "https" +) + +// ErrIconSourceUnresolved reports that a relative icon cannot be tied to the +// installed provider version, so no repository-relative fetch is attempted. +var ErrIconSourceUnresolved = errors.New("provider source version is unresolved") + +// IconLocation is where an icon reference points. Exactly one field is set. +type IconLocation struct { + URL string + File string +} + +// ResolveProviderIconReference resolves an author-supplied icon reference +// against the installed provider source. It performs no I/O except resolving +// symlinks for local manifests, so it is safe to call from list paths. +func ResolveProviderIconReference(source ProviderSource, reference string) (IconLocation, error) { + parsed, err := parseIconReference(reference) + if err != nil { + return IconLocation{}, err + } + if parsed.Scheme != "" { + return resolveAbsoluteIconURL(parsed) + } + relative, err := cleanRelativeIconPath(parsed) + if err != nil { + return IconLocation{}, err + } + return resolveRelativeIconReference(source, parsed, relative) +} + +func parseIconReference(reference string) (*url.URL, error) { + reference = strings.TrimSpace(reference) + if reference == "" { + return nil, errors.New("icon reference is empty") + } + if strings.ContainsRune(reference, 0) { + return nil, errors.New("icon reference contains a NUL byte") + } + + parsed, err := url.Parse(reference) + if err != nil { + return nil, errors.New("icon reference is not a valid URL or path") + } + return parsed, nil +} + +func resolveRelativeIconReference( + source ProviderSource, + parsed *url.URL, + relative string, +) (IconLocation, error) { + switch { + case source.Internal: + return IconLocation{}, errors.New("built-in providers have no source-relative icons") + case source.Github != "": + return resolveGithubIconReference(source, parsed, relative) + case source.File != "": + return resolveLocalIconReference(source.File, parsed, relative) + default: + return resolveURLRelativeIcon(source, parsed) + } +} + +func resolveGithubIconReference( + source ProviderSource, + parsed *url.URL, + relative string, +) (IconLocation, error) { + location, err := resolveGithubIcon(source, relative) + if err != nil { + return IconLocation{}, err + } + target, err := url.Parse(location.URL) + if err != nil { + return IconLocation{}, err + } + target.RawQuery, target.ForceQuery = parsed.RawQuery, parsed.ForceQuery + target.Fragment, target.RawFragment = parsed.Fragment, parsed.RawFragment + return IconLocation{URL: target.String()}, nil +} + +func resolveLocalIconReference( + manifestFile string, + parsed *url.URL, + relative string, +) (IconLocation, error) { + if parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" { + return IconLocation{}, errors.New( + "local icon path must not contain a query or fragment", + ) + } + return resolveLocalIcon(manifestFile, relative) +} + +func resolveAbsoluteIconURL(parsed *url.URL) (IconLocation, error) { + scheme := strings.ToLower(parsed.Scheme) + if scheme != iconSchemeHTTP && scheme != iconSchemeHTTPS { + return IconLocation{}, fmt.Errorf("icon scheme %q is not supported", parsed.Scheme) + } + if parsed.Host == "" { + return IconLocation{}, errors.New("icon URL has no host") + } + + return IconLocation{URL: parsed.String()}, nil +} + +// cleanRelativeIconPath validates a scheme-less reference and returns its +// decoded, cleaned, slash-separated path rooted at the logical manifest root. +func cleanRelativeIconPath(parsed *url.URL) (string, error) { + if parsed.Host != "" || parsed.User != nil { + return "", errors.New("icon reference must not contain a URL authority") + } + + if err := validateRelativeIconPath(parsed.Path); err != nil { + return "", err + } + cleaned := path.Clean(parsed.Path) + if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, "../") { + return "", errors.New("icon reference escapes the provider manifest directory") + } + return cleaned, nil +} + +func validateRelativeIconPath(decoded string) error { + switch { + case decoded == "": + return errors.New("icon reference has no path") + case strings.ContainsRune(decoded, 0): + return errors.New("icon reference contains a NUL byte") + case strings.ContainsRune(decoded, '\\'): + return errors.New("icon reference must not contain backslashes") + case strings.HasPrefix(decoded, "/"): + return errors.New("icon reference must be relative to the provider manifest") + } + + return nil +} + +// localIconRelativePath reuses the source-reference path checks at the rooted +// file-read boundary, without replacing the logical root with a resolved path. +func localIconRelativePath(reference string) (string, error) { + parsed, err := parseIconReference(reference) + if err != nil { + return "", err + } + return cleanRelativeIconPath(parsed) +} + +func resolveGithubIcon(source ProviderSource, relative string) (IconLocation, error) { + if source.ResolvedRef == "" { + return IconLocation{}, ErrIconSourceUnresolved + } + + repository := strings.TrimPrefix(source.Github, "github.com/") + owner, repo, ok := strings.Cut(repository, "/") + if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") { + return IconLocation{}, fmt.Errorf("invalid github source %q", source.Github) + } + + target, err := url.Parse(githubRawBaseURL) + if err != nil { + return IconLocation{}, err + } + target.Path = path.Join("/", owner, repo, "refs/tags", source.ResolvedRef, relative) + + return IconLocation{URL: target.String()}, nil +} + +func resolveURLRelativeIcon(source ProviderSource, relative *url.URL) (IconLocation, error) { + base := source.ResolvedManifestURL + if base == "" { + base = logicalManifestURL(source.URL) + } + if base == "" { + return IconLocation{}, ErrIconSourceUnresolved + } + + target, err := url.Parse(base) + if err != nil || (target.Scheme != iconSchemeHTTP && target.Scheme != iconSchemeHTTPS) || + target.Host == "" { + return IconLocation{}, errors.New("provider manifest URL is not a valid http(s) URL") + } + + target.User = nil + target.RawQuery = "" + target.ForceQuery = false + target.Fragment = "" + target.RawFragment = "" + + return IconLocation{URL: target.ResolveReference(relative).String()}, nil +} + +// resolveLocalIcon keeps the icon inside the manifest directory even through +// symlinks; the returned path is fully resolved. +func resolveLocalIcon(manifestFile, relative string) (IconLocation, error) { + if strings.ContainsRune(relative, ':') { + return IconLocation{}, errors.New("local icon path must not contain ':'") + } + + root, err := filepath.EvalSymlinks(filepath.Dir(manifestFile)) + if err != nil { + return IconLocation{}, fmt.Errorf("resolve manifest directory: %w", err) + } + + relativeTarget, err := resolveLocalIconTarget(root, relative) + if err != nil { + return IconLocation{}, err + } + return IconLocation{File: filepath.Join(root, relativeTarget)}, nil +} + +// resolveLocalIconTarget keeps symlink targets within the canonical source +// directory. Callers opening the file must still use an os.Root boundary. +func resolveLocalIconTarget(root, relative string) (string, error) { + resolved, err := filepath.EvalSymlinks(filepath.Join(root, filepath.FromSlash(relative))) + if err != nil { + return "", fmt.Errorf("resolve local icon: %w", err) + } + relativeTarget := mustRel(root, resolved) + if !filepath.IsLocal(relativeTarget) { + return "", errors.New("local icon resolves outside the provider manifest directory") + } + return relativeTarget, nil +} + +// mustRel returns a path that is never local when target is not under root. +func mustRel(root, target string) string { + rel, err := filepath.Rel(root, target) + if err != nil { + return ".." + string(os.PathSeparator) + } + return rel +} + +// PrepareProviderIcons downloads, validates and caches the provider's light +// and dark icons, then selects the resulting immutable revision in +// cfg.IconRevision. Asset failures are recorded as missing variants and never +// returned; only cache I/O failures or cancellation are errors, in which case +// cfg.IconRevision stays empty. cfg.Source must already be authoritative and +// the call must precede saving the installed manifest. +func PrepareProviderIcons( + ctx context.Context, + devsyContext string, + cfg *ProviderConfig, + manifest []byte, +) error { + if cfg == nil { + return errors.New("provider config is nil") + } + cfg.IconRevision = "" + if cfg.Icon == "" && cfg.IconDark == "" { + return nil + } + + cacheDir, err := GetProviderAssetsDir(devsyContext, cfg.Name) + if err != nil { + return err + } + + fetcher := newIconFetcher() + defer fetcher.close() + + light, dark := fetchIconVariants(ctx, fetcher, cfg) + if err := ctx.Err(); err != nil { + return err + } + + revision, created, err := storeIconRevision(cacheDir, iconInputs{ + manifest: manifest, + source: cfg.Source, + icon: cfg.Icon, + iconDark: cfg.IconDark, + }, light, dark) + if err != nil { + return err + } + + if created { + logIconDiagnostic(cfg.Name, light, dark) + } + cfg.IconRevision = revision + + return nil +} + +func fetchIconVariants( + ctx context.Context, + fetcher *iconFetcher, + cfg *ProviderConfig, +) (light, dark iconVariant) { + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + light = fetcher.fetchVariant(ctx, cfg.Source, cfg.Icon) + }() + go func() { + defer wg.Done() + dark = fetcher.fetchVariant(ctx, cfg.Source, cfg.IconDark) + }() + wg.Wait() + + return light, dark +} + +// logIconDiagnostic emits one concise line for a newly recorded revision with +// failed variants. It never fails the provider lifecycle. +func logIconDiagnostic(providerName string, light, dark iconVariant) { + var failures []string + if light.failure != "" { + failures = append(failures, "light: "+light.failure) + } + if dark.failure != "" { + failures = append(failures, "dark: "+dark.failure) + } + if len(failures) == 0 { + return + } + + log.Warnf( + "provider %q icon unavailable, using fallback (%s)", + providerName, + strings.Join(failures, "; "), + ) +} diff --git a/pkg/provider/assets_cache.go b/pkg/provider/assets_cache.go new file mode 100644 index 0000000000..2ca51fd5bf --- /dev/null +++ b/pkg/provider/assets_cache.go @@ -0,0 +1,425 @@ +package provider + +import ( + "context" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "regexp" +) + +const ( + // ProviderAssetsDirName is the installed provider's icon cache directory. + ProviderAssetsDirName = "provider-assets" + + iconThemeLight = "light" + iconThemeDark = "dark" + + iconCacheSchemaVersion = 1 + iconBlobsDir = "blobs" + iconRevisionsDir = "revisions" + maxRevisionMetadata = 64 << 10 +) + +var sha256HexPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// ProviderIconResult is the disk-only answer to a provider icon read. +type ProviderIconResult struct { + Revision string `json:"revision"` + MimeType string `json:"mimeType,omitempty"` + DataBase64 string `json:"dataBase64,omitempty"` + Missing bool `json:"missing,omitempty"` +} + +// iconInputs are everything that identifies where a revision came from. +type iconInputs struct { + manifest []byte + source ProviderSource + icon string + iconDark string +} + +// iconVariantMetadata describes one theme variant of a revision. File is the +// cache-relative slash-separated blob name. +type iconVariantMetadata struct { + Missing bool `json:"missing,omitempty"` + MimeType string `json:"mimeType,omitempty"` + SHA256 string `json:"sha256,omitempty"` + File string `json:"file,omitempty"` +} + +// iconRevisionMetadata is the immutable record an installed manifest selects by +// its hash. It deliberately carries no revision field of its own. +type iconRevisionMetadata struct { + SchemaVersion int `json:"schemaVersion"` + Fingerprint string `json:"fingerprint"` + Light iconVariantMetadata `json:"light"` + Dark iconVariantMetadata `json:"dark"` +} + +func iconFingerprint(inputs iconInputs) (string, error) { + manifestHash := sha256.Sum256(inputs.manifest) + payload, err := json.Marshal(struct { + Manifest string `json:"manifest"` + Source ProviderSource `json:"source"` + Icon string `json:"icon"` + IconDark string `json:"iconDark"` + }{ + Manifest: hex.EncodeToString(manifestHash[:]), + Source: inputs.source, + Icon: inputs.icon, + IconDark: inputs.iconDark, + }) + if err != nil { + return "", err + } + + sum := sha256.Sum256(payload) + return hex.EncodeToString(sum[:]), nil +} + +func hashIconRevision(metadata iconRevisionMetadata) (string, error) { + payload, err := json.Marshal(metadata) + if err != nil { + return "", err + } + + sum := sha256.Sum256(payload) + return hex.EncodeToString(sum[:]), nil +} + +func variantMetadata(variant iconVariant) iconVariantMetadata { + if variant.data == nil { + return iconVariantMetadata{Missing: true} + } + + sum := sha256.Sum256(variant.data) + digest := hex.EncodeToString(sum[:]) + return iconVariantMetadata{ + MimeType: variant.mime, + SHA256: digest, + File: iconBlobsDir + "/" + digest, + } +} + +// storeIconRevision writes the content-addressed blobs first and the revision +// metadata last, so a revision visible on disk is always complete. created is +// false when the identical revision was already recorded. +func storeIconRevision( + cacheDir string, + inputs iconInputs, + light, dark iconVariant, +) (revision string, created bool, err error) { + fingerprint, err := iconFingerprint(inputs) + if err != nil { + return "", false, fmt.Errorf("fingerprint provider icons: %w", err) + } + + metadata := iconRevisionMetadata{ + SchemaVersion: iconCacheSchemaVersion, + Fingerprint: fingerprint, + Light: variantMetadata(light), + Dark: variantMetadata(dark), + } + revision, err = hashIconRevision(metadata) + if err != nil { + return "", false, fmt.Errorf("hash provider icon revision: %w", err) + } + + if err := storeIconBlobs(cacheDir, metadata, light, dark); err != nil { + return "", false, err + } + + revisionFile := filepath.Join(cacheDir, iconRevisionsDir, revision+".json") + if existingRevisionVerifies(cacheDir, revision) { + return revision, false, nil + } + + payload, err := json.Marshal(metadata) + if err != nil { + return "", false, fmt.Errorf("encode provider icon revision: %w", err) + } + if err := WriteFileAtomic(revisionFile, payload, 0o600); err != nil { + return "", false, fmt.Errorf("write provider icon revision: %w", err) + } + + return revision, true, nil +} + +func existingRevisionVerifies(cacheDir, revision string) bool { + root, err := os.OpenRoot(cacheDir) + if err != nil { + return false + } + defer func() { _ = root.Close() }() + _, err = loadIconRevision(root, revision) + return err == nil +} + +func storeIconBlobs( + cacheDir string, + metadata iconRevisionMetadata, + light, dark iconVariant, +) error { + blobsDir := filepath.Join(cacheDir, iconBlobsDir) + for _, dir := range []string{blobsDir, filepath.Join(cacheDir, iconRevisionsDir)} { + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("create provider icon cache: %w", err) + } + } + for _, stored := range []struct { + meta iconVariantMetadata + variant iconVariant + }{{metadata.Light, light}, {metadata.Dark, dark}} { + if stored.meta.Missing { + continue + } + if err := WriteFileAtomic( + filepath.Join(blobsDir, stored.meta.SHA256), + stored.variant.data, + 0o600, + ); err != nil { + return fmt.Errorf("write provider icon: %w", err) + } + } + return nil +} + +// ReadProviderIcon returns the cached icon variant selected by the installed +// manifest. It reads disk only, never the network. An installation without a +// revision or an explicitly missing variant returns Missing; absent selected +// cache files and other I/O or integrity failures are errors. +func ReadProviderIcon( + devsyContext string, + cfg *ProviderConfig, + theme string, +) (*ProviderIconResult, error) { + if err := validateIconRead(cfg, theme); err != nil { + return nil, err + } + if cfg.IconRevision == "" { + return &ProviderIconResult{Missing: true}, nil + } + + cacheDir, err := GetProviderAssetsDir(devsyContext, cfg.Name) + if err != nil { + return nil, err + } + + root, err := os.OpenRoot(cacheDir) + if err != nil { + return nil, fmt.Errorf("open provider icon cache: %w", err) + } + defer func() { _ = root.Close() }() + return readCachedProviderIcon(root, cfg.IconRevision, theme) +} + +func validateIconRead(cfg *ProviderConfig, theme string) error { + if theme != iconThemeLight && theme != iconThemeDark { + return fmt.Errorf("unsupported icon theme %q: use light or dark", theme) + } + if cfg == nil { + return errors.New("provider config is nil") + } + if cfg.IconRevision != "" && !sha256HexPattern.MatchString(cfg.IconRevision) { + return fmt.Errorf("invalid icon revision %q", cfg.IconRevision) + } + return nil +} + +func readCachedProviderIcon(root *os.Root, revision, theme string) (*ProviderIconResult, error) { + metadata, err := loadIconRevision(root, revision) + if err != nil { + return nil, err + } + + variant := metadata.Light + if theme == iconThemeDark { + variant = metadata.Dark + } + if variant.Missing { + return &ProviderIconResult{Revision: revision, Missing: true}, nil + } + + data, err := loadIconBlob(root, variant) + if err != nil { + return nil, err + } + + return &ProviderIconResult{ + Revision: revision, + MimeType: variant.MimeType, + DataBase64: base64.StdEncoding.EncodeToString(data), + }, nil +} + +func loadIconRevision(root *os.Root, revision string) (*iconRevisionMetadata, error) { + file, err := root.Open(iconRevisionsDir + "/" + revision + ".json") + if err != nil { + return nil, fmt.Errorf("%s: %w", "open provider icon revision", err) + } + defer func() { _ = file.Close() }() + + payload, err := io.ReadAll(io.LimitReader(file, maxRevisionMetadata+1)) + if err != nil { + return nil, fmt.Errorf("read provider icon revision: %w", err) + } + if len(payload) > maxRevisionMetadata { + return nil, errors.New("provider icon revision metadata is too large") + } + + metadata := &iconRevisionMetadata{} + if err := json.Unmarshal(payload, metadata); err != nil { + return nil, fmt.Errorf("decode provider icon revision: %w", err) + } + if metadata.SchemaVersion != iconCacheSchemaVersion { + return nil, fmt.Errorf("unsupported provider icon schema %d", metadata.SchemaVersion) + } + + recomputed, err := hashIconRevision(*metadata) + if err != nil { + return nil, err + } + if recomputed != revision { + return nil, errors.New("provider icon revision metadata does not match its revision") + } + + return metadata, nil +} + +func loadIconBlob(root *os.Root, variant iconVariantMetadata) ([]byte, error) { + if !validIconBlobMetadata(variant) { + return nil, errors.New("provider icon metadata names an invalid cache entry") + } + + file, err := root.Open(variant.File) + if err != nil { + return nil, fmt.Errorf("%s: %w", "open provider icon", err) + } + defer func() { _ = file.Close() }() + + data, err := readIconBlob(file) + if err != nil { + return nil, err + } + sum := sha256.Sum256(data) + if hex.EncodeToString(sum[:]) != variant.SHA256 { + return nil, errors.New("cached provider icon does not match its recorded hash") + } + return data, nil +} + +func validIconBlobMetadata(variant iconVariantMetadata) bool { + return sha256HexPattern.MatchString(variant.SHA256) && + variant.File == iconBlobsDir+"/"+variant.SHA256 && + isAllowedIconMime(variant.MimeType) +} + +func readIconBlob(file *os.File) ([]byte, error) { + info, err := file.Stat() + if err != nil { + return nil, fmt.Errorf("stat provider icon: %w", err) + } + if info.Size() > maxIconBytes { + return nil, fmt.Errorf("cached provider icon exceeds %d bytes", maxIconBytes) + } + + data, err := io.ReadAll(io.LimitReader(file, maxIconBytes+1)) + if err != nil { + return nil, fmt.Errorf("read provider icon: %w", err) + } + if len(data) > maxIconBytes { + return nil, fmt.Errorf("cached provider icon exceeds %d bytes", maxIconBytes) + } + + return data, nil +} + +// CopyProviderIcons copies the selected revision into the clone's own cache. +// Blobs precede metadata, and the caller publishes the destination manifest last. +// Missing source files, I/O failures and integrity errors are returned. +func CopyProviderIcons( + ctx context.Context, + devsyContext, sourceName string, + destination *ProviderConfig, +) error { + if destination.IconRevision == "" { + return nil + } + if !sha256HexPattern.MatchString(destination.IconRevision) { + return errors.New("invalid provider icon revision") + } + sourceDir, err := GetProviderAssetsDir(devsyContext, sourceName) + if err != nil { + return err + } + source, err := os.OpenRoot(sourceDir) + if err != nil { + return err + } + defer func() { _ = source.Close() }() + destinationDir, err := GetProviderAssetsDir(devsyContext, destination.Name) + if err != nil { + return err + } + return copyCachedIconRevision(ctx, source, destinationDir, destination.IconRevision) +} + +func copyCachedIconRevision( + ctx context.Context, + source *os.Root, + destinationDir, revision string, +) error { + metadata, err := loadIconRevision(source, revision) + if err != nil { + return err + } + for _, variant := range []iconVariantMetadata{metadata.Light, metadata.Dark} { + if err := copyIconVariant(ctx, source, destinationDir, variant); err != nil { + return err + } + } + if err := ctx.Err(); err != nil { + return err + } + if err := os.MkdirAll(filepath.Join(destinationDir, iconRevisionsDir), 0o700); err != nil { + return err + } + payload, err := json.Marshal(metadata) + if err != nil { + return err + } + return WriteFileAtomic( + filepath.Join(destinationDir, iconRevisionsDir, revision+".json"), + payload, + 0o600, + ) +} + +func copyIconVariant( + ctx context.Context, + source *os.Root, + destinationDir string, + variant iconVariantMetadata, +) error { + if err := ctx.Err(); err != nil { + return err + } + if variant.Missing { + return nil + } + data, err := loadIconBlob(source, variant) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Join(destinationDir, iconBlobsDir), 0o700); err != nil { + return err + } + return WriteFileAtomic(filepath.Join(destinationDir, variant.File), data, 0o600) +} diff --git a/pkg/provider/assets_download.go b/pkg/provider/assets_download.go new file mode 100644 index 0000000000..78174cd233 --- /dev/null +++ b/pkg/provider/assets_download.go @@ -0,0 +1,403 @@ +package provider + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "io" + "io/fs" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/devsy-org/devsy/pkg/download" + "github.com/devsy-org/devsy/pkg/gitcredentials" + devsyhttp "github.com/devsy-org/devsy/pkg/http" +) + +const ( + iconDownloadTimeout = 5 * time.Second + maxIconRedirects = 5 +) + +var ( + errTooManyIconRedirects = fmt.Errorf("stopped after %d redirects", maxIconRedirects) + urlInTextPattern = regexp.MustCompile(`https?://[^\s"'<>)]+`) +) + +// iconVariant is one fetched and validated icon. data is nil when the variant +// is absent or unusable; failure then carries a redacted one-line reason for a +// declared reference. +type iconVariant struct { + data []byte + mime string + failure string +} + +type iconHTTPResponse struct { + data []byte + contentType string + status int +} + +// iconFetcher downloads optional icons with bounded time, size and redirects. +// It never retries: a logo must not delay provider setup. +type iconFetcher struct { + client *http.Client + credentials download.CredentialResolver + timeout time.Duration +} + +func newIconFetcher() *iconFetcher { + return &iconFetcher{ + client: newIconHTTPClient(), + credentials: githubIconCredentials{inner: gitcredentials.Resolver{}}, + timeout: iconDownloadTimeout, + } +} + +func (f *iconFetcher) close() { + f.client.CloseIdleConnections() +} + +func newIconHTTPClient() *http.Client { + transport := http.DefaultTransport.(*http.Transport).Clone() + if insecure, _ := strconv.ParseBool(os.Getenv(config.EnvInsecureTLS)); insecure { + // #nosec G402 -- enabled with DEVSY_INSECURE_TLS env, like the shared client + transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + } + + return &http.Client{ + Transport: devsyhttp.WithUserAgent(transport, devsyhttp.UserAgent()), + CheckRedirect: checkIconRedirect, + } +} + +// checkIconRedirect caps redirects and keeps Authorization on the origin it was +// resolved for. +func checkIconRedirect(req *http.Request, via []*http.Request) error { + if len(via) > maxIconRedirects { + return errTooManyIconRedirects + } + if !sameOrigin(req.URL, via[0].URL) { + req.Header.Del("Authorization") + } + return nil +} + +func sameOrigin(a, b *url.URL) bool { + return strings.EqualFold(a.Scheme, b.Scheme) && strings.EqualFold(a.Host, b.Host) +} + +func (f *iconFetcher) fetchVariant( + ctx context.Context, + source ProviderSource, + reference string, +) iconVariant { + if strings.TrimSpace(reference) == "" { + return iconVariant{} + } + + location, err := ResolveProviderIconReference(source, reference) + if err != nil { + return failedIcon(err.Error()) + } + + var ( + data []byte + contentType string + origin string + ) + if location.File != "" { + origin = "local file " + filepath.Base(location.File) + relative, pathErr := localIconRelativePath(reference) + if pathErr != nil { + return failedIcon(origin + ": " + pathErr.Error()) + } + data, err = readLocalIcon(filepath.Dir(source.File), filepath.FromSlash(relative)) + } else { + origin = redactURL(location.URL) + data, contentType, err = f.download(ctx, location.URL) + } + if err != nil { + return failedIcon(origin + ": " + err.Error()) + } + + mimeType, err := validateIconImage(data, contentType) + if err != nil { + return failedIcon(origin + ": " + err.Error()) + } + + return iconVariant{data: data, mime: mimeType} +} + +func failedIcon(reason string) iconVariant { + return iconVariant{failure: redactURLsInText(reason)} +} + +func (f *iconFetcher) download(ctx context.Context, rawURL string) ([]byte, string, error) { + ctx, cancel := context.WithTimeout(ctx, f.timeout) + defer cancel() + + response, err := f.get(ctx, rawURL, "") + if err == nil || f.credentials == nil || !isCredentialStatus(response.status) { + return response.data, response.contentType, err + } + + token := f.resolveToken(ctx, rawURL) + if token == "" { + return nil, "", err + } + + response, err = f.get(ctx, rawURL, token) + return response.data, response.contentType, err +} + +// resolveToken asks for credentials only for origins that may carry them: +// https, or a loopback host. +func (f *iconFetcher) resolveToken(ctx context.Context, rawURL string) string { + parsed, err := url.Parse(rawURL) + if err != nil || !credentialTransportSafe(parsed) { + return "" + } + + _, password, err := f.credentials.Resolve(ctx, parsed.Scheme, parsed.Hostname(), parsed.Path) + if err != nil { + return "" + } + return password +} + +func credentialTransportSafe(target *url.URL) bool { + if strings.EqualFold(target.Scheme, iconSchemeHTTPS) { + return true + } + + host := target.Hostname() + if strings.EqualFold(host, "localhost") { + return true + } + ip := net.ParseIP(host) + return ip != nil && ip.IsLoopback() +} + +func (f *iconFetcher) get( + ctx context.Context, + rawURL, token string, +) (iconHTTPResponse, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return iconHTTPResponse{}, errors.New("invalid icon URL") + } + req.Header.Set("Accept", "image/*") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + + resp, err := f.client.Do(req) + if err != nil { + return iconHTTPResponse{}, errors.New(describeRequestError(err)) + } + defer func() { _ = resp.Body.Close() }() + + return readIconHTTPResponse(resp) +} + +func readIconHTTPResponse(resp *http.Response) (iconHTTPResponse, error) { + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return iconHTTPResponse{status: resp.StatusCode}, fmt.Errorf( + "HTTP status %d", + resp.StatusCode, + ) + } + if resp.ContentLength > maxIconBytes { + return iconHTTPResponse{status: resp.StatusCode}, fmt.Errorf( + "image exceeds %d bytes", + maxIconBytes, + ) + } + + data, err := io.ReadAll(io.LimitReader(resp.Body, maxIconBytes+1)) + if err != nil { + return iconHTTPResponse{status: resp.StatusCode}, errors.New( + describeRequestError(err), + ) + } + if len(data) > maxIconBytes { + return iconHTTPResponse{status: resp.StatusCode}, fmt.Errorf( + "image exceeds %d bytes", + maxIconBytes, + ) + } + + return iconHTTPResponse{ + data: data, + contentType: resp.Header.Get("Content-Type"), + status: resp.StatusCode, + }, nil +} + +// describeRequestError reduces a transport error to a reason that cannot echo +// the request URL back. +func describeRequestError(err error) string { + if urlErr, ok := errors.AsType[*url.Error](err); ok { + err = urlErr.Err + } + + switch { + case errors.Is(err, context.DeadlineExceeded): + return "timed out" + case errors.Is(err, context.Canceled): + return "canceled" + default: + return err.Error() + } +} + +// readLocalIcon opens the original relative path beneath the logical manifest +// directory, so a symlink swap cannot redirect the read outside that root. +func readLocalIcon(directory, relative string) ([]byte, error) { + root, err := os.OpenRoot(directory) + if err != nil { + return nil, describeFileError(err) + } + defer func() { _ = root.Close() }() + + handle, err := openContainedLocalIcon(root, directory, relative) + if err != nil { + return nil, describeFileError(err) + } + defer func() { _ = handle.Close() }() + + info, err := handle.Stat() + if err != nil { + return nil, describeFileError(err) + } + if !info.Mode().IsRegular() { + return nil, errors.New("not a regular file") + } + if info.Size() > maxIconBytes { + return nil, fmt.Errorf("image exceeds %d bytes", maxIconBytes) + } + + data, err := io.ReadAll(io.LimitReader(handle, maxIconBytes+1)) + if err != nil { + return nil, describeFileError(err) + } + if len(data) > maxIconBytes { + return nil, fmt.Errorf("image exceeds %d bytes", maxIconBytes) + } + return data, nil +} + +// openContainedLocalIcon permits contained absolute symlinks but opens only a +// relative target through the already-open root. A later escape swap is rejected. +func openContainedLocalIcon(root *os.Root, directory, relative string) (*os.File, error) { + canonicalRoot, err := filepath.EvalSymlinks(directory) + if err != nil { + return nil, err + } + target, err := resolveLocalIconTarget(canonicalRoot, relative) + if err != nil { + return nil, err + } + info, err := root.Stat(target) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() { + return nil, errors.New("not a regular file") + } + return openLocalIconFile(root, target) +} + +func describeFileError(err error) error { + if errors.Is(err, fs.ErrNotExist) { + return errors.New("file not found") + } + return err +} + +// redactURL keeps scheme, host and path only: userinfo, query and fragment +// commonly hold secrets or signatures. +func redactURL(raw string) string { + parsed, err := url.Parse(raw) + if err != nil { + return "" + } + + parsed.User = nil + parsed.RawQuery = "" + parsed.ForceQuery = false + parsed.Fragment = "" + parsed.RawFragment = "" + return parsed.String() +} + +func redactURLsInText(text string) string { + return urlInTextPattern.ReplaceAllStringFunc(text, redactURL) +} + +// githubIconCredentials limits credential lookups to GitHub hosts, mapping the +// raw-content host to the github.com credential that git helpers store. +type githubIconCredentials struct { + inner download.CredentialResolver +} + +func (r githubIconCredentials) Resolve( + ctx context.Context, + _, host, path string, +) (username, password string, err error) { + switch strings.ToLower(host) { + case "github.com", "raw.githubusercontent.com": + repositoryPath := githubRepositoryCredentialPath(path) + if repositoryPath == "" { + return "", "", nil + } + return r.inner.Resolve(ctx, iconSchemeHTTPS, "github.com", repositoryPath) + default: + return "", "", nil + } +} + +func githubRepositoryCredentialPath(path string) string { + if !strings.HasPrefix(path, "/") { + return "" + } + owner, remaining, found := strings.Cut(path[1:], "/") + if !found { + return "" + } + repository, _, _ := strings.Cut(remaining, "/") + if !isGitHubRepositorySegment(owner) || !isGitHubRepositorySegment(repository) { + return "" + } + return "/" + owner + "/" + repository +} + +func isGitHubRepositorySegment(segment string) bool { + if segment == "" || segment == "." || segment == ".." { + return false + } + for i := range segment { + if !isGitHubRepositoryByte(segment[i]) { + return false + } + } + return true +} + +func isGitHubRepositoryByte(value byte) bool { + lower := value | 0x20 + return lower >= 'a' && lower <= 'z' || + value >= '0' && value <= '9' || + value == '.' || value == '_' || value == '-' +} diff --git a/pkg/provider/assets_download_test.go b/pkg/provider/assets_download_test.go new file mode 100644 index 0000000000..54d687fa8f --- /dev/null +++ b/pkg/provider/assets_download_test.go @@ -0,0 +1,820 @@ +package provider + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "image/jpeg" + "image/png" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/devsy-org/devsy/pkg/config" + "github.com/stretchr/testify/suite" + "golang.org/x/image/webp" +) + +const svgOpen = `` + +type fakeCredentials struct { + mu sync.Mutex + calls []string + token string +} + +func (f *fakeCredentials) Resolve( + _ context.Context, + protocol, host, _ string, +) (string, string, error) { + f.mu.Lock() + defer f.mu.Unlock() + f.calls = append(f.calls, protocol+"://"+host) + return "user", f.token, nil +} + +func (f *fakeCredentials) callCount() int { + f.mu.Lock() + defer f.mu.Unlock() + return len(f.calls) +} + +type pathSensitiveCredentials struct { + tokens map[string]string + paths []string +} + +func (f *pathSensitiveCredentials) Resolve( + _ context.Context, + _, _, path string, +) (string, string, error) { + f.paths = append(f.paths, path) + return "user", f.tokens[path], nil +} + +func lossyWebPBytes(t *testing.T) []byte { + t.Helper() + data, err := base64.StdEncoding.DecodeString(` +UklGRooJAABXRUJQVlA4IH4JAAAyLwCdASqWAGQAPo04lUeioYwGg0EUBGJZQDWZNsO1JP5n64fB +3Ub8v+o9XG3d53fTuYGQ1jfacgmJk6PthcDb6Dzr0z01vyivwkv9E+4YUHpwH65k6mVaIXqrC4XT +BQLqkGc1rCgGes04gKPUimJAmZhyXeG4DBy84mCBiQxZwB3y0ABGURmcpLymWUnJPKhGe8RujkoI +Z810gU5JiH/ONuOi9qprpe/D+igi50G8+UMtjxOVM02DI1cX8zoiV/kuK0uHAtfQaqJC3eZhgnSA +YCLcn9Ayj9pMHbfk0JJRbdF9H8CZCBhGkcIF2K+oGIR+gVW/6aRvmPtQNcIoyzgdFht+Z31lpq0f +F/hD2JlqnmNkvDsKndGC/A+Z2BH0/lTXb9S/ELRNKqWKIrfN/h2Pao6wijZj9KO5+yNBvsnvdZyN +mFFB2O/JHVnn3XtYdzUEN9w2Fz52sfwOAMXrMIYRcnd3nEYDHjHyw4dvT5hhr5BZSlFAHgz7I3AW +w5qCIy/YgAD+/p/aKcNszx8Xd4P/UesGZn9KuPC+bM7Ftm6MOeuMu5ZP3zWAOb4skNx3FFcXmMGa +zmsEGYQxHgVSeNZ9FqVet4IUc/QajL5J2TiLIyAJvSnMT8RZXKotqUhB00DSZ+hzvShMFGwcuPBT +vvABW6TRYILdCUNwFVOGZl4yyQ9vGi5HuKDPa0gsLt5fP8S4wD8dJy27Tx3P+MUlS3egiSAY3Ynl +R2aEQlh866iFPPH4U06y6+VGtvbq+N2Kh7z14i/+zoWLhk9pvfWkhXMMm9MPLtl0gOEtc9xLInLy +eKbb3kbUD60/vRcE6d6302jpc9f8tyCW9qcg2LhBeY7H2akeaH/6bXaX5rc45emsA+58yiAwxbaG +eWFF5DyCqUMWbwX+BIHTlFjTeatv8Sl8hjklsykxPbFpSt0dCM//nn9ZdFg3tLTgq6vbkKhe7dWN +NSGsafAD2DYlAyGH4P0320LlribfnfkovkKWxuky/vTuGOBnAr/wZcL2eyg+34CczxKpZKh77B+Y +/VUqH4LnC2BOEdIPmgkE/zOGa2S5wyNqfdctPTNhYMOtR/HFOukVkv/v5q5E4alohykAaUISEiLq +RbaZkkTkhypdOAfifqYybCSqlCYCwsaqVL4sDhbep/dRfVog8tmgSoeh+MIl+D/ePR8eD56tz6EY +EKnHVN8AaXvpFK50F3SFMLcnaEMJhUJc8PvGF/Ez/q7X+HKQ3J84TzFJbscxr7eozHeFMMH9/h0l +5DXY4aTv+iIR4gM0dnbjbEHgsKP61ALeNz28bvmwhHa0rFBa9uJVskb1W3k5cAMzC1RkxfJ/sT++ +R+7jjNsNc3XkIKUrwP6nZrwzhpXAvJx4tFQoPhnq1k754EgDJG16UBY37s0uMFIAsT+slJHQ0OGm +nE8aWr9oXIe02bm/CAIXyEWvxnHcHTTxIqhFD4XzHGJ+MCe7opIY/dEkOPcKUD6zNQ8IPOT/XpDv +WGw/ok/UcILHoyQ3QdCgUqFDr1rm1Jt5wWbZcWSNhXjf1LuKzwJrkf1rHf/Ktf4tAtfWr/rQhun3 +1sTg2rbi5fWKOZul29eY3ngUYVPHgSb/vvPisPqqXdfnJLpilz0u/VvCPFVofn1VADfJKNOJkXtC +IxQ/v7RKZMrtdUkmRJZswSHIZ9950jHQi7KTbIozDSPMHUy5aw2VzfNS47v6d4YOvGY2pMW5Q4B6 +vh1E+FirurI+iYkoyBWyfAJxKHc58PQ5CYOUXqC7pdinZViLBy70kYbbPbgU16bokAP2zAR/UBW9 ++GTlfdAUNdGskU7nGzUbge7rt45UqaTZcKTu5GbN3YflPxU2uS7NxWGOuCgtGCu1O2zX12MVXSKg +HlYv6pddY6EWs6QeEpvgtKAdQv8MJmISVUS1y3+Xom1owgeGRyqpgO9dulNmPt3UdK4PBiVz97n4 +QbX6QRooaAlPvFmUgYNO1CJXiWGkzP0vNP2JNu7Uymtxhz7UZCAHjW2aFJ7s6cNOZIdKmCkq2bw5 +iA4jZSPs+snTiT8gFyUKnSK7Lvc7rUOJNq9qvNoZtAgC9mMDhOA4WVjNR2cBJKQgzfgtRsVLMpbb +b3FJroDkux5VhZ2nB16TBoEqgYqQVo5WdivKjNOLGJqAfcX2hMjE3UK1Yu8DT5qfQrRuAK2Y5rGu +t0SWSmpLZX5oCO+KXgbeh9mzk1ULYJcaWCVCKBy5bGrsnEUN/9L8qkahJ2sF4FJp/aG7WATm/9nN +fvkAi8lhzP/kWYQa9HUJpUL3gBJcTRd4yFXMPA3Sd0p4NQBULx1DdGWxeCP9eyvD39+nWkHgYJIf +rEqlpXaD5TrpJt5O/XbQa7IlyHjPimjnSQsjf5WXdfIGOL21QHGApYH6u54q1jf6WGac8ynys7oJ +FEM36NyUp+UTsX4pxn1RaWGRKJ8EUk3XJ5GXVGQO9BB7YID2vR537253t2WNYirDbju9w8bfBJ02 +jDOgEjZRSMP4VZLutXotpzQo8259eLACChjWX8ODdcvEf/OwTwQNoI8hZGimdkNEgILhM0zYlOe/ +fvv4VdkxvU3oMXhie9v16T7kN9sL2GPzB//P0FLhM+QKOxbdguTnMDvH6VbEoeuX6wO/o2wec6id +/QOZb0e5hbVrq2UgcXpbHm0bYn+DuA5e4FT50zUUlVe7cTvmnstNZ+p0Xx903zN/WMjmLvgt1/b2 +syHzhRgTFraP9Do3ny9hNZnIrCrGjzHRtrVqe+tXgR6ZNZ+m/jwyFG7P2rXbjnkhpHuEMADn/iT2 +5su+3c8AO61vNksZfCsbt4+kycfRJ+i4XiIP08ro2g7+yyYpRvnPmyJ9ojMVMcGtxMwqA0xX3VFs +DzaRi/RhJi2Oq3eNKX0RmNIU44qhLkJGgqfqTFv0iHdegTV1gC1kmG5RjbTZPcOHR1p1IeEJIHrf +BdSa+gUASMi1S7t3crCjBtIcmPizFbEGi/EzDV7APO+vG523/eSG2foiiRUUpHFULlY4/yxOcoew +d28fFY+vXN5LbUbZKIV5H8GiUlX6VfPimYmh0cF/plxhM9cKZjyoroVYgx2CS0YDaRx1cXFEkQfP +5XjpzRKf4p907sdYKFcqEPQlbmHFjEidsSKEpR+BW97QhyY5R5qhJLhYeW9z8daTdGUKGE35tq2v +7YKorbyGClrbuz8sZhepmUhbcbem+wvwkD1AW074/fSpNdTCIzlajUOz++SHPqSubek2AAAAAAA= +`) + if err != nil { + t.Fatal(err) + } + return data +} + +type iconRoundTripper func(*http.Request) (*http.Response, error) + +func (f iconRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { + return f(request) +} + +type AssetDownloadSuite struct { + suite.Suite +} + +func TestAssetDownloadSuite(t *testing.T) { + suite.Run(t, new(AssetDownloadSuite)) +} + +func (s *AssetDownloadSuite) SetupTest() { + setupTestHome(s.T()) +} + +func (s *AssetDownloadSuite) TestValidateAcceptsSupportedFormats() { + tests := []struct { + name string + data []byte + want string + }{ + {"png", pngBytes(s.T(), 16, 16), mimePNG}, + {"png at the pixel limit", pngBytes(s.T(), maxIconDimension, 1), mimePNG}, + {"jpeg", jpegBytes(s.T(), 16, 16), mimeJPEG}, + {"webp", validWebPBytes(s.T()), mimeWebP}, + { + "extended webp with matching frame", + webpExtendedFrameBytes(1, 1, validWebPBytes(s.T())), + mimeWebP, + }, + {"svg", []byte(testIconSVGLight), mimeSVG}, + {"svg with BOM and declaration", append( + []byte("\xEF\xBB\xBF\n"), + []byte(testIconSVGLight)..., + ), mimeSVG}, + } + + for _, tt := range tests { + s.Run(tt.name, func() { + got, err := validateIconImage(tt.data, "") + s.Require().NoError(err) + s.Equal(tt.want, got) + }) + } +} + +func (s *AssetDownloadSuite) TestValidateRejectsBadImages() { + truncatedPNG := pngBytes(s.T(), 4, 4) + truncatedPNG = truncatedPNG[:len(truncatedPNG)-12] + truncatedJPEG := jpegBytes(s.T(), 4, 4) + truncatedJPEG = truncatedJPEG[:len(truncatedJPEG)-2] + truncatedWebP := validWebPBytes(s.T()) + truncatedWebP = truncatedWebP[:len(truncatedWebP)-2] + _, err := png.DecodeConfig(bytes.NewReader(truncatedPNG)) + s.Require().NoError(err) + _, err = jpeg.DecodeConfig(bytes.NewReader(truncatedJPEG)) + s.Require().NoError(err) + _, err = webp.DecodeConfig(bytes.NewReader(truncatedWebP)) + s.Require().NoError(err) + + tests := []struct { + name string + data []byte + contentType string + }{ + {"empty image body", nil, ""}, + {"html error page", []byte("404"), "text/html"}, + { + "html login page labelled as image", + []byte("login"), + "image/png", + }, + { + "html declared type with svg-looking body", + []byte(testIconSVGLight), + "text/html; charset=utf-8", + }, + {"plain text", []byte("not an image"), ""}, + {"gif", []byte("GIF89a\x01\x00\x01\x00"), ""}, + {"png too wide", pngBytes(s.T(), maxIconDimension+1, 1), ""}, + {"png too tall", pngBytes(s.T(), 1, maxIconDimension+1), ""}, + {"jpeg too wide", jpegBytes(s.T(), maxIconDimension+1, 8), ""}, + {"webp too wide", webpExtendedBytes(maxIconDimension+1, 8), ""}, + {"truncated png", pngBytes(s.T(), 4, 4)[:12], ""}, + {"truncated webp", webpExtendedBytes(8, 8)[:20], ""}, + {"truncated PNG payload", truncatedPNG, ""}, + {"truncated JPEG payload", truncatedJPEG, ""}, + {"truncated WebP payload", truncatedWebP, ""}, + { + "oversized", + append([]byte(testIconSVGLight), bytes.Repeat([]byte(" "), maxIconBytes)...), + "", + }, + } + + for _, tt := range tests { + s.Run(tt.name, func() { + _, err := validateIconImage(tt.data, tt.contentType) + s.Error(err) + }) + } +} + +func (s *AssetDownloadSuite) TestValidateRejectsWebPCanvasFrameMismatch() { + data := webpExtendedFrameBytes(2, 1, validWebPBytes(s.T())) + + _, err := validateIconImage(data, "") + + s.Error(err, "the VP8X canvas must match its VP8L frame") +} + +func (s *AssetDownloadSuite) TestValidateRejectsOversizedWebPInnerFrameBeforeDecode() { + data := webpExtendedFrameBytes(1, 1, oversizedWebPFrameBytes(s.T())) + + _, err := validateIconImage(data, "") + + s.Error(err) +} + +func (s *AssetDownloadSuite) TestValidateRejectsOversizedVP8ChunkLength() { + data := lossyWebPBytes(s.T()) + s.Require().Equal("VP8 ", string(data[12:16])) + mimeType, err := validateIconImage(data, "") + s.Require().NoError(err) + s.Equal(mimeWebP, mimeType) + + binary.LittleEndian.PutUint32(data[16:20], 2<<20) + binary.LittleEndian.PutUint32(data[4:8], (2<<20)+12) + _, err = validateIconImage(data, "") + s.Error(err) +} + +func (s *AssetDownloadSuite) TestValidateSVGAcceptsSimpleDrawings() { + accepted := map[string]string{ + "gradient fill": svgOpen + `` + + ``, + "internal use": svgOpen + ``, + "xlink internal": svgOpen + ``, + "stylesheet": svgOpen + ``, + "style attribute": svgOpen + ``, + "editor metadata": `` + + ``, + "animation of fill": svgOpen + `` + + ``, + "xml comment": `` + svgOpen + ``, + "split internal url": svgOpen + ``, + } + + for name, svg := range accepted { + s.Run(name, func() { + _, err := validateIconImage([]byte(svg), "image/svg+xml") + s.Require().NoError(err) + }) + } +} + +func (s *AssetDownloadSuite) TestValidateSVGRejectsHostileContent() { + rejected := map[string]string{ + "not well-formed": svgOpen + ``, + "unterminated": svgOpen + ``, + "wrong root": ``, + "missing namespace": ``, + "multiple roots": svgOpen + `` + svgOpen + ``, + "text outside root": `hello ` + svgOpen + ``, + "doctype": `` + svgOpen + ``, + "entity expansion": `]>` + + svgOpen + `&b;`, + "external entity": `]>` + + svgOpen + `&x;`, + "stylesheet instruction": `` + svgOpen + ``, + "script": svgOpen + ``, + "nested script": svgOpen + ``, + "foreignObject": svgOpen + `
`, + "iframe": svgOpen + `