diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bd9a46ff0..4700ef0041 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,8 @@ All notable changes to `src-cli` are documented in this file. ### Added +- `src` now prints a warning to stderr when it is older than the version recommended by your Sourcegraph instance. The recommended version is looked up at most once every 24 hours per instance. To disable the check, set the `SRC_SKIP_VERSION_CHECK` environment variable to any non-blank string. [#930](https://github.com/sourcegraph/src-cli/issues/930) + ### Changed ### Fixed diff --git a/cmd/src/main.go b/cmd/src/main.go index 8635301b8a..cf941eeb96 100644 --- a/cmd/src/main.go +++ b/cmd/src/main.go @@ -156,7 +156,13 @@ func (c *config) apiClient(flags *api.Flags, out io.Writer) api.Client { } } - return api.NewClient(opts) + client := api.NewClient(opts) + // Checked here rather than before the command is dispatched, so that the + // lookup uses the command's own flags, such as -insecure-skip-verify. + warnOutdatedVersionOnce.Do(func() { + maybeWarnOutdatedVersion(client, c.endpointURL, flag.CommandLine.Arg(0)) + }) + return client } // readConfig reads the config file from the given path. diff --git a/cmd/src/version.go b/cmd/src/version.go index fad3a42f78..64d0659f44 100644 --- a/cmd/src/version.go +++ b/cmd/src/version.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "net/url" "os" "github.com/sourcegraph/sourcegraph/lib/errors" @@ -42,17 +43,19 @@ var versionCommand = clicompat.Wrap(&cli.Command{ HideVersion: true, Action: func(ctx context.Context, c *cli.Command) error { args := VersionArgs{ - Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), - ClientOnly: c.Bool("client-only"), + Client: cfg.apiClient(clicompat.APIFlagsFromCmd(c), os.Stdout), + EndpointURL: cfg.endpointURL, + ClientOnly: c.Bool("client-only"), } return versionHandler(args) }, }) type VersionArgs struct { - ClientOnly bool - Client api.Client - Output io.Writer + ClientOnly bool + Client api.Client + EndpointURL *url.URL + Output io.Writer } func versionHandler(args VersionArgs) error { @@ -68,9 +71,10 @@ func versionHandler(args VersionArgs) error { if recommendedVersion == "" { fmt.Println("Recommended version: ") fmt.Println("This Sourcegraph instance does not support this feature.") - return nil + } else { + fmt.Printf("Recommended version: %s or later\n", recommendedVersion) } - fmt.Printf("Recommended version: %s or later\n", recommendedVersion) + warnOutdatedVersionFromLookup(recommendedVersion, args.EndpointURL) return nil } diff --git a/cmd/src/version_check.go b/cmd/src/version_check.go new file mode 100644 index 0000000000..b3892e40ea --- /dev/null +++ b/cmd/src/version_check.go @@ -0,0 +1,140 @@ +package main + +import ( + "context" + "fmt" + "net/url" + "os" + "path/filepath" + "sync" + "time" + + "github.com/Masterminds/semver" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/version" +) + +const ( + // versionCheckTimeout bounds the recommended-version lookup, which runs + // before the command the user asked for. + versionCheckTimeout = 3 * time.Second + + // versionCheckInterval is how long the result of a lookup is reused before + // the instance is asked again. + versionCheckInterval = 24 * time.Hour +) + +// warnOutdatedVersionOnce limits the check to once per run of src-cli, however +// many API clients the command creates. +var warnOutdatedVersionOnce sync.Once + +// maybeWarnOutdatedVersion prints a warning to stderr when src-cli is older +// than the version recommended by the Sourcegraph instance at endpointURL, +// which it asks using client unless a recent answer is cached. +// +// It never fails the command: an unreachable instance, an unparseable version, +// or an unwritable cache all result in no warning. +func maybeWarnOutdatedVersion(client api.Client, endpointURL *url.URL, subcommand string) { + // 'src version' asks the instance itself, and then calls + // warnOutdatedVersionFromLookup with the answer. + if subcommand == "version" || skipVersionCheck() { + return + } + cachePath, err := recommendedVersionCachePath(endpointURL) + if err != nil { + return + } + printOutdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) +} + +// warnOutdatedVersionFromLookup is the check for 'src version', which has just +// been told the recommended version by the instance at endpointURL. The answer +// is cached, so that the commands that follow warn about the same version. +func warnOutdatedVersionFromLookup(recommended string, endpointURL *url.URL) { + if skipVersionCheck() { + return + } + if cachePath, err := recommendedVersionCachePath(endpointURL); err == nil { + _ = cacheRecommendedVersion(cachePath, recommended) + } + printOutdatedVersionWarning(recommended, endpointURL) +} + +// skipVersionCheck reports whether the version check is disabled, or has no +// version to compare. +func skipVersionCheck() bool { + return os.Getenv("SRC_SKIP_VERSION_CHECK") != "" || version.BuildTag == version.DefaultBuildTag +} + +func printOutdatedVersionWarning(recommended string, endpointURL *url.URL) { + if warning := outdatedVersionWarning(recommended, endpointURL); warning != "" { + fmt.Fprintln(os.Stderr, warning) + } +} + +// outdatedVersionWarning returns the warning to print, or "" when src-cli is +// not known to be older than the recommended version. +func outdatedVersionWarning(recommendedVersion string, endpointURL *url.URL) string { + current, err := semver.NewVersion(version.BuildTag) + if err != nil { + return "" + } + recommended, err := semver.NewVersion(recommendedVersion) + if err != nil { + return "" + } + if !current.LessThan(recommended) { + return "" + } + return fmt.Sprintf("⚠️ Warning: src-cli %s is older than %s, the version recommended by %s. "+ + "To upgrade, see https://github.com/sourcegraph/src-cli#installation. "+ + "To silence this warning, set SRC_SKIP_VERSION_CHECK=1.", + current, recommended, endpointURL) +} + +// recommendedVersionCachePath returns the file that holds the version +// recommended by the instance at endpointURL. +func recommendedVersionCachePath(endpointURL *url.URL) (string, error) { + cacheDir, err := os.UserCacheDir() + if err != nil { + return "", err + } + return filepath.Join(cacheDir, "sourcegraph", "src-cli", "recommended-version-"+url.QueryEscape(endpointURL.String())), nil +} + +// cacheRecommendedVersion records recommended, and the time it was learned, in +// the file at cachePath. +func cacheRecommendedVersion(cachePath, recommended string) error { + if err := os.MkdirAll(filepath.Dir(cachePath), 0o700); err != nil { + return err + } + return os.WriteFile(cachePath, []byte(recommended), 0o600) +} + +// recommendedVersion returns the src-cli version recommended by the instance +// that client talks to, or "" when it is unknown. The answer is cached in the +// file at cachePath for versionCheckInterval, so most commands make no extra +// request. +func recommendedVersion(client api.Client, cachePath string) string { + if info, err := os.Stat(cachePath); err == nil && time.Since(info.ModTime()) < versionCheckInterval { + cached, _ := os.ReadFile(cachePath) + return string(cached) + } + + // Record the attempt before the lookup, so that an instance that does not + // answer delays one command per versionCheckInterval instead of every + // command. Without a writable cache there is no such bound, so do not look. + if cacheRecommendedVersion(cachePath, "") != nil { + return "" + } + + ctx, cancel := context.WithTimeout(context.Background(), versionCheckTimeout) + defer cancel() + recommended, err := getRecommendedVersion(ctx, client) + if err != nil { + return "" + } + _ = cacheRecommendedVersion(cachePath, recommended) + return recommended +} diff --git a/cmd/src/version_check_test.go b/cmd/src/version_check_test.go new file mode 100644 index 0000000000..e67f52e687 --- /dev/null +++ b/cmd/src/version_check_test.go @@ -0,0 +1,325 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "github.com/sourcegraph/src-cli/internal/api" + "github.com/sourcegraph/src-cli/internal/version" +) + +// setBuildTag pretends that src-cli was built as the given release. +func setBuildTag(t *testing.T, buildTag string) { + t.Helper() + original := version.BuildTag + t.Cleanup(func() { version.BuildTag = original }) + version.BuildTag = buildTag +} + +// versionServer is a fake Sourcegraph instance that answers every request with +// the given status and recommended version, and counts the requests it gets. +func versionServer(t *testing.T, status int, recommended string) (client api.Client, endpointURL *url.URL, requests *int) { + t.Helper() + requests = new(int) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *requests++ + if r.URL.Path != "/.api/src-cli/version" { + t.Errorf("unexpected request path %q", r.URL.Path) + } + w.WriteHeader(status) + fmt.Fprintf(w, `{"version": %q}`, recommended) + })) + t.Cleanup(server.Close) + endpointURL = mustParseURL(t, server.URL) + return api.NewClient(api.ClientOpts{EndpointURL: endpointURL, AccessToken: "token", Out: io.Discard}), endpointURL, requests +} + +// useTemporaryCacheDir points os.UserCacheDir at an empty directory. +func useTemporaryCacheDir(t *testing.T) { + t.Helper() + // Wherever os.UserCacheDir looks on this operating system. + for _, name := range []string{"HOME", "XDG_CACHE_HOME", "LocalAppData"} { + t.Setenv(name, t.TempDir()) + } +} + +// captureStderr returns what run writes to os.Stderr. +func captureStderr(t *testing.T, run func()) string { + t.Helper() + stderr := os.Stderr + defer func() { os.Stderr = stderr }() + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stderr = writer + run() + writer.Close() + output, err := io.ReadAll(reader) + if err != nil { + t.Fatal(err) + } + return string(output) +} + +func TestOutdatedVersionWarning(t *testing.T) { + tests := []struct { + name string + current string + status int + recommended string + wantWarning bool + }{ + {name: "older patch", current: "6.4.1", status: http.StatusOK, recommended: "6.4.2", wantWarning: true}, + {name: "older, compared as numbers not strings", current: "9.9.9", status: http.StatusOK, recommended: "10.0.0", wantWarning: true}, + {name: "newer, compared as numbers not strings", current: "10.0.0", status: http.StatusOK, recommended: "9.9.9"}, + {name: "same version", current: "6.4.2", status: http.StatusOK, recommended: "6.4.2"}, + {name: "instance does not recommend a version", current: "6.4.2", status: http.StatusNotFound}, + {name: "instance returns an error", current: "6.4.2", status: http.StatusInternalServerError, recommended: "7.0.0"}, + {name: "instance returns an unparseable version", current: "6.4.2", status: http.StatusOK, recommended: "latest"}, + {name: "running an unparseable version", current: "custom-build", status: http.StatusOK, recommended: "7.0.0"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.current) + client, endpointURL, _ := versionServer(t, test.status, test.recommended) + + warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(t.TempDir(), "recommended-version")), endpointURL) + + if !test.wantWarning { + if warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + return + } + for _, want := range []string{test.current, test.recommended, endpointURL.String(), "SRC_SKIP_VERSION_CHECK"} { + if !strings.Contains(warning, want) { + t.Errorf("warning %q does not mention %q", warning, want) + } + } + }) + } +} + +func TestRecommendedVersionIsLookedUpOncePerInterval(t *testing.T) { + makeStale := func(t *testing.T, cachePath string) { + t.Helper() + stale := time.Now().Add(-versionCheckInterval - time.Minute) + if err := os.Chtimes(cachePath, stale, stale); err != nil { + t.Fatal(err) + } + } + + t.Run("answer is reused until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "nested", "recommended-version") + + for range 2 { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { + t.Fatal("got no warning, want one on every command") + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + + makeStale(t, cachePath) + outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL) + if *requests != 2 { + t.Fatalf("got %d requests after the cache went stale, want 2", *requests) + } + }) + + t.Run("upgrading silences the warning without another lookup", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + cachePath := filepath.Join(t.TempDir(), "recommended-version") + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning == "" { + t.Fatal("got no warning before upgrading, want one") + } + + setBuildTag(t, "6.4.2") + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { + t.Fatalf("got warning %q after upgrading, want none", warning) + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + }) + + t.Run("failed lookup is not retried until it is stale", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusInternalServerError, "") + cachePath := filepath.Join(t.TempDir(), "recommended-version") + + for range 2 { + if warning := outdatedVersionWarning(recommendedVersion(client, cachePath), endpointURL); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + } + if *requests != 1 { + t.Fatalf("got %d requests, want 1", *requests) + } + }) + + t.Run("no lookup without a writable cache", func(t *testing.T) { + setBuildTag(t, "6.4.1") + client, endpointURL, requests := versionServer(t, http.StatusOK, "6.4.2") + // A regular file where the cache directory should be. + blocker := filepath.Join(t.TempDir(), "blocker") + if err := os.WriteFile(blocker, nil, 0o600); err != nil { + t.Fatal(err) + } + + if warning := outdatedVersionWarning(recommendedVersion(client, filepath.Join(blocker, "recommended-version")), endpointURL); warning != "" { + t.Fatalf("got warning %q, want none", warning) + } + if *requests != 0 { + t.Fatalf("got %d requests, want 0", *requests) + } + }) +} + +func TestSkipVersionCheck(t *testing.T) { + tests := []struct { + name string + buildTag string + optOut string + want bool + }{ + {name: "release build", buildTag: "6.4.2", want: false}, + {name: "opted out", buildTag: "6.4.2", optOut: "1", want: true}, + {name: "dev build", buildTag: version.DefaultBuildTag, want: true}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, test.buildTag) + t.Setenv("SRC_SKIP_VERSION_CHECK", test.optOut) + + if got := skipVersionCheck(); got != test.want { + t.Errorf("skipVersionCheck() = %v, want %v", got, test.want) + } + }) + } +} + +// TestVersionCommandChecksWithItsOwnLookup covers 'src version', which always +// asks the instance: it warns with that answer and caches it, instead of +// running the check that other commands get from config.apiClient. +func TestVersionCommandChecksWithItsOwnLookup(t *testing.T) { + const warning = "Warning: src-cli 6.4.1 is older than 6.4.3" + + // setup returns a fake instance that recommends 6.4.3, and the path of a + // cache that was told 6.4.2 a moment ago. + setup := func(t *testing.T) (client api.Client, endpointURL *url.URL, requests *int, cachePath string) { + t.Helper() + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + useTemporaryCacheDir(t) + client, endpointURL, requests = versionServer(t, http.StatusOK, "6.4.3") + cachePath, err := recommendedVersionCachePath(endpointURL) + if err != nil { + t.Fatal(err) + } + if err := cacheRecommendedVersion(cachePath, "6.4.2"); err != nil { + t.Fatal(err) + } + return client, endpointURL, requests, cachePath + } + + t.Run("warns with the answer it gets, and caches it for later commands", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + // The check that config.apiClient runs for every command. + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL}); err != nil { + t.Error(err) + } + }) + + if got := strings.Count(stderr, "Warning:"); got != 1 || !strings.Contains(stderr, warning) { + t.Errorf("got stderr %q, want only %q", stderr, warning) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.3" { + t.Errorf("got cached version %q, want 6.4.3", cached) + } + if *requests != 1 { + t.Errorf("got %d requests, want 1", *requests) + } + }) + + t.Run("-client-only does not ask the instance", func(t *testing.T) { + client, endpointURL, requests, cachePath := setup(t) + + stderr := captureStderr(t, func() { + maybeWarnOutdatedVersion(client, endpointURL, "version") + if err := versionHandler(VersionArgs{Client: client, EndpointURL: endpointURL, ClientOnly: true}); err != nil { + t.Error(err) + } + }) + + if stderr != "" { + t.Errorf("got stderr %q, want none", stderr) + } + if cached := recommendedVersion(client, cachePath); cached != "6.4.2" { + t.Errorf("got cached version %q, want 6.4.2 left alone", cached) + } + if *requests != 0 { + t.Errorf("got %d requests, want 0", *requests) + } + }) +} + +// TestAPIClientWarnsAboutOutdatedVersion covers where the check is hooked in: +// config.apiClient, which every command that talks to the instance calls with +// its own flags. +func TestAPIClientWarnsAboutOutdatedVersion(t *testing.T) { + tests := []struct { + name string + insecureSkipVerify bool + wantWarnings int + }{ + {name: "self-signed instance with -insecure-skip-verify is warned once, however many clients", insecureSkipVerify: true, wantWarnings: 1}, + {name: "self-signed instance without -insecure-skip-verify is not trusted", insecureSkipVerify: false, wantWarnings: 0}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + setBuildTag(t, "6.4.1") + t.Setenv("SRC_SKIP_VERSION_CHECK", "") + useTemporaryCacheDir(t) + warnOutdatedVersionOnce = sync.Once{} + t.Cleanup(func() { warnOutdatedVersionOnce = sync.Once{} }) + + server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprint(w, `{"version": "6.4.2"}`) + })) + server.Config.ErrorLog = log.New(io.Discard, "", 0) // rejected certificates + server.StartTLS() + t.Cleanup(server.Close) + cfg := &config{endpointURL: mustParseURL(t, server.URL), accessToken: "token"} + flags := api.NewFlagsFromValues(false, false, false, test.insecureSkipVerify, false) + + stderr := captureStderr(t, func() { + for range 2 { + cfg.apiClient(flags, io.Discard) + } + }) + + if got := strings.Count(stderr, "Warning: src-cli 6.4.1 is older than 6.4.2"); got != test.wantWarnings { + t.Errorf("got %d warnings, want %d; stderr: %q", got, test.wantWarnings, stderr) + } + }) + } +} diff --git a/go.mod b/go.mod index e90ea68b3f..3a1dfd626f 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.27.3 require ( cloud.google.com/go/storage v1.70.0 + github.com/Masterminds/semver v1.5.0 github.com/aws/aws-sdk-go-v2/config v1.33.12 github.com/aws/aws-sdk-go-v2/service/ec2 v1.343.0 github.com/aws/aws-sdk-go-v2/service/eks v1.105.1 @@ -57,7 +58,6 @@ require ( github.com/Azure/go-ansiterm v0.0.0-20261013165250-51075c6ea6bc // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.62.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.62.0 // indirect - github.com/Masterminds/semver v1.5.0 // indirect github.com/alecthomas/chroma/v2 v2.27.0 // indirect github.com/aws/aws-sdk-go-v2 v1.47.5 // indirect github.com/aws/aws-sdk-go-v2/credentials v1.20.12 // indirect