Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions internal/api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
57 changes: 57 additions & 0 deletions internal/cmd/cmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
46 changes: 18 additions & 28 deletions internal/cmd/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 <environment>",
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)
},
}
Expand Down Expand Up @@ -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
}
Expand All @@ -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
}
Expand All @@ -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
}
Expand Down
11 changes: 11 additions & 0 deletions internal/cmd/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
54 changes: 50 additions & 4 deletions internal/cmd/resolve.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ 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.
func resolveEnvironment(cmd *cobra.Command, pc *projectContext, cred *activeCredential, projectID int) (api.Environment, error) {
// 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) {
Comment thread
Aditya030207 marked this conversation as resolved.
Resolved
ref, _ := pc.Environment.Value.(string)
if ref == "" {
// The SDK credential doubles as an environment reference, host-scoped
Expand All @@ -88,11 +88,20 @@ 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
}

// 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 {
return api.Environment{}, err
}
if ref == "" {
return api.Environment{}, withHint(errors.New("no environment"),
"Pass -e, set FLAGSMITH_ENVIRONMENT, or run `flagsmith init`.")
Expand Down Expand Up @@ -203,6 +212,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 {
Expand Down