diff --git a/convox.yml b/convox.yml index 36dfd4f3..d1dc86b1 100644 --- a/convox.yml +++ b/convox.yml @@ -30,7 +30,7 @@ services: # Pinned to an immutable release tag. scripts/bump-version.sh sets it to the new # version (:vX.Y.Z); the release workflow publishes that tag when the v* git tag is pushed. # :e327add is the v0.1.1 release (identical to :latest when this was pinned). - image: docker.io/docspringcom/rack-gateway:v0.1.33 + image: docker.io/docspringcom/rack-gateway:v0.1.34 command: ./scripts/start-gateway.sh environment: - PORT=8080 @@ -54,7 +54,7 @@ services: admin: # Uses same image as gateway service (kept in sync by scripts/bump-version.sh) - image: docker.io/docspringcom/rack-gateway:v0.1.33 + image: docker.io/docspringcom/rack-gateway:v0.1.34 command: echo "Use this service to run migrations, database admin tasks, etc." environment: - PORT=8080 diff --git a/docs/src/content/docs/integrations/deploy-approvals/index.mdx b/docs/src/content/docs/integrations/deploy-approvals/index.mdx index d36da152..8ef3098e 100644 --- a/docs/src/content/docs/integrations/deploy-approvals/index.mdx +++ b/docs/src/content/docs/integrations/deploy-approvals/index.mdx @@ -286,6 +286,9 @@ pending request can be approved; one that is already approved or deployed counts # Every listed app's request for the commit, on every listed rack rack-gateway deploy-approval approve --app web,worker --commit --rack us,eu +# The same, with one --rack per rack +rack-gateway deploy-approval approve --app web,worker --commit --rack us --rack eu + # Every app's request for the commit rack-gateway deploy-approval approve --all-apps --commit --rack staging ``` diff --git a/docs/src/content/docs/user-guide/cli/commands.mdx b/docs/src/content/docs/user-guide/cli/commands.mdx index 71c411e1..124edac2 100644 --- a/docs/src/content/docs/user-guide/cli/commands.mdx +++ b/docs/src/content/docs/user-guide/cli/commands.mdx @@ -13,7 +13,7 @@ These flags work with any command: | Flag | Short | Description | |------|-------|-------------| -| `--rack` | `-r` | Override the current rack (deploy approval commands accept a comma-separated list, or `all`) | +| `--rack` | `-r` | Override the current rack. Deploy approval commands take several: repeat `--rack`, give a comma-separated list, or use `all` | | `--config` | | Override config directory | | `--api-token` | | Use API token for authentication | | `--mfa-code` | | Provide MFA code for step-up auth | diff --git a/docs/src/content/docs/user-guide/cli/multi-rack.mdx b/docs/src/content/docs/user-guide/cli/multi-rack.mdx index f91ef5ef..7d96b81d 100644 --- a/docs/src/content/docs/user-guide/cli/multi-rack.mdx +++ b/docs/src/content/docs/user-guide/cli/multi-rack.mdx @@ -74,7 +74,8 @@ rack-gateway logs -a myapp -r eu-prod ``` The `--rack` flag doesn't change your default; it only affects that one command. Deploy approval commands also -take a comma-separated list of racks, or `all`. +take several racks: repeat the flag (`--rack us --rack eu`), separate names with commas (`--rack us,eu`), or use +`all`. Repeated racks count once. Commands that use one rack refuse several, rather than picking one of them. ## Environment Variable Override diff --git a/internal/cli/AGENTS.md b/internal/cli/AGENTS.md index 39b28226..8c5fbf7a 100644 --- a/internal/cli/AGENTS.md +++ b/internal/cli/AGENTS.md @@ -114,6 +114,12 @@ cx deploy-approval approve --app web,worker --commit <40-char sha> --rack us,eu The `all` value expands to all configured racks in `gateways`, excluding any racks listed in `all_racks_exclude`. This is useful for avoiding local development racks when operating on production infrastructure. +`--rack` is a `rackFlagValue` (`rack_flag.go`): a repeated flag adds to the list instead of replacing it, so +`--rack us --rack eu`, `--rack us,eu` and `--rack us --rack us,eu` all select US and EU (`parseRackList` drops +repeats, keeping the order given). Deploy approval commands read the list through `resolveRacks`. Every other command +uses `SelectedRack`, which refuses several racks: a plain string flag kept only the last `--rack`, so +`approve --rack us --rack eu` once approved EU alone with no warning. Login refuses rack names with commas. + Without `--commit`, deploy approval commands use the full SHA of `HEAD` (`git rev-parse HEAD`): the gateway matches `--commit` as a prefix, so a short SHA could also match another commit's request. `wait --approve` in a terminal asks for y/N on every request whose commit isn't exactly the full `--commit` (found by `--branch`, or by a short diff --git a/internal/cli/cli_login.go b/internal/cli/cli_login.go index 0374d63b..f3e2a696 100644 --- a/internal/cli/cli_login.go +++ b/internal/cli/cli_login.go @@ -132,8 +132,8 @@ func resolveLoginTarget(args []string) (string, string, error) { return rack, gatewayURL, nil case 1: rack := rackArg - if rack == "" { - return "", "", fmt.Errorf("rack name cannot be empty") + if err := checkLoginRackName(rack); err != nil { + return "", "", err } gatewayURL, err := resolveLoginGatewayURL(rack) if err != nil { @@ -143,8 +143,8 @@ func resolveLoginTarget(args []string) (string, string, error) { case 2: rack := rackArg gatewayURL := gatewayArg - if rack == "" { - return "", "", fmt.Errorf("rack name cannot be empty") + if err := checkLoginRackName(rack); err != nil { + return "", "", err } if gatewayURL == "" { return "", "", fmt.Errorf("gateway URL cannot be empty") @@ -155,6 +155,17 @@ func resolveLoginTarget(args []string) (string, string, error) { } } +// checkLoginRackName refuses a rack name that --rack couldn't select: --rack separates rack names with commas. +func checkLoginRackName(rack string) error { + if rack == "" { + return fmt.Errorf("rack name cannot be empty") + } + if strings.Contains(rack, ",") { + return fmt.Errorf("rack name %q can't contain a comma: --rack uses commas to separate racks", rack) + } + return nil +} + func normalizeLoginArgs(args []string) (string, string) { var rack string var gatewayURL string diff --git a/internal/cli/deploy_approvals_approve.go b/internal/cli/deploy_approvals_approve.go index 8d11c79b..31223f6e 100644 --- a/internal/cli/deploy_approvals_approve.go +++ b/internal/cli/deploy_approvals_approve.go @@ -43,6 +43,8 @@ app on every listed rack, shows them, and approves the pending ones: one PIN, th Requests that are already approved or deployed count as done. If a listed app has no request on a listed rack, nothing is approved and the command fails. +--rack takes several racks: repeat it (--rack us --rack eu), separate names with commas (--rack us,eu), or use all. + From a terminal it asks for Enter first. Without a terminal (scripts, AI agents) it doesn't, and it needs an explicit --app list and a full 40-character --commit (no --branch or --all-apps). The macOS PIN dialog then lists every approval the command makes (branch, app, rack, commit and message) above the command line. @@ -66,6 +68,9 @@ Examples: # Approve two apps' requests for a commit on US and EU (one PIN, one touch per approval) cx deploy-approval approve --app web,worker --commit --rack us,eu + # The same, with one --rack per rack + cx deploy-approval approve --app web,worker --commit --rack us --rack eu + # Approve every app's request for a commit cx deploy-approval approve --all-apps --commit --rack staging`, Args: cobra.MaximumNArgs(1), diff --git a/internal/cli/deploy_approvals_list.go b/internal/cli/deploy_approvals_list.go index 312ef66b..6dd95f34 100644 --- a/internal/cli/deploy_approvals_list.go +++ b/internal/cli/deploy_approvals_list.go @@ -26,7 +26,9 @@ func newDeployApprovalListCommand() *cobra.Command { cmd := &cobra.Command{ Use: "list", Short: "List deploy approval requests", - Long: "List deploy approval requests with optional filtering by status, app and commit.", + Long: `List deploy approval requests with optional filtering by status, app and commit. + +--rack takes several racks: repeat it (--rack us --rack eu), separate names with commas (--rack us,eu), or use all.`, RunE: func(cmd *cobra.Command, _ []string) error { return executeDeployApprovalList(cmd, opts) }, diff --git a/internal/cli/deploy_approvals_shared.go b/internal/cli/deploy_approvals_shared.go index 5a34d3b0..07b47015 100644 --- a/internal/cli/deploy_approvals_shared.go +++ b/internal/cli/deploy_approvals_shared.go @@ -9,6 +9,7 @@ import ( "net/url" "os" "os/exec" + "slices" "strings" "time" @@ -143,28 +144,33 @@ var errGatewayURLWithManyRacks = errors.New( "RACK_GATEWAY_URL names a single gateway; unset it to use --rack all or a list of racks", ) -// resolveRacks parses the selected rack. Deploy approval commands accept comma-separated rack names -// through the global --rack flag. Special value "all" expands to all configured racks. RACK_GATEWAY_URL names one -// gateway, so it is refused with several racks: each rack's request would go to that one host. +// errAllWithOtherRacks explains why "all" can't be listed with rack names. +var errAllWithOtherRacks = errors.New("--rack all already selects every rack; don't list other racks with it") + +// resolveRacks parses the selected racks for deploy approval commands: the global --rack flag, repeated or with +// comma-separated names, or RACK_GATEWAY_RACK (rackSelection). Repeats are dropped, keeping the order given. The +// special value "all" expands to all configured racks. RACK_GATEWAY_URL names one gateway, so it is refused with +// several racks: each rack's request would go to that one host. func resolveRacks() ([]string, error) { - rack, err := SelectedRack() + selection, err := rackSelection() if err != nil { return nil, err } - trimmed := strings.TrimSpace(rack) + racks, err := parseRackList(selection) + if err != nil { + return nil, err + } envURL := strings.TrimSpace(os.Getenv("RACK_GATEWAY_URL")) - if trimmed == "all" { + if slices.Contains(racks, "all") { + if len(racks) > 1 { + return nil, errAllWithOtherRacks + } if envURL != "" { return nil, errGatewayURLWithManyRacks } return expandAllRacks() } - - racks, err := parseRackList(trimmed) - if err != nil { - return nil, err - } if envURL != "" { // The rack name is a label for that gateway, and LoadRackAuth checks it against a stored session. if len(racks) > 1 { @@ -178,21 +184,6 @@ func resolveRacks() ([]string, error) { return racks, nil } -func parseRackList(raw string) ([]string, error) { - parts := strings.Split(raw, ",") - racks := make([]string, 0, len(parts)) - for _, part := range parts { - value := strings.TrimSpace(part) - if value != "" { - racks = append(racks, value) - } - } - if len(racks) == 0 { - return nil, fmt.Errorf("no valid rack names provided") - } - return racks, nil -} - // expandAllRacks returns all configured racks except those in all_racks_exclude. func expandAllRacks() ([]string, error) { cfg, _, err := LoadConfig() diff --git a/internal/cli/deploy_approvals_show.go b/internal/cli/deploy_approvals_show.go index 835d9dcb..3c5ef2a8 100644 --- a/internal/cli/deploy_approvals_show.go +++ b/internal/cli/deploy_approvals_show.go @@ -29,6 +29,8 @@ func newDeployApprovalShowCommand() *cobra.Command { If no ID is provided, searches for the latest approval request matching the current app and git branch. Use --branch or --commit to search by specific criteria instead. +--rack takes several racks: repeat it (--rack us --rack eu), separate names with commas (--rack us,eu), or use all. + Examples: # Show by ID cx deploy-approval show abc123-def456-... diff --git a/internal/cli/deploy_approvals_wait.go b/internal/cli/deploy_approvals_wait.go index 5677d2c3..e31b5a55 100644 --- a/internal/cli/deploy_approvals_wait.go +++ b/internal/cli/deploy_approvals_wait.go @@ -29,6 +29,8 @@ In a terminal, --approve asks you to confirm (y/N) each request whose commit isn --branch and no --commit it finds the newest request for the branch whatever its commit, and a short --commit matches any commit that starts with it. +--rack takes several racks: repeat it (--rack us --rack eu), separate names with commas (--rack us,eu), or use all. + Examples: # Approve two apps' requests for a commit on staging (one PIN, one touch per approval) rack-gateway deploy-approval wait --approve --app web,worker --commit --rack staging`, diff --git a/internal/cli/rack.go b/internal/cli/rack.go index 657e52ad..71406a9b 100644 --- a/internal/cli/rack.go +++ b/internal/cli/rack.go @@ -30,8 +30,27 @@ func currentRack() (string, error) { return GetCurrentRack() } -// SelectedRack determines which rack to use based on flags, env vars, or config +// SelectedRack is the one rack a command uses: --rack, else RACK_GATEWAY_RACK, else the current rack. Several racks +// (a repeated --rack, or comma-separated names) are refused rather than using one of them and ignoring the rest; +// deploy approval commands take several through resolveRacks. func SelectedRack() (string, error) { + selection, err := rackSelection() + if err != nil || !strings.Contains(selection, ",") { + return selection, err + } + racks, err := parseRackList(selection) + if err != nil { + return "", err + } + if len(racks) > 1 { + return "", fmt.Errorf("this command uses one rack, but several were selected: %s", strings.Join(racks, ", ")) + } + return racks[0], nil +} + +// rackSelection is the rack selection as given: --rack (several racks are joined with commas), else +// RACK_GATEWAY_RACK, else the current rack. +func rackSelection() (string, error) { if RackFlag != "" { return RackFlag, nil } diff --git a/internal/cli/rack_flag.go b/internal/cli/rack_flag.go new file mode 100644 index 00000000..3514ce35 --- /dev/null +++ b/internal/cli/rack_flag.go @@ -0,0 +1,64 @@ +package cli + +import ( + "fmt" + "strings" + + "github.com/spf13/pflag" +) + +const rackFlagHelp = "Rack to use. Deploy approval commands take several: repeat --rack, " + + "give a comma-separated list, or all" + +// rackFlagValue is the global --rack flag. A repeated flag adds to the list instead of replacing it, so +// `--rack us --rack eu` selects the same racks as `--rack us,eu`. Deploy approval commands act on each rack +// (resolveRacks), and commands that use one rack refuse a list (SelectedRack) instead of quietly using the last. +type rackFlagValue struct { + value *string + set bool +} + +// addRackFlag registers --rack (-r) on flags, storing the selection in target. +func addRackFlag(flags *pflag.FlagSet, target *string) { + *target = "" + flags.VarP(&rackFlagValue{value: target}, "rack", "r", rackFlagHelp) +} + +func (r *rackFlagValue) String() string { + if r.value == nil { + return "" + } + return *r.value +} + +func (r *rackFlagValue) Set(value string) error { + if r.set { + *r.value += "," + value + } else { + *r.value = value + r.set = true + } + return nil +} + +func (*rackFlagValue) Type() string { + return "string" +} + +// parseRackList splits a rack selection on commas, dropping blanks and repeats and keeping the order given. +func parseRackList(raw string) ([]string, error) { + parts := strings.Split(raw, ",") + racks := make([]string, 0, len(parts)) + seen := make(map[string]bool, len(parts)) + for _, part := range parts { + value := strings.TrimSpace(part) + if value != "" && !seen[value] { + seen[value] = true + racks = append(racks, value) + } + } + if len(racks) == 0 { + return nil, fmt.Errorf("no valid rack names provided") + } + return racks, nil +} diff --git a/internal/cli/rack_flag_test.go b/internal/cli/rack_flag_test.go new file mode 100644 index 00000000..5ba4452b --- /dev/null +++ b/internal/cli/rack_flag_test.go @@ -0,0 +1,129 @@ +package cli + +import ( + "testing" + + "github.com/stretchr/testify/require" +) + +// parseRootFlags parses args with the real root command's global flags, as the CLI does before running a command. +func parseRootFlags(t *testing.T, args ...string) { + t.Helper() + require.NoError(t, newRootCommand().PersistentFlags().Parse(args)) +} + +func withRackConfig(t *testing.T) { + t.Helper() + withCLIConfig(t, Config{Gateways: map[string]GatewayConfig{ + "staging": {URL: "https://rack-gateway-staging.example.com"}, + "us": {URL: "https://rack-gateway-us.example.com"}, + "eu": {URL: "https://rack-gateway-eu.example.com"}, + }}) +} + +// A repeated --rack used to keep only its last value, so `approve --rack us --rack eu` approved EU alone, with no +// warning. Repeating the flag and listing racks with commas must select the same racks. +func TestResolveRacksTakesRepeatedAndCommaSeparatedRackFlags(t *testing.T) { + cases := []struct { + name string + args []string + want []string + }{ + {"repeated", []string{"--rack", "us", "--rack", "eu"}, []string{"us", "eu"}}, + {"short and long", []string{"-r", "us", "--rack=eu"}, []string{"us", "eu"}}, + {"comma-separated", []string{"--rack", "us,eu"}, []string{"us", "eu"}}, + {"mixed", []string{"--rack", "staging", "--rack", "us,eu"}, []string{"staging", "us", "eu"}}, + {"order given", []string{"--rack", "eu", "-r", "staging,us"}, []string{"eu", "staging", "us"}}, + {"duplicates", []string{"--rack", "us", "--rack", "us, eu", "-r", "eu"}, []string{"us", "eu"}}, + {"blank values", []string{"--rack", "us", "--rack", "", "--rack", " ,eu,"}, []string{"us", "eu"}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + withRackConfig(t) + parseRootFlags(t, tc.args...) + + racks, err := resolveRacks() + + require.NoError(t, err) + require.Equal(t, tc.want, racks) + }) + } +} + +func TestResolveRacksTakesRepeatedAll(t *testing.T) { + withRackConfig(t) + parseRootFlags(t, "--rack", "all", "--rack", "all") + + racks, err := resolveRacks() + + require.NoError(t, err) + require.ElementsMatch(t, []string{"staging", "us", "eu"}, racks) +} + +func TestResolveRacksRefusesAllWithOtherRacks(t *testing.T) { + for _, args := range [][]string{ + {"--rack", "all", "--rack", "us"}, + {"--rack", "us", "--rack", "all"}, + {"--rack", "all,eu"}, + } { + withRackConfig(t) + parseRootFlags(t, args...) + + _, err := resolveRacks() + + require.ErrorIs(t, err, errAllWithOtherRacks, args) + } +} + +// Commands that use one rack must refuse several rather than quietly use one of them. +func TestSelectedRackRefusesSeveralRacks(t *testing.T) { + for _, args := range [][]string{ + {"--rack", "us", "--rack", "eu"}, + {"--rack", "us,eu"}, + {"--rack", "us", "-r", "us,eu"}, + } { + withRackConfig(t) + parseRootFlags(t, args...) + + _, err := SelectedRack() + + require.EqualError(t, err, "this command uses one rack, but several were selected: us, eu", args) + } +} + +func TestSelectedRackRefusesSeveralRacksFromTheEnvironment(t *testing.T) { + withRackConfig(t) + t.Setenv("RACK_GATEWAY_RACK", "us,eu") + + _, err := SelectedRack() + + require.EqualError(t, err, "this command uses one rack, but several were selected: us, eu") +} + +func TestSelectedRackTakesOneRackNamedMoreThanOnce(t *testing.T) { + for _, args := range [][]string{ + {"--rack", "us"}, + {"--rack", "us", "--rack", "us"}, + {"--rack", "us,us"}, + {"--rack", "us", "--rack", ""}, + } { + withRackConfig(t) + parseRootFlags(t, args...) + + rack, err := SelectedRack() + + require.NoError(t, err, args) + require.Equal(t, "us", rack, args) + } +} + +// --rack couldn't select a rack whose name has a comma, so login refuses one. +func TestLoginRefusesRackNameWithComma(t *testing.T) { + withRackConfig(t) + + for _, args := range [][]string{{"us,eu"}, {"us,eu", "https://rack-gateway-us.example.com"}} { + _, _, err := resolveLoginTarget(args) + + require.EqualError(t, err, `rack name "us,eu" can't contain a comma: --rack uses commas to separate racks`) + } +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 6236dc4e..12921d5c 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -6,6 +6,11 @@ import ( // Execute runs the root command func Execute() error { + return explainRefusedHandshake(newRootCommand().Execute()) +} + +// newRootCommand builds the root command with its global flags and every subcommand. +func newRootCommand() *cobra.Command { rootCmd := &cobra.Command{ Use: "rack-gateway", Short: "API gateway for Convox with authentication and RBAC", @@ -39,8 +44,7 @@ Rack management: // Global flags rootCmd.PersistentFlags().StringVar(&ConfigPath, "config", ConfigPath, "Config directory") - rootCmd.PersistentFlags(). - StringVarP(&RackFlag, "rack", "r", "", "Rack to use (deploy approvals accept comma-separated names or all)") + addRackFlag(rootCmd.PersistentFlags(), &RackFlag) rootCmd.PersistentFlags(). StringVar(&APITokenFlag, "api-token", "", "API token for CLI requests (overrides RACK_GATEWAY_API_TOKEN)") rootCmd.PersistentFlags(). @@ -93,5 +97,5 @@ Rack management: InstancesCommand(), ) - return explainRefusedHandshake(rootCmd.Execute()) + return rootCmd } diff --git a/web/package.json b/web/package.json index b8f2c95f..505a0f3a 100644 --- a/web/package.json +++ b/web/package.json @@ -1,6 +1,6 @@ { "name": "web", - "version": "0.1.33", + "version": "0.1.34", "private": true, "type": "module", "scripts": {