From 4e8d794582a5628500f858501dd688acc02b5661 Mon Sep 17 00:00:00 2001 From: Aditya030207 <230317630+Aditya030207@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:44:53 +0530 Subject: [PATCH 1/2] fix: infer project from client-side environment key --- internal/api/client.go | 5 ++++ internal/cmd/cmd_test.go | 57 +++++++++++++++++++++++++++++++++++++ internal/cmd/environment.go | 46 ++++++++++++------------------ internal/cmd/flags.go | 11 +++++++ internal/cmd/resolve.go | 49 +++++++++++++++++++++++++++++-- 5 files changed, 138 insertions(+), 30 deletions(-) diff --git a/internal/api/client.go b/internal/api/client.go index c815a74..771d95f 100644 --- a/internal/api/client.go +++ b/internal/api/client.go @@ -345,6 +345,11 @@ func statusOf(err error) int { return 0 } +// IsNotFound reports whether the API returned HTTP 404. +func IsNotFound(err error) bool { + return statusOf(err) == http.StatusNotFound +} + // apiDetailOf returns the API's own message for an error, or "" — which is what // a response that no API rendered looks like. func apiDetailOf(err error) string { diff --git a/internal/cmd/cmd_test.go b/internal/cmd/cmd_test.go index 1777c36..9ae9400 100644 --- a/internal/cmd/cmd_test.go +++ b/internal/cmd/cmd_test.go @@ -6546,6 +6546,63 @@ func withEnvironments(f *fakeInstance) { } } +func TestEnvironmentKeyWithoutProject(t *testing.T) { + const key = "K2mVsGdXhZ8kQqZ9pJmNbJ" + for _, tc := range []struct { + name string + args []string + envKey string + want string + wantGets int + wantList int + wantErr string + }{ + {name: "flag list by key", args: []string{"flag", "list", "-e", key}, wantGets: 1}, + {name: "flag list by SDK key", args: []string{"flag", "list"}, envKey: key, wantGets: 1}, + {name: "get JSON by key", args: []string{"environment", "get", key, "--jq", ".project"}, want: "101", wantGets: 1}, + {name: "name requires project", args: []string{"environment", "get", "Production"}, wantErr: "no project"}, + {name: "unknown key requires project", args: []string{"environment", "get", strings.Repeat("a", 22)}, wantErr: "no project", wantGets: 1}, + {name: "wrong explicit project", args: []string{"flag", "list", "-e", key, "--project", "999"}, wantErr: "not found in project 999", wantList: 1}, + } { + t.Run(tc.name, func(t *testing.T) { + // Given + isolateStorage(t) + f := newFakeInstance(t) + withEnvironments(f) + f.envs["999"] = []map[string]any{} + tempRepo(t) + setMasterKey(t, f.srv.URL) + t.Setenv("FLAGSMITH_API_URL", f.srv.URL) + setEnvCred(t, envEnvironmentKey, f.srv.URL, tc.envKey) + t.Setenv("FLAGSMITH_SDK_API_URL", f.srv.URL) + + // When + out, err := run("", tc.args...) + + // Then + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("error = %v, want %q", err, tc.wantErr) + } + } else if err != nil { + t.Fatalf("command: %v\noutput: %s", err, out) + } + if tc.want != "" && strings.TrimSpace(out) != tc.want { + t.Errorf("output = %q, want %q", out, tc.want) + } + if tc.wantErr == "" && tc.args[0] == "flag" && f.featuresEnv() != "2" { + t.Errorf("features environment = %q, want 2", f.featuresEnv()) + } + if got := f.environmentGets(); got != tc.wantGets { + t.Errorf("environment retrieves = %d, want %d", got, tc.wantGets) + } + if got := f.environmentLists(); got != tc.wantList { + t.Errorf("environment lists = %d, want %d", got, tc.wantList) + } + }) + } +} + func TestEnvironment(t *testing.T) { t.Run("list", func(t *testing.T) { f := flagUpdateEnv(t) diff --git a/internal/cmd/environment.go b/internal/cmd/environment.go index 42dcb0e..3fb9a6f 100644 --- a/internal/cmd/environment.go +++ b/internal/cmd/environment.go @@ -89,28 +89,30 @@ var environmentListCmd = &cobra.Command{ }, } +func environmentScopedContext(cmd *cobra.Command, ref string, full bool) (*activeCredential, *api.Environment, error) { + pc, err := applyContext(cmd) + if err != nil { + return nil, nil, err + } + cred, err := resolveCredential(cmd.Context()) + if err != nil { + return nil, nil, err + } + env, err := resolveEnvironmentWithProject(cmd, pc, cred, ref, full) + return cred, env, err +} + var environmentGetCmd = &cobra.Command{ Use: "get ", Short: "Show an environment", Example: " flagsmith environment get Production", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cred, projectID, err := projectScopedContext(cmd) - if err != nil { - return err - } - ref, err := resolveEnvironmentRef(cmd, cred, projectID, args[0]) + // Machine output needs the full retrieve payload. + _, env, err := environmentScopedContext(cmd, args[0], jsonOutput()) if err != nil { return err } - // The human detail's fields are all in the resolved list row. The - // retrieve payload is richer, so machine output re-fetches for fidelity. - env := ref - if jsonOutput() { - if env, err = cred.client().GetEnvironment(cmd.Context(), ref.APIKey); err != nil { - return err - } - } return renderEnvironment(cmd, env) }, } @@ -149,11 +151,7 @@ var environmentUpdateCmd = &cobra.Command{ if len(body) == 0 { return usageErrorf("nothing to update — pass --name, --description, or a setting flag") } - cred, projectID, err := projectScopedContext(cmd) - if err != nil { - return err - } - ref, err := resolveEnvironmentRef(cmd, cred, projectID, args[0]) + cred, ref, err := environmentScopedContext(cmd, args[0], false) if err != nil { return err } @@ -172,11 +170,7 @@ var environmentDeleteCmd = &cobra.Command{ Example: " flagsmith environment delete Staging --yes", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - cred, projectID, err := projectScopedContext(cmd) - if err != nil { - return err - } - ref, err := resolveEnvironmentRef(cmd, cred, projectID, args[0]) + cred, ref, err := environmentScopedContext(cmd, args[0], false) if err != nil { return err } @@ -198,11 +192,7 @@ var environmentCloneCmd = &cobra.Command{ Example: ` flagsmith environment clone Production "Production Copy"`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { - cred, projectID, err := projectScopedContext(cmd) - if err != nil { - return err - } - ref, err := resolveEnvironmentRef(cmd, cred, projectID, args[0]) + cred, ref, err := environmentScopedContext(cmd, args[0], false) if err != nil { return err } diff --git a/internal/cmd/flags.go b/internal/cmd/flags.go index ba9d7cc..dfabd2b 100644 --- a/internal/cmd/flags.go +++ b/internal/cmd/flags.go @@ -288,6 +288,17 @@ func flagContext(cmd *cobra.Command) (*projectContext, *activeCredential, int, a if err != nil { return nil, nil, 0, api.Environment{}, err } + if pc.Project.Value == nil { + ref, err := environmentReference(pc) + if err != nil { + return nil, nil, 0, api.Environment{}, err + } + env, err := resolveEnvironmentWithProject(cmd, pc, cred, ref, false) + if err != nil { + return nil, nil, 0, api.Environment{}, err + } + return pc, cred, env.Project, *env, nil + } projectID, err := resolveProjectID(cmd, pc, cred) if err != nil { return nil, nil, 0, api.Environment{}, err diff --git a/internal/cmd/resolve.go b/internal/cmd/resolve.go index 363ec2a..22ebdfc 100644 --- a/internal/cmd/resolve.go +++ b/internal/cmd/resolve.go @@ -76,7 +76,7 @@ func pickCandidate(cmd *cobra.Command, entity, idKind, ref string, candidates [] // resolveEnvironment turns the environment context reference (a client-side key // or a name) into the full environment within a project, over the Admin API. -func resolveEnvironment(cmd *cobra.Command, pc *projectContext, cred *activeCredential, projectID int) (api.Environment, error) { +func environmentReference(pc *projectContext) (string, error) { ref, _ := pc.Environment.Value.(string) if ref == "" { // The SDK credential doubles as an environment reference, host-scoped @@ -88,11 +88,19 @@ func resolveEnvironment(cmd *cobra.Command, pc *projectContext, cred *activeCred // environment over the Admin API. Name the variable, never its value: // it is a secret and must stay out of stderr and CI logs. if strings.HasPrefix(ref, "ser.") { - return api.Environment{}, withHint( + return "", withHint( fmt.Errorf("%s holds a server-side key, which cannot identify an environment for Admin commands", name), "Pass -e, set FLAGSMITH_ENVIRONMENT, or run `flagsmith init`.") } } + return ref, nil +} + +func resolveEnvironment(cmd *cobra.Command, pc *projectContext, cred *activeCredential, projectID int) (api.Environment, error) { + ref, err := environmentReference(pc) + if err != nil { + return api.Environment{}, err + } if ref == "" { return api.Environment{}, withHint(errors.New("no environment"), "Pass -e, set FLAGSMITH_ENVIRONMENT, or run `flagsmith init`.") @@ -203,6 +211,43 @@ func resolveEnvironmentRef(cmd *cobra.Command, cred *activeCredential, projectID return nil, notFound } +// resolveEnvironmentWithProject keeps explicit project scoping and otherwise +// looks up the project directly from a client-side environment key. +func resolveEnvironmentWithProject(cmd *cobra.Command, pc *projectContext, cred *activeCredential, ref string, full bool) (*api.Environment, error) { + if pc.Project.Value != nil { + projectID, err := resolveProjectID(cmd, pc, cred) + if err != nil { + return nil, err + } + env, err := resolveEnvironmentRef(cmd, cred, projectID, ref) + if err != nil || !full { + return env, err + } + return cred.client().GetEnvironment(cmd.Context(), env.APIKey) + } + + noProject := withHint(errors.New("no project"), + "Pass a client-side environment key, set --project, or set `project` in flagsmith.json. Environment names require a project.") + if strings.HasPrefix(ref, "ser.") { + return nil, withHint( + errors.New("the environment reference takes a client-side key, not a server-side one"), + hintServerSideKey()) + } + if !environmentKeyShape.MatchString(ref) { + return nil, noProject + } + + env, err := cred.client().GetEnvironment(cmd.Context(), ref) + if api.IsNotFound(err) { + return nil, noProject + } + if err != nil { + return nil, err + } + _ = cache.Merge(apiURL, &cache.Names{Environments: map[string]string{env.APIKey: env.Name}}) + return env, nil +} + // resolveProjectID turns the project reference (an id or a name) into an id. func resolveProjectID(cmd *cobra.Command, pc *projectContext, cred *activeCredential) (int, error) { if id, ok := pc.Project.Value.(int); ok { From 650868247df67659cab6e4f2eb17d8fd6fa9fba0 Mon Sep 17 00:00:00 2001 From: Aditya030207 <230317630+Aditya030207@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:58:39 +0530 Subject: [PATCH 2/2] docs: describe environment reference lookup --- internal/cmd/resolve.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/cmd/resolve.go b/internal/cmd/resolve.go index 22ebdfc..df2674e 100644 --- a/internal/cmd/resolve.go +++ b/internal/cmd/resolve.go @@ -74,8 +74,8 @@ func pickCandidate(cmd *cobra.Command, entity, idKind, ref string, candidates [] return candidates[idx], nil } -// resolveEnvironment turns the environment context reference (a client-side key -// or a name) into the full environment within a project, over the Admin API. +// environmentReference returns the configured environment name or client-side key, +// falling back to the SDK credential when no reference is configured. func environmentReference(pc *projectContext) (string, error) { ref, _ := pc.Environment.Value.(string) if ref == "" { @@ -96,6 +96,7 @@ func environmentReference(pc *projectContext) (string, error) { return ref, nil } +// resolveEnvironment looks up the configured environment within a project. func resolveEnvironment(cmd *cobra.Command, pc *projectContext, cred *activeCredential, projectID int) (api.Environment, error) { ref, err := environmentReference(pc) if err != nil {