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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ namespace: ""
```

Sensitive fields (`username`, `password`, `accessKey`, `secretKey`, and
`securityToken`) are encrypted with AES-256-GCM before being saved by the CLI.
`securityToken`, and `token`) are encrypted with AES-256-GCM before being saved by the CLI.
The local encryption key is stored at `~/.nacos-cli/key` with `0600`
permissions. Existing plaintext config files remain readable for backward
compatibility; the next profile load or `profile edit` rewrites sensitive fields
Expand All @@ -583,6 +583,7 @@ nacos-cli profile get auth-type

# Non-interactively create or update profile values
nacos-cli profile set dev host=127.0.0.1 port=8848 auth-type=none
nacos-cli profile set dev host=127.0.0.1 port=8848 auth-type=token token=<token>
nacos-cli profile set dev auth-type=nacos username=nacos password=nacos
nacos-cli profile set dev server=127.0.0.1:8848 namespace=public

Expand Down
6 changes: 6 additions & 0 deletions cmd/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ var (
"accesskey": true,
"secretkey": true,
"securitytoken": true,
"token": true,
"namespace": true,
}
)
Expand Down Expand Up @@ -136,6 +137,7 @@ Examples:
stsURLVal,
stsAuthTokenVal,
cfg.GetScheme(),
client.WithToken(cfg.Token),
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
Expand Down Expand Up @@ -195,6 +197,8 @@ Examples:
fmt.Printf("%-15s %d\n", "port:", cfg.Port)
fmt.Printf("%-15s %s\n", "auth-type:", cfg.AuthType)
switch cfg.AuthType {
case "token":
fmt.Printf("%-15s %s\n", "token:", maskSensitiveValue(cfg.Token))
case "aliyun":
fmt.Printf("%-15s %s\n", "access-key:", displayConfigValue(cfg.AccessKey))
fmt.Printf("%-15s %s\n", "secret-key:", maskSensitiveValue(cfg.SecretKey))
Expand Down Expand Up @@ -351,6 +355,7 @@ before being saved.

Examples:
nacos-cli profile set dev host=127.0.0.1 port=8848 auth-type=none
nacos-cli profile set dev host=127.0.0.1 port=8848 auth-type=token token=<token>
nacos-cli profile set dev auth-type=nacos username=nacos password=nacos
nacos-cli profile set dev server=127.0.0.1:8848 namespace=public`,
Args: cobra.MinimumNArgs(1),
Expand Down Expand Up @@ -560,6 +565,7 @@ func printProfileValues(cfg *config.Config) {
"access-key",
"secret-key",
"security-token",
"token",
"namespace",
} {
value, sensitive, err := cfg.GetValue(key)
Expand Down
6 changes: 6 additions & 0 deletions cmd/profile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,9 @@ func TestProfileDisplayValues(t *testing.T) {
t.Fatalf("empty masked value = %q, want (not set)", got)
}
}

func TestProfileRecognizesTokenField(t *testing.T) {
if !isProfileFieldKey("token") {
t.Fatal("token should be recognized as a profile field")
}
}
20 changes: 15 additions & 5 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ var (
accessKey string
secretKey string
securityToken string
token string
stsURL string
stsAuthToken string
configFile string
Expand Down Expand Up @@ -198,7 +199,7 @@ Examples:
password = fileConfig.Password
}

// AccessKey / SecretKey / SecurityToken: command line > config file
// AccessKey / SecretKey / SecurityToken / Token: command line > config file
if accessKey == "" && fileConfig != nil {
accessKey = fileConfig.AccessKey
}
Expand All @@ -208,6 +209,9 @@ Examples:
if securityToken == "" && fileConfig != nil {
securityToken = fileConfig.SecurityToken
}
if token == "" && fileConfig != nil {
token = fileConfig.Token
}

