diff --git a/natscontext/context.go b/natscontext/context.go index 12e0dc3..612f873 100644 --- a/natscontext/context.go +++ b/natscontext/context.go @@ -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 { diff --git a/natscontext/context_test.go b/natscontext/context_test.go index d484bee..5e7ed80 100644 --- a/natscontext/context_test.go +++ b/natscontext/context_test.go @@ -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()) + } } diff --git a/natscontext/testdata/gotest.json b/natscontext/testdata/gotest.json index 3019e73..636442f 100644 --- a/natscontext/testdata/gotest.json +++ b/natscontext/testdata/gotest.json @@ -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" }