diff --git a/.golangci.yml b/.golangci.yml index 61fb998b..96fd92c8 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -310,9 +310,8 @@ linters: - github.com/meshcloud/meshstack-cli/client # the API docs choose the version of a request - github.com/meshcloud/meshstack-cli/internal/apidocs - # a full URL picks the stored profile whose endpoint holds it, and has to fit an endpoint - # or profile named by flag or environment, so api reads the stored profiles and the - # source of both settings, which pkg/ leaves out + # api-docs takes the endpoint of the profile without a login, and a full URL gives its + # origin as the endpoint setting, both of which pkg/ leaves out - github.com/meshcloud/meshstack-cli/internal/profile - github.com/meshcloud/meshstack-cli/internal/meshstack - github.com/meshcloud/meshstack-cli/internal/setting diff --git a/cmd/api/api.go b/cmd/api/api.go index d870a155..65bd3c63 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -19,7 +19,6 @@ import ( "github.com/meshcloud/meshstack-cli/client/http" "github.com/meshcloud/meshstack-cli/client/openapi" "github.com/meshcloud/meshstack-cli/cmd/internal" - "github.com/meshcloud/meshstack-cli/internal/setting" ) func New() *cobra.Command { @@ -28,7 +27,7 @@ func New() *cobra.Command { cmd := &cobra.Command{ Use: "api ", Short: "Send an authorized request to the meshStack API", - Long: fmt.Sprintf(`Send an authorized request to a path of the meshStack API, and print the response, which is typically JSON. Give the path relative to the endpoint, or give a full URL whose endpoint matches a stored profile with credentials. + Long: fmt.Sprintf(`Send an authorized request to a path of the meshStack API, and print the response, which is typically JSON. Give the path relative to the endpoint, or give a full URL, whose scheme and host the command then uses as the endpoint. Use this command for everything that the other commands do not cover. For a path of meshStack's public API, the command sets the Accept and Content-Type headers to the latest API version that the API docs list, unless you set them yourself. @@ -52,24 +51,14 @@ To see what the API docs say about the request, run the same command line with ' return err } ctx := cmd.Context() - var profileSources setting.Sources - if r.target.IsAbs() { - if _, profileSources, err = profileFor(ctx, r.target); err != nil { - return err - } - } // Resolved before the API docs, whose first download takes a while, so that a missing // login fails at once. - meshStack, err := internal.ResolveClient(ctx, internal.WithSettingSources(profileSources)) + meshStack, err := internal.ResolveClient(ctx, internal.WithSettingSources(r.originAsEndpoint())) if err != nil { return err } - if r.target.IsAbs() { - if err = r.cutTo(meshStack.Endpoint); err != nil { - return err - } - selector.Path = r.target.Path - args = []string{r.target.String()} + if r.target.IsAbs() && !strings.EqualFold(r.origin(), meshStack.Endpoint.String()) { + return fmt.Errorf("%s is not at the endpoint %s of this command; leave out --%s", r.target.Redacted(), meshStack.Endpoint, internal.EndpointFlag.Name) } spec, wait, err := flags.loadApiDocs(cmd, meshStack.Endpoint) defer wait() diff --git a/cmd/api/api_test.go b/cmd/api/api_test.go index ee7e7612..e25bb28a 100644 --- a/cmd/api/api_test.go +++ b/cmd/api/api_test.go @@ -70,7 +70,7 @@ func TestApi(t *testing.T) { _, err := meshStack.run(t, api.New(), "", "/api/meshobjects/meshbuildingblocks") - require.ErrorContains(t, err, "selects no credential") + require.ErrorContains(t, err, "no credential for the endpoint") assert.Empty(t, docs.TakeRequests()) assert.Empty(t, meshStack.requests) }) @@ -128,13 +128,13 @@ func TestApi(t *testing.T) { t.Run("writes the body of a failed answer, and fails with a hint to api-docs on a client error", func(t *testing.T) { for status, wantError := range map[int]string{ - gohttp.StatusConflict: "meshStack answered HTTP 409: still in use. Run meshstack api-docs /api/x -H 'Accept: application/json' -X DELETE to see what the API expects", + gohttp.StatusConflict: "meshStack answered HTTP 409: still in use. Run meshstack api-docs /api/x -H 'Accept: application/json' -X POST to see what the API expects", gohttp.StatusBadGateway: "meshStack answered HTTP 502: still in use", - gohttp.StatusForbidden: "auth scope profile default: meshStack answered HTTP 403: still in use", + gohttp.StatusForbidden: "auth scope endpoint " + meshStack.URL + ": meshStack answered HTTP 403: still in use", } { meshStack.answer(status, `{"message":"still in use"}`) - stdout, err := meshStack.run(t, api.New(), "", "-X", "DELETE", "/api/x", "-H", "Accept: application/json") + stdout, err := meshStack.run(t, api.New(), "", "-X", "POST", "/api/x", "-H", "Accept: application/json") require.EqualError(t, err, wantError) assert.JSONEq(t, "{\n \"message\": \"still in use\"\n}\n", stdout) diff --git a/cmd/api/docs.go b/cmd/api/docs.go index 0d7d83c5..090497a8 100644 --- a/cmd/api/docs.go +++ b/cmd/api/docs.go @@ -17,6 +17,8 @@ import ( "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/markdown" + "github.com/meshcloud/meshstack-cli/internal/profile" + "github.com/meshcloud/meshstack-cli/internal/setting" ) //go:embed docs.md.tmpl @@ -67,17 +69,11 @@ The command downloads the API docs from your meshStack, so they list only what y return fmt.Errorf("--%s cannot be combined with a path; see --help", describeFlagName) } var endpoint xurl.URL - if r.target.IsAbs() { - if endpoint, _, err = profileFor(cmd.Context(), r.target); err != nil { - return err - } - if endpoint.URL == nil { - return fmt.Errorf("no stored profile matches %s; give the path relative to the endpoint", r.target.Redacted()) - } - if err = r.cutTo(endpoint); err != nil { - return err - } - } else if endpoint, err = docsEndpoint(cmd.Context()); err != nil { + resolved, _, err := profile.ResolveProfile(cmd.Context(), append(internal.SettingSources(), r.originAsEndpoint()...)) + switch { + case err == nil: + endpoint = resolved.Endpoint + case !errors.Is(err, setting.ErrNoSourceProvidedValue): return err } selector, err := flags.selector(r) diff --git a/cmd/api/profile.go b/cmd/api/profile.go deleted file mode 100644 index 7d520a8a..00000000 --- a/cmd/api/profile.go +++ /dev/null @@ -1,106 +0,0 @@ -package api - -import ( - "context" - "errors" - "fmt" - "log/slog" - "net/url" - - "github.com/meshcloud/meshstack-cli/client/types/xurl" - "github.com/meshcloud/meshstack-cli/cmd/internal" - "github.com/meshcloud/meshstack-cli/internal/meshstack" - "github.com/meshcloud/meshstack-cli/internal/profile" - "github.com/meshcloud/meshstack-cli/internal/setting" -) - -// profileFor fails where a profile or endpoint named by flag or environment does not hold the URL, -// rather than send that profile's credential to another meshStack. The endpoint it returns is the -// one to cut the URL at, and is zero where the session is to create the profile named. -func profileFor(ctx context.Context, requestURL *url.URL) (endpoint xurl.URL, sources setting.Sources, err error) { - settingSources := internal.SettingSources() - profiles, err := profile.LoadProfiles(ctx, profile.LoadProfilesOptions{SettingSources: settingSources}) - if err != nil { - return xurl.URL{}, nil, err - } - - explicitEndpoint, endpointSource, err := settingSources.ResolveSettingWithSource(ctx, meshstack.EndpointSetting) - endpointIsExplicit := err == nil - if err != nil && !errors.Is(err, setting.ErrNoSourceProvidedValue) { - return xurl.URL{}, nil, err - } - // Checked before the profile name: where both are named, the error is about the endpoint, as it - // overrides the profile's. - if endpointIsExplicit { - if _, held := explicitEndpoint.PathTo(requestURL); !held { - return xurl.URL{}, nil, notHeldError(profiles, requestURL, explicitEndpoint, "", endpointSource.Describe(meshstack.EndpointSetting.EnvKey())) - } - } - - name, nameSource, err := settingSources.ResolveSettingWithSource(ctx, profile.NameSetting) - if err != nil { - return xurl.URL{}, nil, err - } - if _, isDefault := nameSource.(setting.DefaultSource); !isDefault { - named, stored := profiles.Profiles[name] - if !stored { - return explicitEndpoint, nil, nil - } - if _, held := named.Endpoint.PathTo(requestURL); !held { - return xurl.URL{}, nil, notHeldError(profiles, requestURL, named.Endpoint, fmt.Sprintf(" of profile '%s'", named.Name), - nameSource.Describe(profile.NameSetting.EnvKey())) - } - if endpointIsExplicit { - return explicitEndpoint, nil, nil - } - return named.Endpoint, nil, nil - } - - var selected profile.Profile - if endpointIsExplicit { - if len(profiles.Profiles) == 0 { - return explicitEndpoint, nil, nil - } - if selected, _, err = profiles.ForEndpoint(explicitEndpoint, requestURL); err != nil { - return xurl.URL{}, nil, err - } - endpoint = explicitEndpoint - } else { - var current bool - if selected, current, err = profiles.Holding(requestURL); err != nil { - return xurl.URL{}, nil, err - } - if !current { - slog.WarnContext(ctx, fmt.Sprintf("Using profile '%s' for '%s' instead of the current profile ('%s') because its endpoint matches the given URL.", - selected, requestURL.Redacted(), profiles.CurrentProfile)) - } - endpoint = selected.Endpoint - } - return endpoint, setting.Sources{setting.FallbackSource{Source: setting.LookupSource{ - MatchingKey: profile.NameSetting.EnvKey(), - Description: "profile whose endpoint matches " + requestURL.Redacted(), - Func: func(context.Context) (string, error) { return string(selected.Name), nil }, - }}}, nil -} - -func docsEndpoint(ctx context.Context) (xurl.URL, error) { - settingSources := internal.SettingSources() - var storedEndpoint setting.Sources - current, _, err := profile.ResolveProfile(ctx, profile.ResolveProfileOptions{SettingSources: settingSources, StoredOnly: true}) - if err == nil { - storedEndpoint = setting.Sources{current.EndpointSource()} - } else if !errors.Is(err, profile.ErrNoStoredProfile) { - return xurl.URL{}, err - } - endpoint, err := settingSources.ResolveSetting(ctx, meshstack.EndpointSetting, storedEndpoint...) - if errors.Is(err, setting.ErrNoSourceProvidedValue) { - return xurl.URL{}, nil - } - return endpoint, err -} - -func notHeldError(profiles profile.Profiles, requestURL *url.URL, endpoint xurl.URL, ofProfile, source string) error { - urlEndpoint, _ := profiles.EndpointHolding(requestURL) - return fmt.Errorf("%s is under endpoint %s, which does not match the endpoint %s%s from %s; leave out %s, or give the path relative to %s", - requestURL.Redacted(), urlEndpoint, endpoint, ofProfile, source, source, endpoint) -} diff --git a/cmd/api/profile_test.go b/cmd/api/profile_test.go deleted file mode 100644 index 2d81a143..00000000 --- a/cmd/api/profile_test.go +++ /dev/null @@ -1,106 +0,0 @@ -package api - -import ( - "log/slog" - "net/url" - "os" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" - - "github.com/meshcloud/meshstack-cli/internal/config" - "github.com/meshcloud/meshstack-cli/internal/logs" - "github.com/meshcloud/meshstack-cli/internal/meshstack" - "github.com/meshcloud/meshstack-cli/internal/profile" -) - -func TestProfileForARequestURL(t *testing.T) { - for _, envKey := range []string{profile.NameSetting.EnvKey(), meshstack.EndpointSetting.EnvKey()} { - t.Setenv(envKey, "") - } - configDir := t.TempDir() - t.Setenv(config.DirectorySetting.EnvKey(), configDir) - require.NoError(t, os.WriteFile(config.Directory(configDir).ProfilesJson(), []byte(`{"version":1,"currentProfile":"local","profiles":{ - "local": {"endpoint":"https://localhost:1337"}, - "a": {"endpoint":"https://meshstack.example.com/a"}, - "a-b": {"endpoint":"https://meshstack.example.com/a/b/"}, - "shared-1": {"endpoint":"https://shared.example.com"}, - "shared-2": {"endpoint":"https://shared.example.com"} - }}`), 0o600)) - resolve := func(t *testing.T, requestURL string) (endpoint string, name profile.Name, warnings []string, err error) { - t.Helper() - parsed, err := url.Parse(requestURL) - require.NoError(t, err) - captured := logs.Capture(t) - cutAt, sources, err := profileFor(t.Context(), parsed) - for _, record := range captured.Records(slog.LevelWarn) { - warnings = append(warnings, record.Message) - } - if err != nil { - return "", "", warnings, err - } - name, err = sources.ResolveSetting(t.Context(), profile.NameSetting) - require.NoError(t, err) - return cutAt.String(), name, warnings, nil - } - - t.Run("a profile other than the current one is picked with a warning that names both", func(t *testing.T) { - endpoint, name, warnings, err := resolve(t, "https://meshstack.example.com/a/api") - - require.NoError(t, err) - assert.Equal(t, "https://meshstack.example.com/a", endpoint) - assert.Equal(t, profile.Name("a"), name) - require.Len(t, warnings, 1) - assert.Contains(t, warnings[0], "'a'") - assert.Contains(t, warnings[0], "'local'") - }) - - t.Run("profiles sharing the endpoint, none of them current, fail until the environment names one", func(t *testing.T) { - _, _, _, err := resolve(t, "https://shared.example.com/api") - - require.ErrorContains(t, err, "'shared-1', 'shared-2'") - - t.Setenv(profile.NameSetting.EnvKey(), "shared-2") - endpoint, name, warnings, err := resolve(t, "https://shared.example.com/api") - - require.NoError(t, err) - assert.Equal(t, "https://shared.example.com", endpoint) - assert.Equal(t, profile.Name("shared-2"), name) - assert.Empty(t, warnings) - }) - - t.Run("an explicit profile is picked over a longer endpoint, and fails where it does not hold the URL", func(t *testing.T) { - t.Setenv(profile.NameSetting.EnvKey(), "a") - endpoint, name, _, err := resolve(t, "https://meshstack.example.com/a/b/api") - - require.NoError(t, err) - assert.Equal(t, "https://meshstack.example.com/a", endpoint) - assert.Equal(t, profile.Name("a"), name) - - _, _, _, err = resolve(t, "https://localhost:1337/api") - - require.ErrorContains(t, err, "https://localhost:1337/api is under endpoint https://localhost:1337, "+ - "which does not match the endpoint https://meshstack.example.com/a of profile 'a' from env "+profile.NameSetting.EnvKey()) - }) - - t.Run("an explicit endpoint fails where it does not hold the URL", func(t *testing.T) { - t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://localhost:1337") - - _, _, _, err := resolve(t, "https://meshstack.example.com/a/api") - - require.ErrorContains(t, err, "https://meshstack.example.com/a/api is under endpoint https://meshstack.example.com/a, "+ - "which does not match the endpoint https://localhost:1337 from env "+meshstack.EndpointSetting.EnvKey()) - }) - - t.Run("with no profile stored, an explicit endpoint that holds the URL leaves the name of the first profile to the session", func(t *testing.T) { - require.NoError(t, os.Remove(config.Directory(configDir).ProfilesJson())) - t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://localhost:1337") - - endpoint, name, _, err := resolve(t, "https://localhost:1337/api") - - require.NoError(t, err) - assert.Equal(t, "https://localhost:1337", endpoint) - assert.Equal(t, profile.Name("default"), name) - }) -} diff --git a/cmd/api/request.go b/cmd/api/request.go index 27194e1c..7b1e0ea6 100644 --- a/cmd/api/request.go +++ b/cmd/api/request.go @@ -1,6 +1,7 @@ package api import ( + "context" "encoding/json/jsontext" "encoding/json/v2" "fmt" @@ -17,6 +18,8 @@ import ( "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/internal/apidocs" + "github.com/meshcloud/meshstack-cli/internal/meshstack" + "github.com/meshcloud/meshstack-cli/internal/setting" ) const ( @@ -81,13 +84,19 @@ func (f *requestFlags) parse(cmd *cobra.Command, args []string) (request, error) return r, nil } -func (r *request) cutTo(endpoint xurl.URL) error { - path, held := endpoint.PathTo(r.target) - if !held { - return fmt.Errorf("%s is not under endpoint %s", r.target.Redacted(), endpoint) +func (r *request) origin() string { + return r.target.Scheme + "://" + r.target.Host +} + +func (r *request) originAsEndpoint() setting.Sources { + if !r.target.IsAbs() { + return nil } - r.target = &url.URL{Path: path, RawQuery: r.target.RawQuery} - return nil + return setting.Sources{setting.LookupSource{ + MatchingKey: meshstack.EndpointSetting.EnvKey(), + Description: "the URL " + r.target.Redacted(), + Func: func(context.Context) (string, error) { return r.origin(), nil }, + }} } func (f *requestFlags) selector(r request) (openapi.Selector, error) { diff --git a/cmd/auth/login_test.go b/cmd/auth/login_test.go index 42717ed6..e38eaa26 100644 --- a/cmd/auth/login_test.go +++ b/cmd/auth/login_test.go @@ -101,9 +101,7 @@ func TestProfileSelection(t *testing.T) { var asked bytes.Buffer source := newProfileSelectionSource(prompt.New(strings.NewReader(tt.answers), &asked), tt.stdin) - ctx := profile.SetSelectionInContext(t.Context(), func() (profile.Selection, error) { - return tt.selection, nil - }) + ctx := profile.SetSelectionInContext(t.Context(), tt.selection) selected, err := source.Lookup(ctx, setting.Profile.EnvKey()) diff --git a/cmd/auth/logout.go b/cmd/auth/logout.go index df7c8c4b..ea7d6528 100644 --- a/cmd/auth/logout.go +++ b/cmd/auth/logout.go @@ -11,6 +11,7 @@ import ( "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" "github.com/meshcloud/meshstack-cli/internal/auth" "github.com/meshcloud/meshstack-cli/internal/profile" + "github.com/meshcloud/meshstack-cli/pkg/setting" ) func newLogout() *cobra.Command { @@ -23,16 +24,18 @@ Without --` + internal.ProfileFlag.Name.String() + `, the command asks which of Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - currentProfile, _, err := profile.ResolveProfile(ctx, profile.ResolveProfileOptions{ - SettingSources: append(internal.SettingSources(), newProfileSelectionSource(prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()), false)), - StoredOnly: true, - }) - if errors.Is(err, profile.ErrNoStoredProfile) { - slog.WarnContext(ctx, "Nothing to log out of: "+err.Error()) + currentProfile, profiles, err := profile.ResolveProfile(ctx, + append(internal.SettingSources(), newProfileSelectionSource(prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()), false))) + if len(profiles.Profiles) == 0 && errors.Is(err, setting.ErrNoSourceProvidedValue) { + slog.WarnContext(ctx, "Nothing to log out of: no profile is stored") return nil } else if err != nil { return err } + if currentProfile.Name == "" { + slog.WarnContext(ctx, "Nothing to log out of: no stored profile is used") + return nil + } if err := auth.Logout(ctx, currentProfile, internal.ResolveClientOptions()); err != nil { return err } diff --git a/cmd/auth/logout_test.go b/cmd/auth/logout_test.go index 09fb39c5..0c893852 100644 --- a/cmd/auth/logout_test.go +++ b/cmd/auth/logout_test.go @@ -22,15 +22,21 @@ func withEmptyConfigDir(t *testing.T) config.Directory { return configDir } -func TestLogoutOfAProfileThatDoesNotExistOnlyWarns(t *testing.T) { +func TestLogoutOfAProfileThatDoesNotExistFails(t *testing.T) { configDir := withEmptyConfigDir(t) + _, err := execute(t, "auth", "logout", "-p", "missing") + + require.ErrorContains(t, err, "there is no profile 'missing'") + assert.NoFileExists(t, configDir.ProfilesJson(), "the logout created no profile") +} + +func TestLogoutWithoutAStoredProfileOnlyWarns(t *testing.T) { + withEmptyConfigDir(t) captured := logs.Capture(t) - _, err := execute(t, "auth", "logout", "-p", "missing") + _, err := execute(t, "auth", "logout") require.NoError(t, err) - assert.Contains(t, captured.String(), "level=WARN") - assert.Contains(t, captured.String(), "no stored profile is named 'missing'") - assert.NoFileExists(t, configDir.ProfilesJson(), "the logout created no profile") + assert.Contains(t, captured.String(), "Nothing to log out of: no profile is stored") } diff --git a/cmd/auth/status_test.go b/cmd/auth/status_test.go index a09cd2cb..1c6887b5 100644 --- a/cmd/auth/status_test.go +++ b/cmd/auth/status_test.go @@ -57,7 +57,7 @@ func TestStatusOfAnApiTokenFromTheEnvironment(t *testing.T) { t.Run("is Markdown where the output is no terminal", func(t *testing.T) { output := executeStatus(t) - assert.Contains(t, output, "| Profile | default |\n| --- | --- |\n") + assert.Contains(t, output, "| Profile | none |\n| --- | --- |\n") assert.Contains(t, output, "| Credential | API token, from env MESHSTACK_API_TOKEN |\n") assert.Contains(t, output, "| | User runner |\n") assert.Contains(t, output, "| meshStack | 2026.40.0 |\n") diff --git a/cmd/buildingblock/tfstate/tfstate.go b/cmd/buildingblock/tfstate/tfstate.go index 383f6556..5db7a8b3 100644 --- a/cmd/buildingblock/tfstate/tfstate.go +++ b/cmd/buildingblock/tfstate/tfstate.go @@ -11,7 +11,6 @@ import ( "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/internal/tfstate" - "github.com/meshcloud/meshstack-cli/pkg/setting" ) var rights = `meshStack gives the state only to a login that has the rights of one of these rows, in the workspace that the login works in: @@ -55,7 +54,7 @@ func New() *cobra.Command { // building block's own workspace, which the runner stores the state under, for every user who has a // default. func openStore(ctx context.Context, meshStack client.Client, buildingBlockUuid uuid.UUID) (tfstate.Store, error) { - workspace, err := setting.ResolveWorkspace(ctx, internal.SettingSources()) + workspace, err := internal.ResolveWorkspace(ctx, internal.IgnoreDefaultWorkspace) if err != nil { return tfstate.Store{}, err } diff --git a/cmd/internal/client.go b/cmd/internal/client.go index 01fb4bbd..66a777e6 100644 --- a/cmd/internal/client.go +++ b/cmd/internal/client.go @@ -36,6 +36,14 @@ func ResolveClient(ctx context.Context, modifiers ...ResolveClientOptionsModifie return auth.ResolveClient(ctx, ResolveClientOptions(modifiers...)) } +func IgnoreDefaultWorkspace(opts *auth.ResolveClientOptions) { + opts.IgnoreDefaultWorkspace = true +} + +func ResolveWorkspace(ctx context.Context, modifiers ...ResolveClientOptionsModifier) (string, error) { + return auth.ResolveWorkspace(ctx, ResolveClientOptions(modifiers...)) +} + func ResolveSession(ctx context.Context, modifiers ...ResolveClientOptionsModifier) (auth.Session, error) { return auth.ResolveSession(ctx, ResolveClientOptions(modifiers...)) } diff --git a/cmd/internal/list.go b/cmd/internal/list.go index e175d97e..e3bb9b33 100644 --- a/cmd/internal/list.go +++ b/cmd/internal/list.go @@ -12,7 +12,6 @@ import ( "github.com/spf13/pflag" "github.com/meshcloud/meshstack-cli/client" - "github.com/meshcloud/meshstack-cli/pkg/auth" ) type ListFlags struct { @@ -32,7 +31,7 @@ func (f *ListFlags) Register(flags *pflag.FlagSet) { // ListWorkspace is the workspace the session works in, which a listing keeps to as every other // command does, and nil where the session works in none. func ListWorkspace(ctx context.Context) (*string, error) { - workspace, err := auth.ResolveWorkspace(ctx, ResolveClientOptions()) + workspace, err := ResolveWorkspace(ctx) if err != nil || workspace == "" { return nil, err } diff --git a/cmd/internal/markdown/credential.md.tmpl b/cmd/internal/markdown/credential.md.tmpl index 4250f86c..c092c9ba 100644 --- a/cmd/internal/markdown/credential.md.tmpl +++ b/cmd/internal/markdown/credential.md.tmpl @@ -2,7 +2,7 @@ {{.OidcLogin.AccessLevel.Label}}{{with .Token}}{{with .AccessLevel}}{{if ne . $.OidcLogin.AccessLevel}}, but the token grants {{.Label}}{{end}}{{end}}{{end}} {{- end -}} {{- define "credential" -}} -| Profile | {{cell .Profile}} | +| Profile | {{with .Profile}}{{cell .}}{{else}}none{{end}} | | --- | --- | | Endpoint | {{cell .Endpoint}} | {{- if ne .Kind "manual"}} @@ -18,9 +18,9 @@ | | {{template "access" .}} | {{- end}} {{- with .OidcLogin}} -| | {{if .SessionEndsAt.IsZero}}Session with no end known{{else if .SessionEnded}}💤 Session ended {{at .SessionEndsAt}}, run `meshstack login --profile {{$.Profile}}`{{else}}Session ends at the latest {{at .SessionEndsAt}}, then run `meshstack login --profile {{$.Profile}}`{{end}} | +| | {{if .SessionEndsAt.IsZero}}Session with no end known{{else if .SessionEnded}}💤 Session ended {{at .SessionEndsAt}}, run `{{$.LoginHint}}`{{else}}Session ends at the latest {{at .SessionEndsAt}}, then run `{{$.LoginHint}}`{{end}} | {{- end}} -| | {{with $token}}{{if .Expired}}Token expired {{at .ExpiresAt}}, {{if eq $.Kind "manual"}}cannot be renewed, run `meshstack login --profile {{$.Profile}} --apitoken`{{else if and $.OidcLogin $.OidcLogin.SessionEnded}}cannot be renewed{{else}}renewed on next use{{end}} +| | {{with $token}}{{if .Expired}}Token expired {{at .ExpiresAt}}, {{if eq $.Kind "manual"}}cannot be renewed, run `{{$.LoginHint}} --apitoken`{{else if and $.OidcLogin $.OidcLogin.SessionEnded}}cannot be renewed{{else}}renewed on next use{{end}} {{- else}}Token expires {{at .ExpiresAt}}{{end}}{{with .Workspace}}, for workspace {{cell .}}{{end}} {{- else}}No token cached yet{{if ne .Kind "manual"}}; one is created on next use{{end}}{{end}} | {{- range $i, $unused := .Unused}} diff --git a/cmd/internal/markdown/markdown_test.go b/cmd/internal/markdown/markdown_test.go index a5545632..95f31097 100644 --- a/cmd/internal/markdown/markdown_test.go +++ b/cmd/internal/markdown/markdown_test.go @@ -23,7 +23,7 @@ var credentialOnly = Parse("test", `{{template "credential" .}}`) func TestABrowserLoginShowsItsUserAccessAndSessionEnd(t *testing.T) { synctest.Test(t, func(t *testing.T) { status := auth.CredentialStatus{ - Profile: "dev", Endpoint: xurl.MustParsef("https://meshstack.example.com"), + Profile: "dev", LoginHint: "meshstack login --profile dev", Endpoint: xurl.MustParsef("https://meshstack.example.com"), Kind: credential.OidcLoginName, Sources: []string{"file credentials/dev.json"}, Workspace: "ops", Token: &auth.TokenStatus{ @@ -77,7 +77,7 @@ func TestAnApiKeyShowsItsClientIdAndNoCachedTokenYet(t *testing.T) { func TestAnExpiredApiTokenSaysItCannotBeRenewed(t *testing.T) { status := auth.CredentialStatus{ - Profile: "run", Endpoint: xurl.MustParsef("https://meshstack.example.com"), + Profile: "run", LoginHint: "meshstack login --profile run", Endpoint: xurl.MustParsef("https://meshstack.example.com"), Kind: credential.ManualName, Sources: []string{"env MESHSTACK_API_TOKEN"}, Token: &auth.TokenStatus{ExpiresAt: time.Now().Add(-time.Hour), Workspace: "ops", ClientId: "11111111-45bf-42ba-a965-2097b9d0d181"}, } diff --git a/cmd/meshstack/meshstack.go b/cmd/meshstack/meshstack.go index 720e82ae..884e3fb7 100644 --- a/cmd/meshstack/meshstack.go +++ b/cmd/meshstack/meshstack.go @@ -51,7 +51,7 @@ Start with 'meshstack login'. It logs you in and stores the login in a profile. AI agents: read https://docs.meshcloud.io/agent-context/index.md before you act, starting with its guardrails. The skill for this CLI is https://github.com/meshcloud/meshstack-cli/blob/main/skills/meshstack-cli/SKILL.md. -A command reads the endpoint, the profile and the workspace from its flag, else from the environment variable that the flag's help lists, else from the profile. A profile stores an endpoint and a default workspace. If you choose no profile, the command uses the profile whose endpoint matches, else the current profile, which 'meshstack login' sets. +A command reads the endpoint, the profile and the workspace from its flag, else from the environment variable that the flag's help lists, else from the profile. A profile stores an endpoint and a default workspace. If you choose no profile, the command uses the current profile, which 'meshstack login' sets. If you give another endpoint than the current profile has, the command uses the only profile with that endpoint. AI agents and scripts: add --%s %s to a list or show command to get JSON. 'meshstack api' sends a request to any path of the meshStack API, and 'meshstack api-docs' describes that path. diff --git a/cmd/profile/form.go b/cmd/profile/form.go index b2533e96..ecf824dc 100644 --- a/cmd/profile/form.go +++ b/cmd/profile/form.go @@ -92,8 +92,7 @@ func parseEndpoint(value string) (endpoint xurl.URL, err error) { if value == "" { return endpoint, errors.New("a profile needs an endpoint") } - err = endpoint.UnmarshalText([]byte(value)) - return + return meshstack.EndpointSetting.Parse(value) } // localEndpoint is meshfed-api of the local stack in ../meshfed-release, on Spring's default port. @@ -288,7 +287,7 @@ func (f *form) lookUpWorkspaces(ctx context.Context, profiles profile.Profiles) endpoint := f.endpoint var asked []profile.Profile if parsed, err := parseEndpoint(endpoint); err == nil { - asked = profiles.MatchingEndpoint(parsed) + asked = profiles.ForEndpoint(parsed) } return func() tea.Msg { return workspacesLookedUp{form: f, endpoint: endpoint, names: knownWorkspaces(ctx, asked)} diff --git a/cmd/profile/form_test.go b/cmd/profile/form_test.go index a5c48c6f..2c96db74 100644 --- a/cmd/profile/form_test.go +++ b/cmd/profile/form_test.go @@ -57,7 +57,7 @@ func TestTheWorkspacesThatTheProfilesAtTheEndpointReachAreSuggested(t *testing.T require.NoError(t, credentials.Store(t.Context())) // The logged-out profile is asked as well, and fails without a call. - assert.Equal(t, []string{"app-team", "platform-team"}, knownWorkspaces(t.Context(), profiles.MatchingEndpoint(endpoint))) - assert.Empty(t, profiles.MatchingEndpoint(xurl.MustParsef("https://unknown.example.io"))) + assert.Equal(t, []string{"app-team", "platform-team"}, knownWorkspaces(t.Context(), profiles.ForEndpoint(endpoint))) + assert.Empty(t, profiles.ForEndpoint(xurl.MustParsef("https://unknown.example.io"))) assert.Equal(t, int64(1), server.Counts().Logins) } diff --git a/cmd/profile/profile.go b/cmd/profile/profile.go index 2d93965d..1dc40f05 100644 --- a/cmd/profile/profile.go +++ b/cmd/profile/profile.go @@ -26,7 +26,7 @@ In a terminal, this command opens an interactive list where you can add, edit an return cmd.Help() } return withLockedProfiles(ctx, func(profiles profile.Profiles) error { - selection, err := profiles.SelectionFor(ctx, profile.ResolveProfileOptions{SettingSources: internal.SettingSources()}) + selection, err := profiles.SelectionFor(ctx, internal.SettingSources()) if err != nil { return err } diff --git a/cmd/profile/select_profile.go b/cmd/profile/select_profile.go index 0d9c9f98..8b9d6656 100644 --- a/cmd/profile/select_profile.go +++ b/cmd/profile/select_profile.go @@ -18,7 +18,7 @@ func selectProfile(ctx context.Context, cmd *cobra.Command, p prompt.Prompt, pro selected, err = profiles.Find(profile.Name(internal.ProfileFlag.Value)) return selected, true, err } - selection, err := profiles.SelectionFor(ctx, profile.ResolveProfileOptions{SettingSources: internal.SettingSources()}) + selection, err := profiles.SelectionFor(ctx, internal.SettingSources()) if err != nil { return nil, false, err } diff --git a/cmd/profile/show.go b/cmd/profile/show.go index 7e54282b..6d38ed44 100644 --- a/cmd/profile/show.go +++ b/cmd/profile/show.go @@ -3,7 +3,6 @@ package profile import ( "context" _ "embed" - "fmt" "log/slog" "github.com/spf13/cobra" @@ -11,7 +10,6 @@ import ( "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/markdown" "github.com/meshcloud/meshstack-cli/internal/auth" - "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/profile" ) @@ -24,7 +22,7 @@ var showTemplate = markdown.Parse("show", showTemplateText) type entry struct { *profile.Profile `json:",inline"` - Name profile.Name `json:"name"` + Name profile.Name `json:"name,omitzero"` Current bool `json:"current"` } @@ -35,7 +33,6 @@ func entryOf(profiles profile.Profiles, p *profile.Profile) entry { type shown struct { entry `json:",inline"` - // New is the profile a first login would create, which is not stored yet. New bool `json:"new,omitzero"` Status *auth.CredentialStatus `json:"status,omitzero"` @@ -65,26 +62,16 @@ func newShow() *cobra.Command { Short: "Show a profile and the status of its stored credential", Long: `Show the profile that other commands would use, and the status of its stored credential. Flags and environment variables can override that credential. -If the profile does not exist yet, the command shows what the first login would create, without saving anything.`, +If the command uses no stored profile for the endpoint, it shows the endpoint alone.`, Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - opts := profile.ResolveProfileOptions{SettingSources: internal.SettingSources(), EndpointOptional: true} - stored, err := profile.LoadProfiles(ctx, profile.LoadProfilesOptions{SettingSources: opts.SettingSources}) + shownProfile, stored, err := profile.ResolveProfile(ctx, internal.SettingSources()) if err != nil { return err } - shownProfile, _, err := profile.ResolveProfile(ctx, opts) - if err != nil { - return err - } - if endpoint, source, err := opts.ResolveSettingWithSource(ctx, meshstack.EndpointSetting); err == nil && !endpoint.Equal(shownProfile.Endpoint) { - slog.WarnContext(ctx, fmt.Sprintf("Profile '%s' has the endpoint '%s', which does not match the endpoint '%s' from %s, so commands fail with this profile", - shownProfile.Name, shownProfile.Endpoint, endpoint, source.Describe(meshstack.EndpointSetting.EnvKey()))) - } s := showOf(ctx, stored, shownProfile) - _, isStored := stored.Profiles[shownProfile.Name] - s.New = !isStored + s.New = shownProfile.Name == "" return output.Show(cmd.OutOrStdout(), showTemplate, s) }, } diff --git a/cmd/profile/show.md.tmpl b/cmd/profile/show.md.tmpl index f3b2e372..aa820623 100644 --- a/cmd/profile/show.md.tmpl +++ b/cmd/profile/show.md.tmpl @@ -2,15 +2,15 @@ {{- with .Status -}} {{template "credential" .}} {{- else -}} -| Profile | {{cell .Name}} | +| Profile | {{with .Name}}{{cell .}}{{else}}none{{end}} | | --- | --- | | Endpoint | {{with .Endpoint.URL}}{{cell .}}{{else}}none{{end}} | | Default workspace | {{or .DefaultWorkspace "none"}} | -| Credential | none, run `meshstack login --profile {{.Name}}` | +| Credential | none, run `{{.LoginHint}}` | {{- end}} {{- if .New}} -This profile is not saved yet. It is saved on the first login. +No stored profile is used. A login saves one. {{- else if .Current}} This is the current profile. diff --git a/cmd/profile/show_test.go b/cmd/profile/show_test.go index 8925dfe0..958d4115 100644 --- a/cmd/profile/show_test.go +++ b/cmd/profile/show_test.go @@ -86,42 +86,28 @@ func TestShow(t *testing.T) { require.NoError(t, err) assert.Contains(t, output, "| Profile | dev |\n") assert.Contains(t, output, "| Credential | API token, from file ") - assert.Contains(t, output, "| | No token cached yet |\n") + assert.Contains(t, output, "| | Token expires 2100-01-01") assert.Contains(t, output, "This is the current profile.") }) - t.Run("shows the current profile with a warning where it is for another endpoint, and that endpoint has several profiles", func(t *testing.T) { + t.Run("shows the endpoint alone where several profiles have it and none of them is current", func(t *testing.T) { require.NoError(t, profiles.Put(t.Context(), nil, profile.Profile{Name: "staging", Endpoint: endpointB})) - captured := logs.Capture(t) output, err := execute(t, "", "show", "--endpoint", "https://b.example.io") require.NoError(t, err) - assert.Contains(t, output, "| Profile | dev |\n") - assert.Contains(t, captured.String(), "Profile 'dev' has the endpoint 'https://a.example.io', which does not match the endpoint 'https://b.example.io' from flag --endpoint, so commands fail with this profile") - }) - - t.Run("shows the profile a first command would create, without storing it, where no profile is current", func(t *testing.T) { - profiles.CurrentProfile = "" - require.NoError(t, profiles.Store(t.Context())) - - output, err := execute(t, "", "show", "--endpoint", "https://b.example.io") - - require.NoError(t, err) - assert.Contains(t, output, "| Profile | default |\n| --- | --- |\n| Endpoint | https://b.example.io |\n") - assert.Contains(t, output, "This profile is not saved yet. It is saved on the first login.") + assert.Contains(t, output, "| Profile | none |\n| --- | --- |\n| Endpoint | https://b.example.io |\n") + assert.Contains(t, output, "| Credential | none, run `meshstack login --endpoint https://b.example.io` |\n") + assert.Contains(t, output, "No stored profile is used. A login saves one.") requireStoredNames(t, "dev", "prod", "staging") }) - t.Run("shows the profile a first command would create without any profile or endpoint", func(t *testing.T) { + t.Run("fails without any profile or endpoint", func(t *testing.T) { emptyConfigDir(t) - output, err := execute(t, "", "show") + _, err := execute(t, "", "show") - require.NoError(t, err) - assert.Contains(t, output, "| Profile | default |\n| --- | --- |\n| Endpoint | none |\n| Default workspace | none |\n") - assert.Contains(t, output, "This profile is not saved yet. It is saved on the first login.") - requireStoredNames(t) + require.ErrorContains(t, err, "or run 'meshstack login'") }) } diff --git a/cmd/profile/store_test.go b/cmd/profile/store_test.go index 37a3e812..eb093e00 100644 --- a/cmd/profile/store_test.go +++ b/cmd/profile/store_test.go @@ -13,6 +13,7 @@ import ( "github.com/meshcloud/meshstack-cli/internal/auth/credential" "github.com/meshcloud/meshstack-cli/internal/logs" "github.com/meshcloud/meshstack-cli/internal/profile" + "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" ) var ( @@ -44,6 +45,7 @@ func storeCredentials(t *testing.T, p *profile.Profile) { credentials, err := p.Credentials(t.Context()) require.NoError(t, err) credentials.Manual = &credential.Manual{Endpoint: p.Endpoint} + require.NoError(t, credentials.Manual.Token.UnmarshalText([]byte(fakemeshstack.Token))) require.NoError(t, credentials.Store(t.Context())) } diff --git a/internal/auth/cache.go b/internal/auth/cache.go index 70a83756..3c9c3983 100644 --- a/internal/auth/cache.go +++ b/internal/auth/cache.go @@ -9,6 +9,7 @@ import ( "log/slog" "os" "reflect" + "sync" "github.com/meshcloud/meshstack-cli/internal/auth/credential" "github.com/meshcloud/meshstack-cli/internal/json" @@ -18,6 +19,8 @@ import ( const cacheVersion = 1 +var warnOfFailedCacheWrite sync.Once + // cacheFile carries the identity the cached tokens were minted for, so that a cache // written by another api key or after a rotated secret is dropped instead of sent. type cacheFile struct { @@ -33,21 +36,17 @@ type Credential struct { // Sources must never carry a secret, as a status shows them. Sources []string - // Stored is set for the credential the profile stores, and not for one that settings provide. - Stored bool - // bringsItsToken is set for an API token that settings provide. A manual credential's identity - // is its endpoint alone, so the profile's cache would match it and replace that token with the - // one a login stored. - bringsItsToken bool - - profile profile.Name + locker lock.Locker cachePath string } func CacheFor(p *profile.Profile, cred credential.Credential) Credential { - path := p.ConfigDir.CredentialsCacheJsonFor(p.Name, cred.Name()) - return Credential{Credential: cred, profile: p.Name, locker: lock.New(path), cachePath: path} + var path string + if _, isToken := cred.(*credential.Manual); !isToken && p.Name != "" { + path = p.ConfigDir.CredentialsCacheJsonFor(p.Name, cred.Name()) + } + return Credential{Credential: cred, locker: lock.New(path), cachePath: path} } func (c Credential) Load(ctx context.Context) error { @@ -75,7 +74,9 @@ func (c Credential) Modify(ctx context.Context, action func() error) error { err = action() if matched { if writeErr := c.write(ctx); writeErr != nil { - slog.DebugContext(ctx, fmt.Sprintf("Cannot update cache %s, continuing with the token in memory: %s", c.cachePath, writeErr.Error())) + warnOfFailedCacheWrite.Do(func() { + slog.WarnContext(ctx, fmt.Sprintf("Cannot update cache %s, continuing with the token in memory: %s", c.cachePath, writeErr.Error())) + }) } } return err @@ -119,7 +120,7 @@ func (c Credential) WriteOver(ctx context.Context) (restore func(context.Context } func (c Credential) read(ctx context.Context) (matched bool, err error) { - if c.bringsItsToken { + if c.cachePath == "" { return false, nil } var file cacheFile @@ -133,8 +134,8 @@ func (c Credential) read(ctx context.Context) (matched bool, err error) { switch { case file.Version != cacheVersion: // Not an error: the cache only saves minting a token, and a login writes a compatible one. - slog.WarnContext(ctx, fmt.Sprintf("Ignoring cache %s of version %d, as this meshstack reads version %d; run 'meshstack login --profile %s' to update it", - c.cachePath, file.Version, cacheVersion, c.profile)) + slog.WarnContext(ctx, fmt.Sprintf("Ignoring cache %s of version %d, as this meshstack reads version %d; a login updates it", + c.cachePath, file.Version, cacheVersion)) case file.Identity != c.Identity().Hash: // Debug, not Warn: a credential from the environment next to the profile's own is normal. slog.DebugContext(ctx, fmt.Sprintf("Ignoring cache %s, it was minted for another identity", c.cachePath)) @@ -148,6 +149,9 @@ func (c Credential) read(ctx context.Context) (matched bool, err error) { } func (c Credential) write(ctx context.Context) (err error) { + if c.cachePath == "" { + return nil + } file := cacheFile{ Version: cacheVersion, Identity: c.Identity().Hash, diff --git a/internal/auth/cache_test.go b/internal/auth/cache_test.go index 80b13843..956cb9eb 100644 --- a/internal/auth/cache_test.go +++ b/internal/auth/cache_test.go @@ -76,7 +76,7 @@ func TestCache(t *testing.T) { require.NoError(t, auth.CacheFor(p, loggedIn).Load(t.Context())) assert.Nil(t, loggedIn.Cache) assert.Contains(t, captured.String(), "level=WARN") - assert.Contains(t, captured.String(), "run 'meshstack login --profile cache-test' to update it") + assert.Contains(t, captured.String(), "a login updates it") loggedIn.Cache = withToken(token) require.NoError(t, auth.CacheFor(p, loggedIn).Write(t.Context())) diff --git a/internal/auth/credential/manual.go b/internal/auth/credential/manual.go index 66a7e6cd..a65759b8 100644 --- a/internal/auth/credential/manual.go +++ b/internal/auth/credential/manual.go @@ -13,16 +13,7 @@ var _ Credential = &Manual{} type Manual struct { Endpoint xurl.URL `json:"endpoint"` - Cache *struct { - Token jwt.JWT `json:"token"` - } `json:"-"` -} - -func NewManual(endpoint xurl.URL, token jwt.JWT) *Manual { - manual := &Manual{Endpoint: endpoint} - newCache(manual) - manual.Cache.Token = token - return manual + Token jwt.JWT `json:"token"` } func (manual *Manual) Name() Name { @@ -34,12 +25,12 @@ func (manual *Manual) Identity() Identity { } func (manual *Manual) CachedToken(_ context.Context, _ getWorkspaceFunc) (jwt.JWT, bool) { - if manual.Cache == nil { - return jwt.JWT{}, false - } - return manual.Cache.Token, true + return manual.Token, true } func (manual *Manual) RefreshCachedToken(_ context.Context, _ http.Client, _ getWorkspaceFunc) error { + if !manual.Token.GetClaim(jwt.ExpiryClaim).Expired(0) { + return nil + } return fmt.Errorf("manual method cannot be refreshed; provide new with 'meshstack login --endpoint %s --apitoken [--stdin]'", manual.Endpoint) } diff --git a/internal/auth/credential_manual.go b/internal/auth/credential_manual.go index 453a593b..46c6d994 100644 --- a/internal/auth/credential_manual.go +++ b/internal/auth/credential_manual.go @@ -30,7 +30,7 @@ func (s Session) resolveManualCredential(ctx context.Context, settingSources set return Credential{}, apiTokenErr } slog.DebugContext(ctx, fmt.Sprintf("Using setting %s as manual credential", ApiTokenSetting.EnvKey())) - manual := CacheFor(s.CurrentProfile, credential.NewManual(s.CurrentProfile.Endpoint, apiToken)) - manual.Sources, manual.bringsItsToken = []string{source.Describe(ApiTokenSetting.EnvKey())}, true + manual := CacheFor(s.CurrentProfile, &credential.Manual{Endpoint: s.CurrentProfile.Endpoint, Token: apiToken}) + manual.Sources = []string{source.Describe(ApiTokenSetting.EnvKey())} return manual, nil } diff --git a/internal/auth/credentials.go b/internal/auth/credentials.go index 5202a838..675c0d51 100644 --- a/internal/auth/credentials.go +++ b/internal/auth/credentials.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/meshcloud/meshstack-cli/internal/auth/credential" + "github.com/meshcloud/meshstack-cli/internal/profile" "github.com/meshcloud/meshstack-cli/internal/setting" ) @@ -53,9 +54,21 @@ func (s Session) resolveCredentials(ctx context.Context, opts ResolveSessionOpti func (s Session) storedCredential(ctx context.Context, noSourceErrs []error) (Credential, error) { currentProfile := s.CurrentProfile + if currentProfile.Name == "" { + var names []string + for _, p := range s.profiles.ForEndpoint(currentProfile.Endpoint) { + names = append(names, "'"+string(p.Name)+"'") + } + noCredential := fmt.Errorf("no credential for the endpoint %s; run '%s'", currentProfile.Endpoint, s.profiles.LoginHint("", currentProfile.Endpoint)) + if len(names) > 0 { + noCredential = fmt.Errorf("no credential for the endpoint %s, and none of its profiles %s is the current one; use --profile or %s to choose one", + currentProfile.Endpoint, strings.Join(names, ", "), profile.NameSetting.EnvKey()) + } + return Credential{}, errors.Join(append([]error{noCredential}, noSourceErrs...)...) + } if currentProfile.Credential == "" { return Credential{}, errors.Join(append([]error{ - fmt.Errorf("profile '%s' selects no credential; run 'meshstack login --profile %s'", currentProfile, currentProfile), + fmt.Errorf("profile '%s' selects no credential; run '%s'", currentProfile, currentProfile.LoginHint()), }, noSourceErrs...)...) } creds, err := currentProfile.Credentials(ctx) @@ -64,11 +77,11 @@ func (s Session) storedCredential(ctx context.Context, noSourceErrs []error) (Cr } current := creds.ByName(currentProfile.Credential) if current == nil { - return Credential{}, fmt.Errorf("profile '%s' selects credential '%s', but %s contains none; run 'meshstack login --profile %s'", - currentProfile, currentProfile.Credential, creds.FilePath, currentProfile) + return Credential{}, fmt.Errorf("profile '%s' selects credential '%s', but %s contains none; run '%s'", + currentProfile, currentProfile.Credential, creds.FilePath, currentProfile.LoginHint()) } slog.DebugContext(ctx, fmt.Sprintf("Using credential %s of profile %s", currentProfile.Credential, currentProfile)) stored := CacheFor(currentProfile, current) - stored.Sources, stored.Stored = []string{"file " + creds.FilePath}, true + stored.Sources = []string{"file " + creds.FilePath} return stored, nil } diff --git a/internal/auth/login.go b/internal/auth/login.go index 41cce365..e49a19ab 100644 --- a/internal/auth/login.go +++ b/internal/auth/login.go @@ -22,7 +22,7 @@ type StoreFunc func(context.Context) error // fails, it holds nothing. An unlock before the credential is stored also takes back the tokens // that the login cached. func Login(ctx context.Context, withAuth credential.Name, opts ResolveSessionOptions) (_ Session, _ StoreFunc, unlock func() error, err error) { - session, profiles, err := newSession(ctx, opts, true) + profiles, err := profile.LoadProfiles(ctx, profile.LoadProfilesOptions{SettingSources: opts.SettingSources, ExclusiveLock: true}) if err != nil { return Session{}, nil, nil, err } @@ -31,6 +31,14 @@ func Login(ctx context.Context, withAuth credential.Name, opts ResolveSessionOpt err = errors.Join(err, profiles.Unlock()) } }() + currentProfile, err := profiles.Resolve(ctx, opts.SettingSources, true) + if err != nil { + return Session{}, nil, nil, err + } + session, err := newSessionFor(ctx, currentProfile, opts) + if err != nil { + return Session{}, nil, nil, err + } var creds profile.Credentials creds, err = session.CurrentProfile.Credentials(ctx) @@ -57,7 +65,7 @@ func Login(ctx context.Context, withAuth credential.Name, opts ResolveSessionOpt slog.DebugContext(ctx, fmt.Sprintf("Setting credential %s in profile", withAuth)) session.CurrentProfile.Credential = withAuth - resolved.Sources, resolved.Stored = []string{"file " + creds.FilePath}, true + resolved.Sources = []string{"file " + creds.FilePath} session.Credential = resolved restoreCache, err := session.Credential.WriteOver(ctx) if err != nil { diff --git a/internal/auth/session.go b/internal/auth/session.go index b9892d97..67ab0e5f 100644 --- a/internal/auth/session.go +++ b/internal/auth/session.go @@ -23,6 +23,7 @@ type Session struct { Client func() (client.Client, error) MeshInfo func() (client.MeshInfo, error) + profiles profile.Profiles getWorkspace func() (meshstack.Workspace, error) httpClient http.Client } @@ -40,10 +41,15 @@ type ( ) func ResolveSession(ctx context.Context, opts ResolveSessionOptions) (Session, error) { - session, _, err := newSession(ctx, opts, false) + currentProfile, profiles, err := profile.ResolveProfile(ctx, opts.SettingSources) if err != nil { return Session{}, err } + session, err := newSessionFor(ctx, currentProfile, opts) + if err != nil { + return Session{}, err + } + session.profiles = profiles resolved, err := session.resolveCredentials(ctx, opts) if err != nil { return Session{}, err @@ -65,6 +71,9 @@ func ResolveSession(ctx context.Context, opts ResolveSessionOptions) (Session, e // works in that workspace, while an API key works in the one that owns it. func (s Session) Scope() string { scope := "profile " + string(s.CurrentProfile.Name) + if s.CurrentProfile.Name == "" { + scope = "endpoint " + s.CurrentProfile.Endpoint.String() + } if _, browserLogin := s.Credential.Credential.(*credential.OidcLogin); browserLogin { if workspace, err := s.getWorkspace(); err == nil && workspace != meshstack.NoWorkspace { scope += " working in workspace " + string(workspace) @@ -88,35 +97,6 @@ func StoredSession(ctx context.Context, p *profile.Profile, opts ResolveSessionO return session.withCredential(ctx, stored, opts) } -// newSession leaves the profiles locked with exclusiveLock only where it succeeds. -func newSession(ctx context.Context, opts ResolveSessionOptions, exclusiveLock bool) (_ Session, _ profile.Profiles, err error) { - currentProfile, profiles, err := profile.ResolveProfile(ctx, profile.ResolveProfileOptions{ - SettingSources: opts.SettingSources, - ExclusiveLock: exclusiveLock, - }) - if err != nil { - return Session{}, profile.Profiles{}, err - } - defer func() { - if err != nil { - err = errors.Join(err, profiles.Unlock()) - } - }() - - endpoint, err := opts.ResolveSetting(ctx, meshstack.EndpointSetting, currentProfile.EndpointSource()) - if err != nil { - return Session{}, profile.Profiles{}, err - } else if !endpoint.Equal(currentProfile.Endpoint) { - // this prevents accidentally sending credentials to the wrong endpoint - return Session{}, profile.Profiles{}, fmt.Errorf("profile '%s' has the endpoint '%s', which does not match the endpoint '%s' of this command; "+ - "use --profile to choose a profile for that endpoint, or create one with 'meshstack login --endpoint %s --profile '", - currentProfile, currentProfile.Endpoint, endpoint, endpoint) - } - - session, err := newSessionFor(ctx, currentProfile, opts) - return session, profiles, err -} - // HttpClient is for a request that the meshStack client does not make, such as the download of the // API docs. It carries the user agent of the front end, as the session's client does. func (opts ResolveSessionOptions) HttpClient() (http.Client, error) { @@ -199,16 +179,14 @@ func (s Session) buildClient(ctx context.Context, opts ResolveSessionOptions) (c // ResolveWorkspace resolves the workspace that a session of opts works in, as ResolveSession does, // and is NoWorkspace where no setting names one and the profile has no default workspace. func ResolveWorkspace(ctx context.Context, opts ResolveSessionOptions) (meshstack.Workspace, error) { - stored, _, err := profile.ResolveProfile(ctx, profile.ResolveProfileOptions{SettingSources: opts.SettingSources, StoredOnly: true}) - var defaultWorkspace setting.Source - switch { - case err == nil: - if !opts.IgnoreDefaultWorkspace { - defaultWorkspace = stored.WorkspaceSource() - } - case !errors.Is(err, profile.ErrNoStoredProfile): + currentProfile, _, err := profile.ResolveProfile(ctx, opts.SettingSources) + if err != nil { return meshstack.NoWorkspace, err } + var defaultWorkspace setting.Source + if !opts.IgnoreDefaultWorkspace { + defaultWorkspace = currentProfile.WorkspaceSource() + } workspace, err := opts.ResolveSetting(ctx, meshstack.WorkspaceSetting, defaultWorkspace) if errors.Is(err, setting.ErrNoSourceProvidedValue) { return meshstack.NoWorkspace, nil diff --git a/internal/auth/session_test.go b/internal/auth/session_test.go index 513451fa..c4675e76 100644 --- a/internal/auth/session_test.go +++ b/internal/auth/session_test.go @@ -54,7 +54,7 @@ func TestSessionResolutionSaysWhyItFails(t *testing.T) { t.Run("without any credential", func(t *testing.T) { _, err := auth.ResolveSession(t.Context(), testSessionOpts) - require.ErrorContains(t, err, "selects no credential") + require.ErrorContains(t, err, "no credential for the endpoint "+server.URL+"; run 'meshstack login --endpoint "+server.URL+"'") require.ErrorContains(t, err, auth.ApiTokenSetting.EnvKey()) require.ErrorContains(t, err, auth.ApiKeyClientIdSetting.EnvKey()) require.ErrorContains(t, err, auth.ApiKeyClientSecretSetting.EnvKey()) @@ -118,7 +118,7 @@ func TestSessionOfAStoredApiKey(t *testing.T) { storeLogin(t, credential.ApiKeyName) t.Setenv(profile.NameSetting.EnvKey(), "") - current, _, err := profile.ResolveProfile(t.Context(), profile.ResolveProfileOptions{}) + current, _, err := profile.ResolveProfile(t.Context(), nil) require.NoError(t, err) assert.Equal(t, profile.Name("dev"), current.Name) }) @@ -299,16 +299,19 @@ func TestSessionWarnsWhenTheEnvironmentOverridesTheStoredLogin(t *testing.T) { t.Run("another profile named in the environment overrides the current one", func(t *testing.T) { t.Setenv(profile.NameSetting.EnvKey(), "dev") + setApiKeyEnv(t, testApiKey1) + storeLogin(t, credential.ApiKeyName) + t.Setenv(profile.NameSetting.EnvKey(), "default") captured := logs.Capture(t) - _, _, err := profile.ResolveProfile(t.Context(), profile.ResolveProfileOptions{}) + _, _, err := profile.ResolveProfile(t.Context(), nil) require.NoError(t, err) lines := captured.Lines(slog.LevelWarn) require.Len(t, lines, 1) - assert.Contains(t, lines[0], "'dev', which overrides 'default' from the current profile") + assert.Contains(t, lines[0], "'default', which overrides 'dev' from the current profile") }) t.Run("a workspace in the environment overrides the default workspace", func(t *testing.T) { - current, profiles, err := profile.ResolveProfile(t.Context(), profile.ResolveProfileOptions{}) + current, profiles, err := profile.ResolveProfile(t.Context(), nil) require.NoError(t, err) current.DefaultWorkspace = "stored-workspace" require.NoError(t, profiles.Store(t.Context())) @@ -319,6 +322,6 @@ func TestSessionWarnsWhenTheEnvironmentOverridesTheStoredLogin(t *testing.T) { require.NoError(t, err) lines := captured.Lines(slog.LevelWarn) require.Len(t, lines, 1) - assert.Contains(t, lines[0], "'env-workspace', which overrides 'stored-workspace' from the default workspace in profile default") + assert.Contains(t, lines[0], "'env-workspace', which overrides 'stored-workspace' from the default workspace in profile dev") }) } diff --git a/internal/auth/status.go b/internal/auth/status.go index 8278183d..fa5641b1 100644 --- a/internal/auth/status.go +++ b/internal/auth/status.go @@ -22,7 +22,8 @@ import ( // CredentialStatus never carries a secret. A part that cannot be read is logged as a warning and // left at its zero value. type CredentialStatus struct { - Profile profile.Name `json:"profile"` + Profile profile.Name `json:"profile,omitzero"` + LoginHint string `json:"-"` Endpoint xurl.URL `json:"endpoint"` Kind credential.Name `json:"credential"` Sources []string `json:"sources"` @@ -98,10 +99,11 @@ type ApiKeyStatus struct { // renews a browser login, which would rotate its refresh token. func (s Session) Status(ctx context.Context) CredentialStatus { status := CredentialStatus{ - Profile: s.CurrentProfile.Name, - Endpoint: s.CurrentProfile.Endpoint, - Kind: s.Credential.Name(), - Sources: s.Credential.Sources, + Profile: s.CurrentProfile.Name, + LoginHint: s.CurrentProfile.LoginHint(), + Endpoint: s.CurrentProfile.Endpoint, + Kind: s.Credential.Name(), + Sources: s.Credential.Sources, } workspace, err := s.getWorkspace() if err != nil && !errors.Is(err, setting.ErrNoSourceProvidedValue) { @@ -139,7 +141,7 @@ func (s Session) unusedCredentials(ctx context.Context, workspace meshstack.Work } for _, name := range credential.Names { cred := stored.ByName(name) - if cred == nil || name == s.Credential.Name() && s.Credential.Stored { + if cred == nil || cred.Identity() == s.Credential.Identity() { continue } if err := CacheFor(s.CurrentProfile, cred).Load(ctx); err != nil { diff --git a/internal/lock/lock.go b/internal/lock/lock.go index c0eea362..fbeb9bed 100644 --- a/internal/lock/lock.go +++ b/internal/lock/lock.go @@ -13,6 +13,9 @@ import ( const retryDelay = 25 * time.Millisecond func New(path string) Locker { + if path == "" { + return Locker{m: &sync.RWMutex{}} + } return Locker{m: &sync.RWMutex{}, pathLock: path + ".lock"} } @@ -55,6 +58,9 @@ func (l Locker) lock(ctx context.Context, read bool) (unlock func() error, err e if err := inMemory.SpinLock(ctx); err != nil { return nil, err } + if l.pathLock == "" { + return sync.OnceValue(inMemory.Unlock), nil + } file := l.fileLocker(read) if err := file.SpinLock(ctx); err != nil { return nil, errors.Join(err, inMemory.Unlock()) diff --git a/internal/meshstack/settings.go b/internal/meshstack/settings.go index 61dbd1dc..a0d55ae7 100644 --- a/internal/meshstack/settings.go +++ b/internal/meshstack/settings.go @@ -16,7 +16,13 @@ var EndpointSetting = setting.Setting[xurl.URL]{ return fmt.Sprintf("The URL of the meshStack API, such as `https://api.example.meshcloud.io`, "+ "also read from `%s`, else taken from the current profile.", envKey) }, - Parse: setting.ParseTextUnmarshaler[xurl.URL], + Parse: func(s string) (xurl.URL, error) { + endpoint, err := setting.ParseTextUnmarshaler[xurl.URL](s) + if err == nil && (endpoint.Path != "" || endpoint.RawQuery != "" || endpoint.Fragment != "" || endpoint.User != nil) { + err = fmt.Errorf("an endpoint is a scheme and a host, such as https://api.example.meshcloud.io, and '%s' has more than that", endpoint.Redacted()) + } + return endpoint, err + }, } // SkipVersionCheckSetting skips both the minimum backend version check and the check for a newer diff --git a/internal/profile/lock_test.go b/internal/profile/lock_test.go index 2064a710..75ab43bc 100644 --- a/internal/profile/lock_test.go +++ b/internal/profile/lock_test.go @@ -64,15 +64,6 @@ func TestTheExclusiveLockOfTheProfiles(t *testing.T) { assert.False(t, lockIsFree(t, dir), "the other command still holds the lock") }) - t.Run("is released where ResolveProfile fails", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "missing") - - _, _, err := ResolveProfile(t.Context(), ResolveProfileOptions{StoredOnly: true, ExclusiveLock: true}) - - require.ErrorIs(t, err, ErrNoStoredProfile) - assert.True(t, lockIsFree(t, dir)) - }) - t.Run("is released where the profiles are invalid", func(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(dir, "profiles.json"), []byte(`{"version":0}`), 0o600)) diff --git a/internal/profile/name.go b/internal/profile/name.go index 65df9457..771ff1e9 100644 --- a/internal/profile/name.go +++ b/internal/profile/name.go @@ -20,11 +20,11 @@ var NameSetting = setting.Setting[Name]{ "A profile is a named bundle of endpoint and credential, written by "+ "`meshstack login` into the meshStack CLI's configuration directory. Flags and environment "+ "variables take precedence over the values in a profile.\n\n"+ - "With no name given, the profile is the one whose endpoint matches the endpoint in use, else the one "+ - "the last `meshstack login` selected, else `default`.", envKey) + "With no name given, the profile is the one the last `meshstack login` selected, if it has the "+ + "endpoint in use, else the only profile with that endpoint. Without such a profile, the endpoint and "+ + "the credential come from the other settings alone.", envKey) }, - Default: setting.StaticDefault("default"), - Parse: setting.ParseTextUnmarshaler[Name], + Parse: setting.ParseTextUnmarshaler[Name], } var nameRegex = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$`) diff --git a/internal/profile/profile.go b/internal/profile/profile.go index 47c34a57..7c47d386 100644 --- a/internal/profile/profile.go +++ b/internal/profile/profile.go @@ -25,13 +25,28 @@ func (p Profile) String() string { return string(p.Name) } -func (p Profile) EndpointSource() setting.FallbackSource { - return setting.FallbackSource{Source: setting.LookupSource{ - Description: fmt.Sprintf("endpoint in profile %s", p.Name), - Func: func(_ context.Context) (string, error) { - return p.Endpoint.String(), nil - }, - }} +func (p Profile) LoginHint() string { + if p.Name == "" { + return "meshstack login --endpoint " + p.Endpoint.String() + } + return "meshstack login --profile " + string(p.Name) +} + +func (ps *Profiles) LoginHint(name Name, endpoint xurl.URL) string { + if stored, ok := ps.Profiles[name]; ok { + return stored.LoginHint() + } + hint := "meshstack login" + if endpoint.URL != nil { + hint += " --endpoint " + endpoint.String() + if name == "" && len(ps.Profiles) > 0 && len(ps.ForEndpoint(endpoint)) == 0 { + name = "" + } + } + if name != "" { + hint += " --profile " + string(name) + } + return hint } func (p Profile) WorkspaceSource() setting.FallbackSource { diff --git a/internal/profile/profiles.go b/internal/profile/profiles.go index bf49e52c..0d2a9cab 100644 --- a/internal/profile/profiles.go +++ b/internal/profile/profiles.go @@ -5,14 +5,10 @@ import ( "errors" "fmt" "io/fs" - "log/slog" "slices" - "strings" "github.com/meshcloud/meshstack-cli/internal/config" "github.com/meshcloud/meshstack-cli/internal/json" - "github.com/meshcloud/meshstack-cli/internal/meshstack" - "github.com/meshcloud/meshstack-cli/internal/setting" ) const ( @@ -37,8 +33,6 @@ type LoadProfilesOptions struct { ExclusiveLock bool } -// LoadProfiles only reads, and resolves nothing but the configuration directory: ResolveProfile -// creates the first profile, as it creates any other. func LoadProfiles(ctx context.Context, opts LoadProfilesOptions) (profiles Profiles, err error) { profiles.configDir, err = opts.ResolveSetting(ctx, config.DirectorySetting) if err != nil { @@ -173,31 +167,6 @@ func (ps *Profiles) add(p Profile) *Profile { return &p } -func (ps *Profiles) addCurrent(ctx context.Context, opts ResolveProfileOptions, name Name) (*Profile, error) { - stored := ps.Selection().Profiles - added := ps.add(Profile{Name: name}) - ps.CurrentProfile = name - - endpoint, err := opts.ResolveSetting(ctx, meshstack.EndpointSetting) - noEndpoint := errors.Is(err, setting.ErrNoSourceProvidedValue) - switch { - case opts.EndpointOptional && noEndpoint: - return added, nil - case noEndpoint && len(stored) > 0: - storedNames := make([]string, len(stored)) - for i, p := range stored { - storedNames[i] = string(p.Name) - } - return nil, fmt.Errorf("there is no profile '%s' among %s, and creating it needs an endpoint: %w", name, strings.Join(storedNames, ", "), err) - case err != nil: - return nil, err - } - added.Endpoint = endpoint - - slog.DebugContext(ctx, fmt.Sprintf("Profile %s resolved to %+v", name, *added)) - return added, nil -} - func (ps *Profiles) validate() (err error) { if ps.Version != version { err = errors.Join(err, fmt.Errorf("version in %s mismatch %d vs expected %d", ps.configDir, ps.Version, version)) diff --git a/internal/profile/resolve.go b/internal/profile/resolve.go index 92d7a208..bec853ec 100644 --- a/internal/profile/resolve.go +++ b/internal/profile/resolve.go @@ -4,136 +4,65 @@ import ( "context" "errors" "fmt" - "log/slog" - "sync" "github.com/meshcloud/meshstack-cli/client/types/xurl" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/setting" ) -type ( - SettingSources = setting.Sources - ResolveProfileOptions struct { - SettingSources +type SettingSources = setting.Sources - // EndpointOptional lets a profile that ResolveProfile creates go without an endpoint, for a - // command that only shows it. - EndpointOptional bool - // StoredOnly makes ResolveProfile return ErrNoStoredProfile rather than create a profile, for a - // command that only acts on a stored one. - StoredOnly bool - // ExclusiveLock is LoadProfilesOptions.ExclusiveLock for the profiles ResolveProfile - // returns, and holds nothing where it fails. - ExclusiveLock bool - } -) - -var ErrNoStoredProfile = errors.New("no stored profile") - -// ResolveProfile returns a *Profile that points into Profiles.Profiles, so a change through the -// pointer is persisted by a later Profiles.Store. -func ResolveProfile(ctx context.Context, opts ResolveProfileOptions) (*Profile, Profiles, error) { - var loaded Profiles - current, profiles, err := resolveProfile(ctx, opts, sync.OnceValues(func() (Profiles, error) { - var err error - loaded, err = LoadProfiles(ctx, LoadProfilesOptions{SettingSources: opts.SettingSources, ExclusiveLock: opts.ExclusiveLock}) - return loaded, err - })) +func ResolveProfile(ctx context.Context, sources SettingSources) (*Profile, Profiles, error) { + profiles, err := LoadProfiles(ctx, LoadProfilesOptions{SettingSources: sources}) if err != nil { - err = errors.Join(err, loaded.Unlock()) + return nil, profiles, err } - return current, profiles, err + resolved, err := profiles.Resolve(ctx, sources, false) + return resolved, profiles, err } -func resolveProfile(ctx context.Context, opts ResolveProfileOptions, loadProfiles func() (Profiles, error)) (*Profile, Profiles, error) { - // Both are fallback sources, so a name given in MESHSTACK_PROFILE wins over what is on disk, - // as NameSetting's own help text says it does. The endpoint match comes first, so that a run - // against a known endpoint picks its profile rather than the one last selected. - endpointMatchingSource := setting.FallbackSource{Source: setting.LookupSource{ - Description: "unique match by endpoint", - Func: func(ctx context.Context) (string, error) { - profiles, err := loadProfiles() - if err != nil { - return "", err - } - return profiles.findProfileNameByMatchingEndpoint(ctx, opts) - }, - }} - - currentProfileSource := setting.FallbackSource{Source: setting.LookupSource{ - Description: "current profile", - Func: func(_ context.Context) (string, error) { - profiles, err := loadProfiles() - return string(profiles.CurrentProfile), err - }, - }, Stored: true} - - // A front end source that selects the profile reads what to select from out of the context, - // as the one for the workspace does. Being a fallback source of the front end, it ranks above - // both of the sources here, so it has to take a unique endpoint match without asking. - ctxWithSelection := SetSelectionInContext(ctx, sync.OnceValues(func() (Selection, error) { - profiles, err := loadProfiles() - if err != nil { - return Selection{}, err - } - return profiles.SelectionFor(ctx, opts) - })) - - name, err := opts.ResolveSetting(ctxWithSelection, NameSetting, - endpointMatchingSource, - currentProfileSource, - ) +func (ps *Profiles) Resolve(ctx context.Context, sources SettingSources, forLogin bool) (*Profile, error) { + selection, err := ps.SelectionFor(ctx, sources) if err != nil { - return nil, Profiles{}, err + return nil, err } - - profiles, err := loadProfiles() - if err != nil { - return nil, profiles, err - } - if currentProfile, ok := profiles.Profiles[name]; ok { - return currentProfile, profiles, nil - } - if opts.StoredOnly { - return nil, profiles, fmt.Errorf("%w is named '%s'", ErrNoStoredProfile, name) + nameSetting := NameSetting + if forLogin { + nameSetting.Default = setting.StaticDefault("default") } - if len(profiles.Profiles) == 0 { - slog.InfoContext(ctx, fmt.Sprintf("Initializing first-time use profile '%s'", name)) - } else { - slog.InfoContext(ctx, fmt.Sprintf("Creating profile '%s'", name)) - } - created, err := profiles.addCurrent(ctx, opts, name) - return created, profiles, err -} - -func (ps *Profiles) findProfileNameByMatchingEndpoint(ctx context.Context, opts ResolveProfileOptions) (string, error) { - endpoint, found, err := opts.resolveEndpointIfAny(ctx) - if err != nil || !found { - return "", err + name, err := sources.ResolveSetting(SetSelectionInContext(ctx, selection), nameSetting, selection.nameSource()) + if err != nil && !errors.Is(err, setting.ErrNoSourceProvidedValue) { + return nil, err } - if matchingProfiles := ps.MatchingEndpoint(endpoint); len(matchingProfiles) == 1 { - profile := matchingProfiles[0] - slog.DebugContext(ctx, fmt.Sprintf("Using profile %s by uniquely matching endpoint '%s'", profile, endpoint)) - return string(profile.Name), nil + stored, isStored := ps.Profiles[name] + switch { + case isStored && selection.Endpoint != nil && !selection.Endpoint.Equal(stored.Endpoint): + return nil, fmt.Errorf("profile '%s' has the endpoint %s, which does not match the endpoint %s of this command; "+ + "use --profile to choose a profile of that endpoint, or run '%s'", name, stored.Endpoint, selection.Endpoint, ps.LoginHint("", *selection.Endpoint)) + case isStored: + return stored, nil + case name != "" && !forLogin: + return nil, fmt.Errorf("there is no profile '%s'; run '%s' to create it", name, ps.LoginHint(name, xurl.URL{})) + case selection.Endpoint == nil: + _, noEndpoint := sources.ResolveSetting(ctx, meshstack.EndpointSetting) + if forLogin { + return nil, fmt.Errorf("the new profile '%s' needs an endpoint: %w", name, noEndpoint) + } + return nil, errors.Join(noEndpoint, fmt.Errorf("or run '%s'", ps.LoginHint("", xurl.URL{}))) + case forLogin: + return ps.add(Profile{Name: name, Endpoint: *selection.Endpoint}), nil } - return "", nil + return &Profile{Endpoint: *selection.Endpoint, ConfigDir: ps.configDir}, nil } -func (ps *Profiles) SelectionFor(ctx context.Context, opts ResolveProfileOptions) (Selection, error) { +func (ps *Profiles) SelectionFor(ctx context.Context, sources SettingSources) (Selection, error) { selection := ps.Selection() - endpoint, found, err := opts.resolveEndpointIfAny(ctx) - if found { + endpoint, err := sources.ResolveSetting(ctx, meshstack.EndpointSetting) + switch { + case err == nil: selection.Endpoint = &endpoint + case !errors.Is(err, setting.ErrNoSourceProvidedValue): + return selection, err } - return selection, err -} - -func (opts ResolveProfileOptions) resolveEndpointIfAny(ctx context.Context) (xurl.URL, bool, error) { - endpoint, err := opts.ResolveSetting(ctx, meshstack.EndpointSetting) - if errors.Is(err, setting.ErrNoSourceProvidedValue) { - slog.DebugContext(ctx, "No endpoint known at this point, cannot search for matching profile") - return xurl.URL{}, false, nil - } - return endpoint, err == nil, err + return selection, nil } diff --git a/internal/profile/resolve_test.go b/internal/profile/resolve_test.go index 7c6361fa..3a3b5fb4 100644 --- a/internal/profile/resolve_test.go +++ b/internal/profile/resolve_test.go @@ -5,13 +5,11 @@ import ( "os" "path/filepath" "testing" - "uuid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/client/types/xurl" - "github.com/meshcloud/meshstack-cli/internal/auth/credential" "github.com/meshcloud/meshstack-cli/internal/config" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/setting" @@ -20,82 +18,45 @@ import ( var testEndpoint = xurl.MustParsef("https://localhost:1337") -func TestResolveProfileOnAFreshConfigDirectory(t *testing.T) { +func TestALoginCreatesItsProfile(t *testing.T) { givenNoMeshstackEnvironment(t) configDir := filepath.Join(t.TempDir(), "missing") t.Setenv(config.DirectorySetting.EnvKey(), configDir) - t.Setenv(meshstack.EndpointSetting.EnvKey(), testEndpoint.String()) - defaultProfile := &Profile{Name: "default", Endpoint: testEndpoint} - dev := &Profile{Name: "dev", Endpoint: testEndpoint} - - t.Run("creates the default profile, though the directory is missing", func(t *testing.T) { - current, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) - - require.NoError(t, err) - assert.EqualExportedValues(t, defaultProfile, withoutConfigDir(current)) - assertProfiles(t, profiles, defaultProfile) - require.NoError(t, profiles.Store(t.Context())) - }) - - t.Run("creates a missing profile the environment names, and selects it", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "dev") - created, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) - - require.NoError(t, err) - assert.EqualExportedValues(t, dev, withoutConfigDir(created)) - assertProfiles(t, profiles, dev, defaultProfile) - - created.DefaultWorkspace = "my-workspace-ab12c" - require.NoError(t, profiles.Store(t.Context())) - }) - - t.Run("what a login stores through the returned profile survives the next run", func(t *testing.T) { - reloaded, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) - + resolveForLogin := func(t *testing.T) (*Profile, Profiles, error) { + t.Helper() + profiles, err := LoadProfiles(t.Context(), LoadProfilesOptions{}) require.NoError(t, err) - dev.DefaultWorkspace = "my-workspace-ab12c" - assert.EqualExportedValues(t, dev, withoutConfigDir(reloaded)) - assertProfiles(t, profiles, dev, defaultProfile) - }) - - t.Run("a profile name from a front end source wins over the environment", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "from-the-environment") + resolved, err := profiles.Resolve(t.Context(), nil, true) + return resolved, profiles, err + } - current, _, err := ResolveProfile(t.Context(), ResolveProfileOptions{SettingSources: profileNameFromFrontend("from-the-front-end")}) + t.Run("a new profile needs an endpoint", func(t *testing.T) { + _, _, err := resolveForLogin(t) - require.NoError(t, err) - assert.Equal(t, Name("from-the-front-end"), current.Name) + require.ErrorIs(t, err, setting.ErrNoSourceProvidedValue) + require.ErrorContains(t, err, "the new profile 'default' needs an endpoint") }) - t.Run("a stored profile is found without its name or endpoint in the environment", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "dev-local") + t.Run("without a name it is the profile default, though the directory is missing", func(t *testing.T) { // Upper case and a trailing slash, so that the stored endpoint shows the canonical form. t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://LOCALHOST:1337/") - devLocal := &Profile{Name: "dev-local", Endpoint: testEndpoint} - created, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) - require.NoError(t, err) - assert.EqualExportedValues(t, devLocal, withoutConfigDir(created)) - require.NoError(t, profiles.Store(t.Context())) - storeApiKey(t, created) - - // An empty value is skipped as no value at all, so this is the unset case. - t.Setenv(NameSetting.EnvKey(), "") - t.Setenv(meshstack.EndpointSetting.EnvKey(), "") - reloaded, _, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) + created, profiles, err := resolveForLogin(t) require.NoError(t, err) - assert.EqualExportedValues(t, devLocal, withoutConfigDir(reloaded)) - assertApiKey(t, reloaded, "08be9109-45bf-42ba-a965-2097b9d0d181", "super-test-secret") + assert.EqualExportedValues(t, &Profile{Name: "default", Endpoint: testEndpoint}, withoutConfigDir(created)) + assert.Same(t, created, profiles.Profiles["default"]) + assert.Equal(t, config.Directory(configDir), created.ConfigDir) + require.NoError(t, profiles.SetCurrent(t.Context(), created.Name)) }) - t.Run("Add puts a profile into the config directory of the profiles", func(t *testing.T) { - profiles, err := LoadProfiles(t.Context(), LoadProfilesOptions{}) - require.NoError(t, err) - - added := profiles.add(Profile{Name: "dev", Endpoint: testEndpoint, ConfigDir: "elsewhere"}) + t.Run("a name in the environment creates a second profile next to the stored one", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), testEndpoint.String()) + t.Setenv(NameSetting.EnvKey(), "dev") + created, profiles, err := resolveForLogin(t) - assert.Equal(t, config.Directory(configDir), added.ConfigDir) - assert.Same(t, added, profiles.Profiles["dev"]) + require.NoError(t, err) + assert.Equal(t, Name("dev"), created.Name) + assert.Len(t, profiles.Profiles, 2) }) t.Run("a null profile is refused", func(t *testing.T) { @@ -122,45 +83,75 @@ func TestResolveProfileOfAStoredConfigDirectory(t *testing.T) { resolveWithSelection := func(t *testing.T) *Profile { t.Helper() asked = nil - selected, _, err := ResolveProfile(t.Context(), ResolveProfileOptions{SettingSources: selectionAnswering("default")}) + selected, _, err := ResolveProfile(t.Context(), selectionAnswering("default")) require.NoError(t, err) return selected } - t.Run("reads the current profile and its credentials", func(t *testing.T) { - currentProfile, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) + t.Run("without a name or an endpoint it is the current profile, with its credentials", func(t *testing.T) { + currentProfile, profiles, err := ResolveProfile(t.Context(), nil) require.NoError(t, err) - devLocal := &Profile{Name: "dev-local", Endpoint: xurl.MustParsef("https://localhost:1337"), Credential: "apiKey"} + devLocal := &Profile{Name: "dev-local", Endpoint: testEndpoint, Credential: "apiKey"} assert.EqualExportedValues(t, devLocal, withoutConfigDir(currentProfile)) - assertProfiles(t, profiles, - devLocal, - &Profile{Name: "default", Endpoint: xurl.MustParsef("https://api.dev.meshcloud.io/")}, - &Profile{Name: "empty"}, - ) + assert.Len(t, profiles.Profiles, 3) assertApiKey(t, currentProfile, "08be9109-45bf-42ba-a965-2097b9d0d181", "super-test-secret") + }) - // Storing what was just loaded leaves the files as they are, so testdata stays the fixture. - require.NoError(t, profiles.Store(t.Context())) + t.Run("an unknown name is an error", func(t *testing.T) { + t.Setenv(NameSetting.EnvKey(), "typo") + + _, _, err := ResolveProfile(t.Context(), nil) + + require.ErrorContains(t, err, "there is no profile 'typo'; run 'meshstack login --profile typo' to create it") }) - t.Run("StoredOnly creates no profile", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "missing") + t.Run("a name from a front end source wins over the environment", func(t *testing.T) { + t.Setenv(NameSetting.EnvKey(), "dev-local") - _, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{StoredOnly: true}) + current, _, err := ResolveProfile(t.Context(), profileNameFromFrontend("default")) - require.ErrorIs(t, err, ErrNoStoredProfile) - require.ErrorContains(t, err, "'missing'") - assert.NotContains(t, profiles.Profiles, Name("missing")) + require.NoError(t, err) + assert.Equal(t, Name("default"), current.Name) }) - t.Run("a missing profile without an endpoint names the stored ones", func(t *testing.T) { - t.Setenv(NameSetting.EnvKey(), "typo") + t.Run("a named profile must have the endpoint given", func(t *testing.T) { + t.Setenv(NameSetting.EnvKey(), "dev-local") + t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://api.dev.meshcloud.io") - _, _, err := ResolveProfile(t.Context(), ResolveProfileOptions{}) + _, _, err := ResolveProfile(t.Context(), nil) - require.ErrorIs(t, err, setting.ErrNoSourceProvidedValue) - require.ErrorContains(t, err, "there is no profile 'typo' among default, dev-local, empty") + require.ErrorContains(t, err, "profile 'dev-local' has the endpoint https://localhost:1337, which does not match the endpoint https://api.dev.meshcloud.io") + }) + + t.Run("an endpoint of another profile than the current one takes the only profile that has it", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://API.dev.meshcloud.io/") + + resolved, _, err := ResolveProfile(t.Context(), nil) + + require.NoError(t, err) + assert.Equal(t, Name("default"), resolved.Name) + }) + + t.Run("an endpoint of no stored profile gives a nameless profile, which is not stored", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://localhost:4711") + + nameless, profiles, err := ResolveProfile(t.Context(), nil) + + require.NoError(t, err) + assert.EqualExportedValues(t, &Profile{Endpoint: xurl.MustParsef("https://localhost:4711")}, withoutConfigDir(nameless)) + assert.Len(t, profiles.Profiles, 3) + assert.Equal(t, "meshstack login --endpoint https://localhost:4711", nameless.LoginHint()) + assert.Equal(t, "meshstack login --endpoint https://localhost:4711 --profile ", profiles.LoginHint("", nameless.Endpoint), + "a login without --profile fails where no stored profile has the endpoint") + }) + + t.Run("an endpoint with a path is refused", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), testEndpoint.String()+"/api") + + _, _, err := ResolveProfile(t.Context(), nil) + + require.ErrorContains(t, err, "an endpoint is a scheme and a host") }) t.Run("without an endpoint the selection offers every profile, ordered by name", func(t *testing.T) { @@ -179,36 +170,12 @@ func TestResolveProfileOfAStoredConfigDirectory(t *testing.T) { assert.Len(t, asked[0].Profiles, 3) }) - t.Run("an endpoint matching no profile leaves no candidate", func(t *testing.T) { - t.Setenv(meshstack.EndpointSetting.EnvKey(), testEndpoint.String()+"/other") - resolveWithSelection(t) - require.Len(t, asked, 1) - assert.Empty(t, asked[0].Candidates()) - }) - t.Run("a profile named in the environment needs no selection", func(t *testing.T) { t.Setenv(NameSetting.EnvKey(), "empty") assert.Equal(t, Name("empty"), resolveWithSelection(t).Name) assert.Empty(t, asked) }) - // This step fails where LoadProfiles resolves the profile name itself: it then reaches the - // selection before the context carries it. - t.Run("a first-time use offers an empty selection", func(t *testing.T) { - t.Setenv(config.DirectorySetting.EnvKey(), t.TempDir()) - t.Setenv(meshstack.EndpointSetting.EnvKey(), testEndpoint.String()) - asked = nil - - created, profiles, err := ResolveProfile(t.Context(), ResolveProfileOptions{SettingSources: selectionAnswering("")}) - - require.NoError(t, err) - require.Len(t, asked, 1) - assert.Empty(t, asked[0].Profiles) - expected := &Profile{Name: "default", Endpoint: testEndpoint} - assert.EqualExportedValues(t, expected, withoutConfigDir(created)) - assertProfiles(t, profiles, expected) - }) - t.Run("the selection is not in the context outside the profile name resolution", func(t *testing.T) { _, err := SelectionFromContext(t.Context()) @@ -241,48 +208,15 @@ func profileNameFromFrontend(name Name) SettingSources { )}} } -func storeApiKey(t *testing.T, p *Profile) { - t.Helper() - creds, err := p.Credentials(t.Context()) - require.NoError(t, err) - creds.Set(&credential.ApiKey{ - Endpoint: p.Endpoint, - ClientId: uuid.MustParse("08be9109-45bf-42ba-a965-2097b9d0d181"), - ClientSecret: "super-test-secret", - }) - require.NoError(t, creds.Store(t.Context())) -} - func assertApiKey(t *testing.T, p *Profile, clientId, clientSecret string) { t.Helper() creds, err := p.Credentials(t.Context()) require.NoError(t, err) require.NotNil(t, creds.ApiKey) - assert.Equal(t, uuid.MustParse(clientId), creds.ApiKey.ClientId) + assert.Equal(t, clientId, creds.ApiKey.ClientId.String()) assert.Equal(t, clientSecret, creds.ApiKey.ClientSecret) } -func assertProfiles(t *testing.T, actual Profiles, expected ...*Profile) { - t.Helper() - expectedProfiles := Profiles{Version: 1} - if len(expected) > 0 { - expectedProfiles.CurrentProfile = expected[0].Name - } - expectedProfiles.Profiles = make(map[Name]*Profile, len(expected)) - for _, profile := range expected { - expectedProfiles.Profiles[profile.Name] = profile - } - // ConfigDir is whatever directory the run resolved, so it is asserted non-empty rather than compared. - actualStripped := actual - actualStripped.Profiles = make(map[Name]*Profile, len(actual.Profiles)) - for name, actualProfile := range actual.Profiles { - assert.NotEmpty(t, actualProfile.ConfigDir) - actualStripped.Profiles[name] = withoutConfigDir(actualProfile) - } - assert.EqualExportedValues(t, expectedProfiles, actualStripped) - assert.NotEmpty(t, actual.configDir) -} - func withoutConfigDir(p *Profile) *Profile { stripped := *p stripped.ConfigDir = "" diff --git a/internal/profile/select.go b/internal/profile/select.go index cf5fac6f..b3c8396f 100644 --- a/internal/profile/select.go +++ b/internal/profile/select.go @@ -5,30 +5,26 @@ import ( "context" "fmt" "maps" - "net/url" "slices" - "strings" "github.com/meshcloud/meshstack-cli/client/types/xurl" + "github.com/meshcloud/meshstack-cli/internal/setting" ) -type ( - selectionContextKey int - SelectionFunc func() (Selection, error) -) +type selectionContextKey struct{} // SelectionFromContext returns what a front end picks a profile from. It is only in the context // while NameSetting is being resolved, so a lookup for any other setting gets an error. func SelectionFromContext(ctx context.Context) (Selection, error) { - selection, found := ctx.Value(selectionContextKey(0)).(SelectionFunc) + selection, found := ctx.Value(selectionContextKey{}).(Selection) if !found { return Selection{}, fmt.Errorf("no profile selection available in this context; it is only provided while resolving %s", NameSetting.EnvKey()) } - return selection() + return selection, nil } -func SetSelectionInContext(ctx context.Context, selection SelectionFunc) context.Context { - return context.WithValue(ctx, selectionContextKey(0), selection) +func SetSelectionInContext(ctx context.Context, selection Selection) context.Context { + return context.WithValue(ctx, selectionContextKey{}, selection) } type Selection struct { @@ -46,9 +42,8 @@ func (ps *Profiles) Selection() Selection { return Selection{Profiles: sorted, Current: ps.CurrentProfile} } -// MatchingEndpoint are copies of the profiles for endpoint, ordered by name, so that a caller can -// read them while the profiles change. -func (ps *Profiles) MatchingEndpoint(endpoint xurl.URL) (matching []Profile) { +// ForEndpoint returns copies, so that a caller can read them while the profiles change. +func (ps *Profiles) ForEndpoint(endpoint xurl.URL) (matching []Profile) { selection := ps.Selection() selection.Endpoint = &endpoint for _, p := range selection.Candidates() { @@ -57,51 +52,6 @@ func (ps *Profiles) MatchingEndpoint(endpoint xurl.URL) (matching []Profile) { return matching } -// EndpointHolding returns the scheme and host of requestURL where no profile holds it: the endpoint -// a profile for it would need. -func (ps *Profiles) EndpointHolding(requestURL *url.URL) (endpoint xurl.URL, held bool) { - for _, p := range ps.Profiles { - if _, holds := p.Endpoint.PathTo(requestURL); holds && (endpoint.URL == nil || len(p.Endpoint.Path) > len(endpoint.Path)) { - endpoint = p.Endpoint - } - } - if endpoint.URL == nil { - return xurl.URL{URL: &url.URL{Scheme: requestURL.Scheme, Host: requestURL.Host}}, false - } - return endpoint, true -} - -func (ps *Profiles) Holding(requestURL *url.URL) (p Profile, current bool, err error) { - endpoint, held := ps.EndpointHolding(requestURL) - if !held { - return Profile{}, false, fmt.Errorf("no stored profile has the endpoint %s of this URL; run 'meshstack login --endpoint %s' to create one", - endpoint, endpoint) - } - return ps.ForEndpoint(endpoint, requestURL) -} - -// ForEndpoint takes the current one of the profiles sharing endpoint, and fails where none of them -// is current rather than guess, as they can hold different credentials. -func (ps *Profiles) ForEndpoint(endpoint xurl.URL, requestURL *url.URL) (p Profile, current bool, err error) { - matching := ps.MatchingEndpoint(endpoint) - isCurrent := func(p Profile) bool { return p.Name == ps.CurrentProfile } - switch { - case len(matching) == 0: - return Profile{}, false, fmt.Errorf("no stored profile has the endpoint %s; run 'meshstack login --endpoint %s' to create one", endpoint, endpoint) - case len(matching) == 1: - return matching[0], isCurrent(matching[0]), nil - } - if i := slices.IndexFunc(matching, isCurrent); i >= 0 { - return matching[i], true, nil - } - names := make([]string, 0, len(matching)) - for _, p := range matching { - names = append(names, "'"+string(p.Name)+"'") - } - return Profile{}, false, fmt.Errorf("profiles %s all have the endpoint %s of %s, and none of them is the current profile; use --profile or %s to choose one", - strings.Join(names, ", "), endpoint, requestURL.Redacted(), NameSetting.EnvKey()) -} - func (s Selection) Candidates() []*Profile { if s.Endpoint == nil { return s.Profiles @@ -111,6 +61,20 @@ func (s Selection) Candidates() []*Profile { }) } +func (s Selection) nameSource() setting.FallbackSource { + var name Name + description := "current profile" + if candidates := s.Candidates(); slices.ContainsFunc(candidates, func(p *Profile) bool { return p.Name == s.Current }) { + name = s.Current + } else if s.Endpoint != nil && len(candidates) == 1 { + name, description = candidates[0].Name, "only profile with the endpoint "+s.Endpoint.String() + } + return setting.FallbackSource{Stored: true, Source: setting.LookupSource{ + Description: description, + Func: func(context.Context) (string, error) { return string(name), nil }, + }} +} + func (p Profile) Label() string { if p.Endpoint.URL == nil { return fmt.Sprintf("%s (no endpoint)", p.Name) diff --git a/internal/profile/select_test.go b/internal/profile/select_test.go index 70a8bbff..0a3be6d8 100644 --- a/internal/profile/select_test.go +++ b/internal/profile/select_test.go @@ -1,82 +1,50 @@ package profile import ( - "net/url" "os" - "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/meshcloud/meshstack-cli/internal/config" + "github.com/meshcloud/meshstack-cli/internal/meshstack" ) -func TestProfilesHoldingARequestURL(t *testing.T) { +func TestProfilesSharingAnEndpoint(t *testing.T) { givenNoMeshstackEnvironment(t) configDir := t.TempDir() t.Setenv(config.DirectorySetting.EnvKey(), configDir) require.NoError(t, os.WriteFile(config.Directory(configDir).ProfilesJson(), []byte(`{"version":1,"currentProfile":"local","profiles":{ "local": {"endpoint":"https://localhost:1337"}, "local-2": {"endpoint":"https://localhost:1337"}, - "a": {"endpoint":"https://meshstack.example.com/a"}, - "a-b": {"endpoint":"https://meshstack.example.com/a/b/"}, "shared-1": {"endpoint":"https://shared.example.com"}, "shared-2": {"endpoint":"https://shared.example.com"} }}`), 0o600)) - profiles, err := LoadProfiles(t.Context(), LoadProfilesOptions{}) - require.NoError(t, err) - holding := func(t *testing.T, requestURL string) (Name, bool, error) { - t.Helper() - parsed, err := url.Parse(requestURL) - require.NoError(t, err) - p, current, err := profiles.Holding(parsed) - return p.Name, current, err - } - - t.Run("the scheme and host match in any letter case, and of the profiles sharing them the current one is picked", func(t *testing.T) { - name, current, err := holding(t, "https://LOCALHOST:1337/api/meshobjects") - - require.NoError(t, err) - assert.Equal(t, Name("local"), name) - assert.True(t, current) - }) - - t.Run("a URL on another port or scheme matches no profile, and the error says how to log in to it", func(t *testing.T) { - for _, requestURL := range []string{"https://localhost:1338/api", "http://localhost:1337/api"} { - _, _, err := holding(t, requestURL) - - endpoint := strings.TrimSuffix(requestURL, "/api") - require.ErrorContains(t, err, "no stored profile has the endpoint "+endpoint) - require.ErrorContains(t, err, "'meshstack login --endpoint "+endpoint+"'") - } - }) - - t.Run("an endpoint path matches whole segments only", func(t *testing.T) { - _, _, err := holding(t, "https://meshstack.example.com/ab/api") - require.ErrorContains(t, err, "no stored profile has the endpoint https://meshstack.example.com ") - }) + t.Run("the current one of them is taken", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://localhost:1337") - t.Run("a profile other than the current one is picked, and is not current", func(t *testing.T) { - name, current, err := holding(t, "https://meshstack.example.com/a/api") + resolved, _, err := ResolveProfile(t.Context(), nil) require.NoError(t, err) - assert.Equal(t, Name("a"), name) - assert.False(t, current) + assert.Equal(t, Name("local"), resolved.Name) }) - t.Run("the profile with the longest endpoint that holds the URL is picked", func(t *testing.T) { - name, _, err := holding(t, "https://meshstack.example.com/a/b/api") + t.Run("none of them is taken where none is current", func(t *testing.T) { + t.Setenv(meshstack.EndpointSetting.EnvKey(), "https://shared.example.com") + + resolved, profiles, err := ResolveProfile(t.Context(), nil) require.NoError(t, err) - assert.Equal(t, Name("a-b"), name) + assert.Empty(t, resolved.Name) + assert.Equal(t, []Name{"shared-1", "shared-2"}, names(pointersTo(profiles.ForEndpoint(resolved.Endpoint)))) }) +} - t.Run("profiles sharing the endpoint, none of them current, need a name", func(t *testing.T) { - _, _, err := holding(t, "https://shared.example.com/api") - - require.ErrorContains(t, err, "'shared-1', 'shared-2'") - require.ErrorContains(t, err, NameSetting.EnvKey()) - }) +func pointersTo(profiles []Profile) (pointers []*Profile) { + for i := range profiles { + pointers = append(pointers, &profiles[i]) + } + return pointers } diff --git a/internal/setting/resolve.go b/internal/setting/resolve.go index 9387a28e..e4f9b95e 100644 --- a/internal/setting/resolve.go +++ b/internal/setting/resolve.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "log/slog" + "reflect" "slices" "strings" ) @@ -60,7 +61,7 @@ func (sources Sources) ResolveSettingWithSource[T any](ctx context.Context, sett setting.Default.asSourcesIfPresent(), ) - for _, candidate := range sourceCandidates { + for i, candidate := range sourceCandidates { if candidate == nil { continue } @@ -82,6 +83,9 @@ func (sources Sources) ResolveSettingWithSource[T any](ctx context.Context, sett if _, fromEnv := candidate.(EnvKey); fromEnv { fallbackSources.warnOfOverriddenStoredValues(ctx, setting.EnvKey(), description, text) } + if i >= len(frontendSources) && i < len(frontendSources)+len(otherSources) { + setting.warnOfOverriddenEnv(ctx, description, text, value) + } return value, candidate, nil } return value, nil, fmt.Errorf("%w for %s", ErrNoSourceProvidedValue, setting.EnvKey()) @@ -97,3 +101,14 @@ func (sources Sources) warnOfOverriddenStoredValues(ctx context.Context, key, de } } } + +func (s Setting[T]) warnOfOverriddenEnv(ctx context.Context, description, text string, value T) { + envText, err := s.Env.Lookup(ctx, s.EnvKey()) + if envText = strings.TrimSpace(envText); err != nil || envText == "" { + return + } + if envValue, parseErr := s.Parse(envText); parseErr == nil && reflect.DeepEqual(envValue, value) { + return + } + slog.WarnContext(ctx, fmt.Sprintf("%s sets '%s', which overrides '%s' from %s", description, text, envText, s.Env.Describe(s.EnvKey()))) +} diff --git a/internal/setting/resolve_test.go b/internal/setting/resolve_test.go index 1a3420d2..b27e99b9 100644 --- a/internal/setting/resolve_test.go +++ b/internal/setting/resolve_test.go @@ -186,3 +186,35 @@ func TestResolveSettingWarnsWhenTheEnvironmentOverridesAStoredValue(t *testing.T assert.Zero(t, storedLookups) }) } + +func TestResolveSettingWarnsWhenASourceOfTheCommandOverridesTheEnvironment(t *testing.T) { + endpoint := setting.Setting[string]{Env: "MESHSTACK_TEST_ENDPOINT", Parse: setting.ParseText[string]} + url := setting.LookupSource{ + Description: "the URL https://a.example/api", + Func: func(context.Context) (string, error) { return "https://a.example", nil }, + } + warnings := func(t *testing.T, sources setting.Sources) []string { + t.Helper() + captured := logs.Capture(t) + _, err := sources.ResolveSetting(t.Context(), endpoint) + require.NoError(t, err) + return captured.Lines(slog.LevelWarn) + } + + t.Run("the environment with the same value is not warned of", func(t *testing.T) { + t.Setenv(endpoint.EnvKey(), "https://a.example") + assert.Empty(t, warnings(t, setting.Sources{url})) + }) + + t.Run("the environment with another value is warned of", func(t *testing.T) { + t.Setenv(endpoint.EnvKey(), "https://b.example") + lines := warnings(t, setting.Sources{url}) + require.Len(t, lines, 1) + assert.Contains(t, lines[0], "the URL https://a.example/api sets 'https://a.example', which overrides 'https://b.example' from env MESHSTACK_TEST_ENDPOINT") + }) + + t.Run("a front end source over the environment is not warned of", func(t *testing.T) { + t.Setenv(endpoint.EnvKey(), "https://b.example") + assert.Empty(t, warnings(t, setting.Sources{setting.FrontendSource{Source: url}})) + }) +} diff --git a/internal/tfstate/proxy.go b/internal/tfstate/proxy.go index 5c6de5ff..8d950847 100644 --- a/internal/tfstate/proxy.go +++ b/internal/tfstate/proxy.go @@ -103,9 +103,8 @@ func (p *Proxy) Serve(ctx context.Context, run func(env []string)) (requests int // With an API key as well, the provider since v0.26.0 refuses to pick one of the two. auth.ApiKeyClientIdSetting.EnvKey() + "=", auth.ApiKeyClientSecretSetting.EnvKey() + "=", - // The provider since v0.26.0 refuses a stored profile whose endpoint is not the proxy's, and - // creates a profile it does not find without storing it. - profile.NameSetting.EnvKey() + "=" + execProfile, + // A profile named in the environment has another endpoint than the proxy. + profile.NameSetting.EnvKey() + "=", }) err = server.Shutdown(context.WithoutCancel(ctx)) @@ -145,8 +144,6 @@ func (p *Proxy) ServeHTTP(w gohttp.ResponseWriter, r *gohttp.Request) { } } -const execProfile = "meshstack-tfstate-exec" - // newApiToken wraps password in the shape of a JWT that expires in a year, because the provider // since v0.26.0 refuses a token that is no JWT, or that has expired. Nobody checks its signature. func newApiToken(password string) string { diff --git a/pkg/setting/source.go b/pkg/setting/source.go index 4a04ab8b..c1d2a200 100644 --- a/pkg/setting/source.go +++ b/pkg/setting/source.go @@ -2,7 +2,6 @@ package setting import ( "context" - "errors" "github.com/meshcloud/meshstack-cli/internal/meshstack" "github.com/meshcloud/meshstack-cli/internal/setting" @@ -22,6 +21,9 @@ type ( MeshWorkspace = meshstack.MeshWorkspace ) +// ErrNoSourceProvidedValue tells a missing setting from a wrong one. +var ErrNoSourceProvidedValue = setting.ErrNoSourceProvidedValue + // SingleSource wraps one source as the front end's only contribution, ranking it above the // environment and the default. func SingleSource(source setting.Source) Sources { @@ -52,13 +54,3 @@ func FallbackLookupSource(matchingEnvKey, description string, lookup func(ctx co func WorkspacesFromContext(ctx context.Context) (meshstack.Workspaces, error) { return meshstack.WorkspacesFromContext(ctx) } - -// ResolveWorkspace resolves Workspace from sources and the environment, and is empty when neither -// names one. A profile's default workspace is no source here, unlike in a session. -func ResolveWorkspace(ctx context.Context, sources Sources) (string, error) { - workspace, err := sources.ResolveSetting(ctx, meshstack.WorkspaceSetting) - if errors.Is(err, setting.ErrNoSourceProvidedValue) { - return "", nil - } - return string(workspace), err -} diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index ea8c8355..bcd01263 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -60,8 +60,8 @@ A login stores a credential in a profile. A profile also holds an endpoint and a `MESHSTACK_PROFILE`, `MESHSTACK_WORKSPACE` and a credential in the environment (`MESHSTACK_API_KEY` with `MESHSTACK_API_SECRET`, or `MESHSTACK_API_TOKEN`) win over what a login stores, and a -command warns when they do. Unset them to use the stored profile. To ignore the stored profiles -instead, as a script or CI job should, point `MESHSTACK_CONFIG_DIR` at a directory of its own. +command warns when they do. Unset them to use the stored profile. A script or CI job needs no +profile: it sets `MESHSTACK_ENDPOINT` and a credential. ```sh meshstack auth status -p # who, which workspace, until when — check this first @@ -398,7 +398,8 @@ read the outcome. Poll its runs instead: `meshstack bbrun list --building-block ## Everything else: `meshstack api` `meshstack api` sends an authenticated, `curl`-like request to any path of the API, with the -current login. For a meshObject endpoint it picks the latest API version, sets the `Accept` and +current login. A full URL, such as a self link, chooses its origin as the endpoint, with a warning +where `MESHSTACK_ENDPOINT` names another one. For a meshObject endpoint it picks the latest API version, sets the `Accept` and `Content-Type` headers and fills in a missing `apiVersion` and `kind` of the body itself; `--api-version` picks another version. Leave the version out unless you need an older one, so the command keeps working when a preview version becomes GA. An answer outside 2xx still prints its