// Set default server address only when neither --host nor --port is provided.
if serverAddr == "" {
Expand Down Expand Up @@ -355,12 +359,13 @@ func init() {
// Global flags - legacy style (for backward compatibility)
rootCmd.PersistentFlags().StringVarP(&serverAddr, "server", "s", "", "Nacos server address (e.g., market.hiclaw.io:80)")
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "Namespace ID")
rootCmd.PersistentFlags().StringVar(&authType, "auth-type", "", "Auth type: nacos | aliyun | sts-hiclaw | sts-agentteams")
rootCmd.PersistentFlags().StringVar(&authType, "auth-type", "", "Auth type: token | nacos | aliyun | sts-hiclaw | sts-agentteams")
rootCmd.PersistentFlags().StringVarP(&username, "username", "u", "", "Username (nacos auth)")
rootCmd.PersistentFlags().StringVarP(&password, "password", "p", "", "Password (nacos auth)")
rootCmd.PersistentFlags().StringVar(&accessKey, "access-key", "", "AccessKey (aliyun/STS auth)")
rootCmd.PersistentFlags().StringVar(&secretKey, "secret-key", "", "SecretKey (aliyun/STS auth)")
rootCmd.PersistentFlags().StringVar(&securityToken, "security-token", "", "STS SecurityToken (STS auth)")
rootCmd.PersistentFlags().StringVar(&token, "token", "", "Bearer token")
rootCmd.PersistentFlags().BoolVar(&verbose, "verbose", false, "Enable verbose/debug output")

// Mark legacy server flag as deprecated but still functional
Expand All @@ -387,9 +392,14 @@ func currentTerminalProfileName() string {

// mustNewNacosClient creates a NacosClient and exits with a clear error message on failure (e.g. login failed).
func mustNewNacosClient() *client.NacosClient {
c, err := client.NewNacosClient(serverAddr, namespace, authType, username, password, accessKey, secretKey, securityToken, stsURL, stsAuthToken, scheme, func(c *client.NacosClient) {
c.Verbose = verbose
})
c, err := client.NewNacosClient(
serverAddr, namespace, authType, username, password,
accessKey, secretKey, securityToken, stsURL, stsAuthToken, scheme,
client.WithToken(token),
func(c *client.NacosClient) {
c.Verbose = verbose
},
)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
Expand Down
79 changes: 79 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"path/filepath"
"testing"

"github.com/nacos-group/nacos-cli/internal/client"
"github.com/nacos-group/nacos-cli/internal/config"
"github.com/nacos-group/nacos-cli/internal/skill"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -163,6 +164,81 @@ func TestPersistentPreRunAuthTypeOverrideKeepsProfileConfig(t *testing.T) {
}
}

func TestMustNewNacosClientUsesToken(t *testing.T) {
resetRootConfigForTest(t)
if rootCmd.PersistentFlags().Lookup("token") == nil {
t.Fatal("--token persistent flag is not registered")
}
serverAddr = "127.0.0.1:8848"
token = "test-token"

c := mustNewNacosClient()
req, err := c.NewAuthedRequest("GET", c.BaseURL(), nil)
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != "Bearer test-token" {
t.Fatalf("Authorization header = %q, want %q", got, "Bearer test-token")
}
}

func TestPersistentPreRunLoadsProfileToken(t *testing.T) {
resetRootConfigForTest(t)
t.Setenv("HOME", t.TempDir())

configPath, err := config.GetProfileConfigPath("dev")
if err != nil {
t.Fatal(err)
}
if err := (&config.Config{
Host: "127.0.0.1",
Port: 8848,
AuthType: "token",
Token: "profile-token",
}).SaveConfig(configPath); err != nil {
t.Fatal(err)
}
profileName = "dev"

rootCmd.PersistentPreRun(&cobra.Command{Use: "skill-list"}, nil)

if token != "profile-token" {
t.Fatalf("token = %q, want profile-token", token)
}
if got := mustNewNacosClient().AuthType; got != client.AuthTypeToken {
t.Fatalf("AuthType = %q, want %q", got, client.AuthTypeToken)
}
}

func TestPersistentPreRunCommandLineTokenOverridesProfile(t *testing.T) {
resetRootConfigForTest(t)
t.Setenv("HOME", t.TempDir())

configPath, err := config.GetProfileConfigPath("dev")
if err != nil {
t.Fatal(err)
}
if err := (&config.Config{
Host: "10.0.0.2",
Port: 8848,
AuthType: "token",
Token: "profile-token",
}).SaveConfig(configPath); err != nil {
t.Fatal(err)
}
profileName = "dev"
token = "command-line-token"

rootCmd.PersistentPreRun(&cobra.Command{Use: "skill-list"}, nil)

if serverAddr != "10.0.0.2:8848" {
t.Fatalf("serverAddr = %q, want profile server", serverAddr)
}
if token != "command-line-token" {
t.Fatalf("token = %q, want command-line-token", token)
}
}

func TestCurrentTerminalProfileName(t *testing.T) {
resetRootConfigForTest(t)
t.Setenv("HOME", t.TempDir())
Expand Down Expand Up @@ -409,6 +485,7 @@ func resetRootConfigForTest(t *testing.T) {
originalAccessKey := accessKey
originalSecretKey := secretKey
originalSecurityToken := securityToken
originalToken := token
originalStsURL := stsURL
originalStsAuthToken := stsAuthToken
originalConfigFile := configFile
Expand All @@ -426,6 +503,7 @@ func resetRootConfigForTest(t *testing.T) {
accessKey = ""
secretKey = ""
securityToken = ""
token = ""
stsURL = ""
stsAuthToken = ""
configFile = ""
Expand All @@ -444,6 +522,7 @@ func resetRootConfigForTest(t *testing.T) {
accessKey = originalAccessKey
secretKey = originalSecretKey
securityToken = originalSecurityToken
token = originalToken
stsURL = originalStsURL
stsAuthToken = originalStsAuthToken
configFile = originalConfigFile
Expand Down
15 changes: 15 additions & 0 deletions internal/client/nacos_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

const (
AuthTypeNone = "none" // No authentication (public registry)
AuthTypeToken = "token" // Bearer token authentication
AuthTypeNacos = "nacos" // Username/password authentication
AuthTypeAliyun = "aliyun" // AccessKey/SecretKey authentication
AuthTypeStsToken = "sts-hiclaw" // STS temporary credential via Hiclaw controller
Expand Down Expand Up @@ -67,6 +68,17 @@ func IsStsAuthType(authType string) bool {
return authType == AuthTypeStsToken || authType == AuthTypeStsAgentTeams
}

// WithToken configures standard Bearer token authentication.
func WithToken(token string) func(*NacosClient) {
return func(c *NacosClient) {
if token == "" {
return
}
c.AuthType = AuthTypeToken
c.AccessToken = token
}
}

// Config represents a Nacos configuration
type Config struct {
DataID string `json:"dataId"`
Expand Down Expand Up @@ -184,6 +196,9 @@ func NewNacosClient(serverAddr, namespace, authType, username, password, accessK
for _, opt := range opts {
opt(c)
}
if c.AuthType == AuthTypeToken {
c.httpClient.SetHeader("Authorization", "Bearer "+c.AccessToken)
}

switch c.AuthType {
case AuthTypeNacos:
Expand Down
28 changes: 28 additions & 0 deletions internal/client/nacos_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,3 +181,31 @@ func TestNacosClientReusesHTTPClientWithTimeout(t *testing.T) {
t.Fatalf("timeout = %s, want %s", first.Timeout, DefaultHTTPTimeout)
}
}

func TestNewNacosClientWithTokenSetsAuthorizationHeader(t *testing.T) {
c, err := NewNacosClient(
"127.0.0.1:8848",
"public",
AuthTypeNone,
"", "", "", "", "", "", "",
"http",
WithToken("test-token"),
)
if err != nil {
t.Fatal(err)
}
if c.AuthType != AuthTypeToken {
t.Fatalf("AuthType = %q, want %q", c.AuthType, AuthTypeToken)
}

req, err := c.NewAuthedRequest(http.MethodGet, c.BaseURL(), nil)
if err != nil {
t.Fatal(err)
}
if got := req.Header.Get("Authorization"); got != "Bearer test-token" {
t.Fatalf("Authorization header = %q, want %q", got, "Bearer test-token")
}
if got := c.httpClient.Header.Get("Authorization"); got != "Bearer test-token" {
t.Fatalf("resty Authorization header = %q, want %q", got, "Bearer test-token")
}
}
Loading
Loading