Skip to content
Merged
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
8 changes: 6 additions & 2 deletions internal/api/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
9 changes: 6 additions & 3 deletions internal/api/wrappers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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 {
Expand Down
23 changes: 19 additions & 4 deletions internal/cmd/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ const (
keysResultPadding = 12
)

var keysCreateModeFlag string
var (
keysCreateModeFlag string
keysCreateNameFlag string
)

var keysCmd = &cobra.Command{
Use: "keys",
Expand Down Expand Up @@ -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-<hostname>)")

keysCmd.AddCommand(keysListCmd)
keysCmd.AddCommand(keysCreateCmd)
Expand Down Expand Up @@ -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)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/cmd/keys_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand All @@ -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"`) {
Expand Down
149 changes: 149 additions & 0 deletions internal/cmd/mode.go
Original file line number Diff line number Diff line change
@@ -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)
}
11 changes: 10 additions & 1 deletion internal/tui/repl.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"runtime"
"strings"
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -1226,7 +1235,7 @@ func (repl REPLModel) executeKeysCreateCommand(modeArg string) tea.Cmd {
return commandErrorMsg{errorText: "Usage: keys create <LIVE|TEST>"}
}

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())}
}
Expand Down
Loading