Skip to content

Commit d1c555f

Browse files
tomhjptvoran
andauthored
Use levelled logger (#63)
* Use levelled logger * Fix log level input, add test readme, remove test for log lines * Add changelog note Co-authored-by: Theron Voran <[email protected]>
1 parent 15b5adc commit d1c555f

17 files changed

+116
-75
lines changed

CHANGELOG.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
## Unreleased
22

3+
CHANGES:
4+
5+
* Logging is now levelled and less chatty by default. Level can be controlled by VAULT_LOG_LEVEL environment variable. [[GH-63](https://github.com/hashicorp/vault-lambda-extension/pull/63)]
6+
7+
IMPROVEMENTS:
8+
9+
* Leading and trailing whitespace is trimmed from environment variable values on reading. [[GH-63](https://github.com/hashicorp/vault-lambda-extension/pull/63)]
10+
311
## 0.5.0 (August 24, 2021)
412

513
FEATURES:

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ Environment variable | Description | Required | Example value
152152
`VAULT_SECRET_FILE_FOO` | Must exist for any correspondingly named `VAULT_SECRET_PATH_FOO`. Name has no further effect beyond matching to the correct path variable | No | `/tmp/token`
153153
`VAULT_TOKEN_EXPIRY_GRACE_PERIOD` | Period at the end of the proxy server's auth token TTL where it will consider the token expired and attempt to re-authenticate to Vault. Must have a unit and be parseable by `time.Duration`. Defaults to 10s. | No | `1m`
154154
`VAULT_STS_ENDPOINT_REGION` | The region of the STS regional endpoint to authenticate with. If the AWS IAM auth mount specified uses a regional STS endpoint, then this needs to match the region of that endpoint. Defaults to using the global endpoint, or the region the Lambda resides in if `AWS_STS_REGIONAL_ENDPOINTS` is set to `regional` | No | `eu-west-1`
155+
`VAULT_LOG_LEVEL` | Log level, one of TRACE, DEBUG, INFO, WARN, ERROR, OFF. Defaults to INFO. | No | `DEBUG`
155156

156157
The remaining environment variables are not required, and function exactly as
157158
described in the [Vault Commands (CLI)][vault-env-vars] documentation. However,

go.mod

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.17
44

55
require (
66
github.com/aws/aws-sdk-go v1.41.10
7+
github.com/hashicorp/go-hclog v1.1.0
78
github.com/hashicorp/go-multierror v1.1.1
89
github.com/hashicorp/vault/api v1.4.1
910
github.com/hashicorp/vault/sdk v0.4.1
@@ -21,7 +22,6 @@ require (
2122
github.com/golang/snappy v0.0.4 // indirect
2223
github.com/hashicorp/errwrap v1.1.0 // indirect
2324
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
24-
github.com/hashicorp/go-hclog v0.16.2 // indirect
2525
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
2626
github.com/hashicorp/go-plugin v1.4.3 // indirect
2727
github.com/hashicorp/go-retryablehttp v0.6.6 // indirect

go.sum

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,9 @@ github.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9n
9797
github.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=
9898
github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrjA0H7acj2lQ=
9999
github.com/hashicorp/go-hclog v0.14.1/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
100-
github.com/hashicorp/go-hclog v0.16.2 h1:K4ev2ib4LdQETX5cSZBG0DVLk1jwGqSPXBjdah3veNs=
101100
github.com/hashicorp/go-hclog v0.16.2/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
101+
github.com/hashicorp/go-hclog v1.1.0 h1:QsGcniKx5/LuX2eYoeL+Np3UKYPNaN7YKpTh29h8rbw=
102+
github.com/hashicorp/go-hclog v1.1.0/go.mod h1:whpDNt7SSdeAju8AWKIWsul05p54N/39EeqMAyrmvFQ=
102103
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
103104
github.com/hashicorp/go-immutable-radix v1.3.1 h1:DKHmCUm2hRBK510BaiZlwvpD40f8bJFeZnpfm2KLowc=
104105
github.com/hashicorp/go-immutable-radix v1.3.1/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=

internal/config/auth.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package config
22

33
import (
44
"os"
5+
"strings"
56
)
67

78
const (
@@ -24,10 +25,10 @@ type AuthConfig struct {
2425
// AuthConfigFromEnv reads config from the environment for authenticating to Vault.
2526
func AuthConfigFromEnv() AuthConfig {
2627
return AuthConfig{
27-
Role: os.Getenv(vaultAuthRole),
28-
Provider: os.Getenv(vaultAuthProvider),
29-
IAMServerID: os.Getenv(vaultIAMServerID),
30-
STSEndpointRegion: os.Getenv(stsEndpointRegionEnv),
31-
VaultAddress: os.Getenv(vleVaultAddr),
28+
Role: strings.TrimSpace(os.Getenv(vaultAuthRole)),
29+
Provider: strings.TrimSpace(os.Getenv(vaultAuthProvider)),
30+
IAMServerID: strings.TrimSpace(os.Getenv(vaultIAMServerID)),
31+
STSEndpointRegion: strings.TrimSpace(os.Getenv(stsEndpointRegionEnv)),
32+
VaultAddress: strings.TrimSpace(os.Getenv(vleVaultAddr)),
3233
}
3334
}

internal/config/cache.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package config
33
import (
44
"os"
55
"strconv"
6+
"strings"
67
"time"
78
)
89

@@ -26,7 +27,7 @@ type CacheConfig struct {
2627
// CacheConfigFromEnv reads config from the environment for caching
2728
func CacheConfigFromEnv() CacheConfig {
2829
var cacheTTL time.Duration
29-
cacheTTLEnv := os.Getenv(VaultCacheTTL)
30+
cacheTTLEnv := strings.TrimSpace(os.Getenv(VaultCacheTTL))
3031
if cacheTTLEnv != "" {
3132
var err error
3233
cacheTTL, err = time.ParseDuration(cacheTTLEnv)
@@ -36,7 +37,7 @@ func CacheConfigFromEnv() CacheConfig {
3637
}
3738

3839
defaultOn := false
39-
defaultOnEnv := os.Getenv(VaultCacheEnabled)
40+
defaultOnEnv := strings.TrimSpace(os.Getenv(VaultCacheEnabled))
4041
if defaultOnEnv != "" {
4142
var err error
4243
defaultOn, err = strconv.ParseBool(defaultOnEnv)

internal/config/secret.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ func ParseConfiguredSecrets() ([]ConfiguredSecret, error) {
6868
return nil, fmt.Errorf("os.Environ should return key=value pairs, but got %s", kv)
6969
}
7070
key := parts[0]
71-
value := parts[1]
71+
value := strings.TrimSpace(parts[1])
7272

7373
switch {
7474
case strings.HasPrefix(key, vaultSecretPathPrefix):
@@ -105,12 +105,12 @@ func ParseConfiguredSecrets() ([]ConfiguredSecret, error) {
105105
}
106106

107107
// Special case for anonymous-name secret
108-
anonymousSecretVaultPath := getenv(vaultSecretPathKey)
108+
anonymousSecretVaultPath := strings.TrimSpace(getenv(vaultSecretPathKey))
109109
if anonymousSecretVaultPath != "" {
110110
s := &ConfiguredSecret{
111111
name: "",
112112
VaultPath: anonymousSecretVaultPath,
113-
FilePath: filePathFromEnv(getenv(vaultSecretFileKey)),
113+
FilePath: filePathFromEnv(strings.TrimSpace(getenv(vaultSecretFileKey))),
114114
}
115115
if s.FilePath == "" {
116116
s.FilePath = path.Join(DefaultSecretDirectory, DefaultSecretFile)

internal/proxy/cache.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ import (
66
"encoding/hex"
77
"fmt"
88
"io/ioutil"
9-
"log"
109
"net/http"
1110
"strings"
1211

12+
"github.com/hashicorp/go-hclog"
1313
"github.com/hashicorp/vault-lambda-extension/internal/config"
1414
"github.com/hashicorp/vault/api"
1515
"github.com/hashicorp/vault/sdk/helper/cryptoutil"
@@ -70,19 +70,19 @@ func NewCache(cc config.CacheConfig) *Cache {
7070

7171
// constructs the CacheKey for this request and token and returns the SHA256
7272
// hash
73-
func makeRequestHash(logger *log.Logger, r *http.Request, token string) (string, error) {
73+
func makeRequestHash(logger hclog.Logger, r *http.Request, token string) (string, error) {
7474
reqBody, err := ioutil.ReadAll(r.Body)
7575
if err != nil {
7676
if r.Body != nil {
7777
if err := r.Body.Close(); err != nil {
78-
logger.Printf("error closing request body: %s", err)
78+
logger.Error("error closing request body", "error", err)
7979
}
8080
}
8181
return "", fmt.Errorf("failed to read request body: %w", err)
8282
}
8383
if r.Body != nil {
8484
if err := r.Body.Close(); err != nil {
85-
logger.Printf("error closing request body: %s", err)
85+
logger.Error("error closing request body", "error", err)
8686
}
8787
}
8888
r.Body = ioutil.NopCloser(bytes.NewReader(reqBody))

internal/proxy/cache_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"bytes"
55
"fmt"
66
"io/ioutil"
7-
"log"
87
"math/rand"
98
"net/http"
109
"net/http/httptest"
@@ -14,6 +13,7 @@ import (
1413
"testing"
1514
"time"
1615

16+
"github.com/hashicorp/go-hclog"
1717
"github.com/hashicorp/vault-lambda-extension/internal/config"
1818
"github.com/hashicorp/vault/api"
1919
"github.com/hashicorp/vault/sdk/helper/consts"
@@ -198,7 +198,7 @@ func Test_makeRequestHash(t *testing.T) {
198198
},
199199
}
200200

201-
h, err := makeRequestHash(log.Default(), req, "blue")
201+
h, err := makeRequestHash(hclog.Default(), req, "blue")
202202
assert.NoError(t, err)
203203
assert.Equal(t, "b62adf8925f91450ee992596dd2fb38edb0d3270ed9edc23b98bf5f322e9ed9a", h)
204204
}

internal/proxy/proxy.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ import (
44
"bytes"
55
"fmt"
66
"io"
7-
"log"
87
"net/http"
98
"net/url"
109

10+
"github.com/hashicorp/go-hclog"
1111
"github.com/hashicorp/vault-lambda-extension/internal/config"
1212
"github.com/hashicorp/vault-lambda-extension/internal/vault"
1313
"github.com/hashicorp/vault/sdk/helper/consts"
@@ -19,7 +19,7 @@ const (
1919
)
2020

2121
// New returns an unstarted HTTP server with health and proxy handlers.
22-
func New(logger *log.Logger, client *vault.Client, cacheConfig config.CacheConfig) *http.Server {
22+
func New(logger hclog.Logger, client *vault.Client, cacheConfig config.CacheConfig) *http.Server {
2323
cache := setupCache(cacheConfig)
2424
mux := http.ServeMux{}
2525
mux.HandleFunc("/", proxyHandler(logger, client, cache))
@@ -32,15 +32,15 @@ func New(logger *log.Logger, client *vault.Client, cacheConfig config.CacheConfi
3232

3333
// The proxyHandler borrows from the Send function in Vault Agent's proxy:
3434
// https://github.com/hashicorp/vault/blob/22b486b651b8956d32fb24e77cef4050df7094b6/command/agent/cache/api_proxy.go
35-
func proxyHandler(logger *log.Logger, client *vault.Client, cache *Cache) func(http.ResponseWriter, *http.Request) {
35+
func proxyHandler(logger hclog.Logger, client *vault.Client, cache *Cache) func(http.ResponseWriter, *http.Request) {
3636
return func(w http.ResponseWriter, r *http.Request) {
3737
token, err := client.Token(r.Context())
3838
if err != nil {
3939
http.Error(w, fmt.Sprintf("failed to get valid Vault token: %s", err), http.StatusInternalServerError)
4040
return
4141
}
4242

43-
logger.Printf("Proxying %s %s\n", r.Method, r.URL.Path)
43+
logger.Debug(fmt.Sprintf("Proxying %s %s", r.Method, r.URL.Path))
4444
fwReq, err := proxyRequest(r, client.VaultConfig.Address, token)
4545
if err != nil {
4646
http.Error(w, fmt.Sprintf("failed to generate proxy request: %s", err), http.StatusInternalServerError)
@@ -57,7 +57,7 @@ func proxyHandler(logger *log.Logger, client *vault.Client, cache *Cache) func(h
5757
// Construct the hash for this request to use as the cache key
5858
cacheKeyHash, err = makeRequestHash(logger, r, token)
5959
if err != nil {
60-
logger.Printf("failed to compute request hash: %s", err)
60+
logger.Error("failed to compute request hash", "error", err)
6161
http.Error(w, "failed to read request", http.StatusInternalServerError)
6262
return
6363
}
@@ -71,10 +71,10 @@ func proxyHandler(logger *log.Logger, client *vault.Client, cache *Cache) func(h
7171
// Check the cache for this request
7272
data, err := cache.Get(cacheKeyHash)
7373
if err != nil {
74-
logger.Printf("failed to fetch from cache: %s", err)
74+
logger.Error("failed to fetch from cache", "error", err)
7575
}
7676
if data != nil {
77-
logger.Printf("Cache hit for: %s %s", r.Method, r.URL.Path)
77+
logger.Debug(fmt.Sprintf("Cache hit for: %s %s", r.Method, r.URL.Path))
7878
fetchFromCache(w, data)
7979
return
8080
}
@@ -99,7 +99,7 @@ func proxyHandler(logger *log.Logger, client *vault.Client, cache *Cache) func(h
9999

100100
if doCacheSet && resp.StatusCode < 300 {
101101
cache.Set(cacheKeyHash, retrieveData(resp, respBody))
102-
logger.Printf("Refreshed cache for: %s %s", r.Method, r.URL.Path)
102+
logger.Debug(fmt.Sprintf("Refreshed cache for: %s %s", r.Method, r.URL.Path))
103103
}
104104

105105
copyHeaders(w.Header(), resp.Header)
@@ -111,7 +111,7 @@ func proxyHandler(logger *log.Logger, client *vault.Client, cache *Cache) func(h
111111
return
112112
}
113113

114-
logger.Printf("Successfully proxied %s %s\n", r.Method, r.URL.Path)
114+
logger.Debug(fmt.Sprintf("Successfully proxied %s %s", r.Method, r.URL.Path))
115115
}
116116
}
117117

internal/proxy/proxy_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,14 @@ import (
55
"errors"
66
"fmt"
77
"io/ioutil"
8-
"log"
98
"net"
109
"net/http"
1110
"net/http/httptest"
1211
"strings"
1312
"testing"
1413

1514
"github.com/aws/aws-sdk-go/aws/session"
15+
"github.com/hashicorp/go-hclog"
1616
"github.com/hashicorp/vault-lambda-extension/internal/config"
1717
"github.com/hashicorp/vault-lambda-extension/internal/ststest"
1818
"github.com/hashicorp/vault-lambda-extension/internal/vault"
@@ -111,12 +111,12 @@ func startProxy(t *testing.T, vaultAddress string, ses *session.Session) (string
111111
vaultConfig := api.DefaultConfig()
112112
require.NoError(t, vaultConfig.Error)
113113
vaultConfig.Address = vaultAddress
114-
client, err := vault.NewClient(log.New(ioutil.Discard, "", 0), vaultConfig, config.AuthConfig{}, ses)
114+
client, err := vault.NewClient(hclog.NewNullLogger(), vaultConfig, config.AuthConfig{}, ses)
115115
require.NoError(t, err)
116116
client.VaultConfig.Address = vaultAddress
117117
ln, err := net.Listen("tcp", "127.0.0.1:0")
118118
require.NoError(t, err)
119-
proxy := New(log.New(ioutil.Discard, "", 0), client, config.CacheConfig{})
119+
proxy := New(hclog.NewNullLogger(), client, config.CacheConfig{})
120120
go func() {
121121
_ = proxy.Serve(ln)
122122
}()

internal/vault/client.go

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,14 @@ import (
66
"encoding/json"
77
"fmt"
88
"io/ioutil"
9-
"log"
109
"os"
10+
"strings"
1111
"sync"
1212
"time"
1313

1414
"github.com/aws/aws-sdk-go/aws/session"
1515
"github.com/aws/aws-sdk-go/service/sts"
16+
"github.com/hashicorp/go-hclog"
1617
"github.com/hashicorp/vault-lambda-extension/internal/config"
1718
"github.com/hashicorp/vault/api"
1819
)
@@ -29,7 +30,7 @@ type Client struct {
2930
VaultClient *api.Client
3031
VaultConfig *api.Config
3132

32-
logger *log.Logger
33+
logger hclog.Logger
3334
stsSvc *sts.STS
3435
authConfig config.AuthConfig
3536

@@ -42,7 +43,7 @@ type Client struct {
4243

4344
// NewClient uses the AWS IAM auth method configured in a Vault cluster to
4445
// authenticate the execution role and create a Vault API client.
45-
func NewClient(logger *log.Logger, vaultConfig *api.Config, authConfig config.AuthConfig, awsSes *session.Session) (*Client, error) {
46+
func NewClient(logger hclog.Logger, vaultConfig *api.Config, authConfig config.AuthConfig, awsSes *session.Session) (*Client, error) {
4647
vaultClient, err := api.NewClient(vaultConfig)
4748
if err != nil {
4849
return nil, fmt.Errorf("error making extension: %w", err)
@@ -73,17 +74,17 @@ func (c *Client) Token(ctx context.Context) (string, error) {
7374
defer c.mtx.Unlock()
7475

7576
if c.expired() {
76-
c.logger.Println("authenticating to Vault")
77+
c.logger.Debug("authenticating to Vault")
7778
err := c.login(ctx)
7879
if err != nil {
7980
return "", err
8081
}
8182
} else if c.shouldRenew() {
8283
// Renew but don't retry or bail on errors, just best effort.
83-
c.logger.Println("renewing Vault token")
84+
c.logger.Debug("renewing Vault token")
8485
err := c.renew()
8586
if err != nil {
86-
c.logger.Printf("failed to renew token but attempting to continue: %s\n", err)
87+
c.logger.Error("failed to renew token but attempting to continue", "error", err)
8788
}
8889
}
8990

@@ -179,7 +180,7 @@ func parseTokenExpiryGracePeriod() (time.Duration, error) {
179180
var err error
180181
expiryGracePeriod := defaultTokenExpiryGracePeriod
181182

182-
expiryGracePeriodString := os.Getenv(tokenExpiryGracePeriodEnv)
183+
expiryGracePeriodString := strings.TrimSpace(os.Getenv(tokenExpiryGracePeriodEnv))
183184
if expiryGracePeriodString != "" {
184185
expiryGracePeriod, err = time.ParseDuration(expiryGracePeriodString)
185186
if err != nil {

0 commit comments

Comments
 (0)