diff --git a/internal/api/keys.go b/internal/api/keys.go index 0f8dc0f..083dcb6 100644 --- a/internal/api/keys.go +++ b/internal/api/keys.go @@ -31,15 +31,19 @@ func (client *Client) ListAPIKeys() ([]APIKeyInfo, error) { return apiKeys, nil } -func (client *Client) CreateAPIKey(mode string) (*GeneratedAPIKey, error) { +func (client *Client) CreateAPIKey(mode, name string) (*GeneratedAPIKey, error) { if mode == "" { return nil, fmt.Errorf("mode cannot be empty — use 'live' or 'test'") } + if name == "" { + return nil, fmt.Errorf("name cannot be empty — describe where the key will be used") + } path := fmt.Sprintf("%s?mode=%s", apiKeysBasePath, mode) + body := map[string]string{"name": name} var generatedKey GeneratedAPIKey - if postError := client.Post(path, nil, &generatedKey); postError != nil { + if postError := client.Post(path, body, &generatedKey); postError != nil { return nil, fmt.Errorf("failed to create API key: %w", postError) } diff --git a/internal/api/wrappers_test.go b/internal/api/wrappers_test.go index 1a2c95e..7ccf0bb 100644 --- a/internal/api/wrappers_test.go +++ b/internal/api/wrappers_test.go @@ -137,12 +137,15 @@ func TestWrappers_HappyPaths(t *testing.T) { if _, err := client.ListAPIKeys(); err != nil { t.Errorf("ListAPIKeys: %v", err) } - if _, err := client.CreateAPIKey("test"); err != nil { + if _, err := client.CreateAPIKey("test", "ci-test"); err != nil { t.Errorf("CreateAPIKey: %v", err) } - if _, err := client.CreateAPIKey(""); err == nil { + if _, err := client.CreateAPIKey("", "ci-test"); err == nil { t.Error("CreateAPIKey must reject empty mode") } + if _, err := client.CreateAPIKey("test", ""); err == nil { + t.Error("CreateAPIKey must reject empty name") + } if err := client.RevokeAPIKey("k1"); err != nil { t.Errorf("RevokeAPIKey: %v", err) } @@ -242,7 +245,7 @@ func TestWrappers_ServerErrorBubblesUp(t *testing.T) { }}, {"GetContactStats", func() error { _, err := client.GetContactStats(); return err }}, {"ListAPIKeys", func() error { _, err := client.ListAPIKeys(); return err }}, - {"CreateAPIKey", func() error { _, err := client.CreateAPIKey("test"); return err }}, + {"CreateAPIKey", func() error { _, err := client.CreateAPIKey("test", "n"); return err }}, {"RevokeAPIKey", func() error { return client.RevokeAPIKey("k1") }}, {"ListNumbers", func() error { _, err := client.ListNumbers(); return err }}, {"CreateCampaign", func() error { diff --git a/internal/cmd/keys.go b/internal/cmd/keys.go index ceaf7f2..85f670c 100644 --- a/internal/cmd/keys.go +++ b/internal/cmd/keys.go @@ -19,7 +19,10 @@ const ( keysResultPadding = 12 ) -var keysCreateModeFlag string +var ( + keysCreateModeFlag string + keysCreateNameFlag string +) var keysCmd = &cobra.Command{ Use: "keys", @@ -48,6 +51,7 @@ var keysRevokeCmd = &cobra.Command{ func init() { keysCreateCmd.Flags().StringVar(&keysCreateModeFlag, "mode", defaultKeyMode, "key mode: LIVE or TEST") + keysCreateCmd.Flags().StringVar(&keysCreateNameFlag, "name", "", "human-readable label (defaults to cli-)") keysCmd.AddCommand(keysListCmd) keysCmd.AddCommand(keysCreateCmd) @@ -101,11 +105,22 @@ func runKeysCreate(command *cobra.Command, arguments []string) error { } client.SetVerbose(IsVerbose()) - return runKeysCreateImpl(client, GetOutputFormat(), os.Stdout, normalizedMode) + return runKeysCreateImpl(client, GetOutputFormat(), os.Stdout, normalizedMode, resolveKeyName(keysCreateNameFlag)) +} + +func resolveKeyName(flag string) string { + if trimmed := strings.TrimSpace(flag); trimmed != "" { + return trimmed + } + hostname, hostError := os.Hostname() + if hostError != nil || hostname == "" { + return "cli" + } + return "cli-" + hostname } -func runKeysCreateImpl(client *api.Client, format output.Format, writer io.Writer, normalizedMode string) error { - generatedKey, createError := client.CreateAPIKey(normalizedMode) +func runKeysCreateImpl(client *api.Client, format output.Format, writer io.Writer, normalizedMode, name string) error { + generatedKey, createError := client.CreateAPIKey(normalizedMode, name) if createError != nil { return fmt.Errorf("create API key: %w", createError) } diff --git a/internal/cmd/keys_test.go b/internal/cmd/keys_test.go index 52fc25b..e5cfbc0 100644 --- a/internal/cmd/keys_test.go +++ b/internal/cmd/keys_test.go @@ -105,7 +105,7 @@ func TestRunKeysCreateImpl_GoldenPathRendersKey(t *testing.T) { _, client := fakeAPIServerJSON(t, http.StatusCreated, body) buffer := &bytes.Buffer{} - if err := runKeysCreateImpl(client, output.FormatText, buffer, "LIVE"); err != nil { + if err := runKeysCreateImpl(client, output.FormatText, buffer, "LIVE", "test-key"); err != nil { t.Fatalf("err: %v", err) } if !strings.Contains(buffer.String(), "ara_live_brandnewfreshkeyxyz") { @@ -118,7 +118,7 @@ func TestRunKeysCreateImpl_JSONOutput(t *testing.T) { _, client := fakeAPIServerJSON(t, http.StatusOK, body) buffer := &bytes.Buffer{} - if err := runKeysCreateImpl(client, output.FormatJSON, buffer, "TEST"); err != nil { + if err := runKeysCreateImpl(client, output.FormatJSON, buffer, "TEST", "test-key"); err != nil { t.Fatalf("err: %v", err) } if !strings.Contains(buffer.String(), `"plainTextKey"`) { diff --git a/internal/cmd/mode.go b/internal/cmd/mode.go new file mode 100644 index 0000000..033808f --- /dev/null +++ b/internal/cmd/mode.go @@ -0,0 +1,149 @@ +package cmd + +import ( + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/ararahq/cli/internal/config" + "github.com/ararahq/cli/internal/output" +) + +var modeCmd = &cobra.Command{ + Use: "mode [live|test]", + Short: "Switch the active profile between LIVE and TEST", + Long: `Show the active profile mode, or switch between LIVE and TEST without +copying API keys around. + + arara mode show the current mode + arara mode live create (or reuse) a LIVE key and persist it in the keyring + arara mode test drop the LIVE key and fall back to TEST (re-run 'arara login' to refresh the OAuth session) + +This command authenticates with whatever credential is already configured +(OAuth session or existing API key) and stores the result in the OS keyring. +The plaintext key is never printed.`, + Args: cobra.MaximumNArgs(1), + RunE: runMode, +} + +func init() { + rootCmd.AddCommand(modeCmd) +} + +func runMode(_ *cobra.Command, arguments []string) error { + if len(arguments) == 0 { + return showCurrentMode() + } + + target := strings.ToLower(strings.TrimSpace(arguments[0])) + switch target { + case "live": + return promoteToLive() + case "test": + return demoteToTest() + default: + return fmt.Errorf("invalid mode %q -- use 'live' or 'test'", arguments[0]) + } +} + +func showCurrentMode() error { + configuration, loadError := config.Load() + if loadError != nil { + return loadError + } + profileName := configuration.CurrentProfile + if profileName == "" { + profileName = "default" + } + profile := configuration.Profiles[profileName] + mode := strings.ToUpper(profile.Mode) + if mode == "" { + mode = strings.ToUpper(config.DefaultMode) + } + fmt.Fprintf(os.Stdout, "Profile %s -- %s\n", profileName, mode) + return nil +} + +func promoteToLive() error { + client, clientError := newClientForCmd() + if clientError != nil { + output.PrintError(fmt.Sprintf("Failed to create API client: %s", clientError.Error())) + return clientError + } + client.SetVerbose(IsVerbose()) + + if client.IsLiveMode() { + output.PrintInfo("Already in LIVE mode.") + return nil + } + + generatedKey, createError := client.CreateAPIKey("LIVE", resolveKeyName("")) + if createError != nil { + output.PrintError(fmt.Sprintf("Failed to create LIVE key: %s", createError.Error())) + return createError + } + + profileName := GetProfile() + if storeError := config.StoreAPIKey(profileName, generatedKey.PlainTextKey); storeError != nil { + output.PrintError(fmt.Sprintf("Failed to store LIVE key: %s", storeError.Error())) + return storeError + } + + if updateError := updateProfileMode(profileName, "live", config.AuthTypeAPIKey); updateError != nil { + output.PrintError(fmt.Sprintf("Failed to update profile: %s", updateError.Error())) + return updateError + } + + output.PrintSuccess(fmt.Sprintf("Switched profile %q to LIVE.", profileName)) + output.PrintInfo("Run 'arara mode test' to revert.") + return nil +} + +func demoteToTest() error { + profileName := GetProfile() + configuration, loadError := config.Load() + if loadError != nil { + return loadError + } + profile := configuration.Profiles[profileName] + + if strings.EqualFold(profile.Mode, "test") { + output.PrintInfo("Already in TEST mode.") + return nil + } + + if deleteError := config.DeleteAPIKey(profileName); deleteError != nil { + output.PrintError(fmt.Sprintf("Failed to remove LIVE key from keyring: %s", deleteError.Error())) + return deleteError + } + + if updateError := updateProfileMode(profileName, "test", config.AuthTypeOAuth); updateError != nil { + output.PrintError(fmt.Sprintf("Failed to update profile: %s", updateError.Error())) + return updateError + } + + output.PrintSuccess(fmt.Sprintf("Switched profile %q to TEST.", profileName)) + output.PrintInfo("Run 'arara login' to refresh the OAuth session before making requests.") + return nil +} + +func updateProfileMode(profileName, mode, authType string) error { + configuration, loadError := config.Load() + if loadError != nil { + return loadError + } + profile, exists := configuration.Profiles[profileName] + if !exists { + profile = config.Profile{ + APIURL: config.DefaultAPIURL, + Mode: config.DefaultMode, + } + } + profile.Mode = mode + profile.AuthType = authType + configuration.Profiles[profileName] = profile + configuration.CurrentProfile = profileName + return config.Save(configuration) +} diff --git a/internal/tui/repl.go b/internal/tui/repl.go index cfd8373..b0f2d63 100644 --- a/internal/tui/repl.go +++ b/internal/tui/repl.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "os" "os/exec" "runtime" "strings" @@ -424,6 +425,14 @@ func renderModeBadge(mode string) string { return sTestBadge.Render(" TEST ") } +func replKeyName() string { + hostname, err := os.Hostname() + if err != nil || hostname == "" { + return "cli" + } + return "cli-" + hostname +} + // ── Output Area ────────────────────────────────────────────────── func (repl *REPLModel) appendOutput(text string) { @@ -1226,7 +1235,7 @@ func (repl REPLModel) executeKeysCreateCommand(modeArg string) tea.Cmd { return commandErrorMsg{errorText: "Usage: keys create "} } - generatedKey, createError := repl.apiClient.CreateAPIKey(mode) + generatedKey, createError := repl.apiClient.CreateAPIKey(mode, replKeyName()) if createError != nil { return commandErrorMsg{errorText: fmt.Sprintf("Failed to create key: %s", createError.Error())} }