Skip to content

Commit

Permalink
Merge pull request #579 from ploubser/issue_577
Browse files Browse the repository at this point in the history
(#577) Add tilde expansion to context parsing
  • Loading branch information
ripienaar authored Oct 8, 2024
2 parents 470b10e + 7ac2448 commit 1954b34
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
12 changes: 12 additions & 0 deletions natscontext/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,18 @@ func (c *Context) loadActiveContext() error {
// performing environment variable expansion for the path of the cerds.
c.config.Creds = os.ExpandEnv(c.config.Creds)

usr, err := user.Current()
if err != nil {
return err
}

// expand tilde to current user's home directory
c.config.Creds = strings.Replace(c.config.Creds, "~", usr.HomeDir, 1)
c.config.NKey = strings.Replace(c.config.NKey, "~", usr.HomeDir, 1)
c.config.Cert = strings.Replace(c.config.Cert, "~", usr.HomeDir, 1)
c.config.Key = strings.Replace(c.config.Key, "~", usr.HomeDir, 1)
c.config.CA = strings.Replace(c.config.CA, "~", usr.HomeDir, 1)

if c.config.NSCLookup != "" {
err := c.resolveNscLookup()
if err != nil {
Expand Down
17 changes: 17 additions & 0 deletions natscontext/context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,21 @@ func TestContext(t *testing.T) {
if err != nil || (config.Name != "gotest" && config.ServerURL() != "demo.nats.io" && config.Token() != "use-nkeys!") {
t.Fatalf("could not load context file: %s", err)
}

// test tilde expansion
if config.NKey() == "~/.keys/nats/example/prod.nkey" {
t.Fatalf("invalid expansion of HOME directory - %s", config.NKey())
}
if config.Creds() == "~/.keys/nats/example/creds" {
t.Fatalf("invalid expansion of HOME directory - %s", config.Creds())
}
if config.Certificate() == "~/.keys/nats/example/public.crt" {
t.Fatalf("invalid expansion of HOME directory - %s", config.Certificate())
}
if config.Key() == "~/.keys/nats/example/public.key" {
t.Fatalf("invalid expansion of HOME directory - %s", config.Key())
}
if config.CA() == "~/.keys/nats/example/public.ca" {
t.Fatalf("invalid expansion of HOME directory - %s", config.CA())
}
}
7 changes: 6 additions & 1 deletion natscontext/testdata/gotest.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
{
"url": "demo.nats.io",
"token": "use-nkeys!"
"token": "use-nkeys!",
"nkey": "~/.keys/nats/example/prod.nkey",
"creds": "~/.keys/nats/example/creds",
"key": "~/.keys/nats/example/public.key",
"cert": "~/.keys/nats/example/public.crt",
"ca": "~/.keys/nats/example/public.ca"
}

0 comments on commit 1954b34

Please sign in to comment.