Skip to content

Commit ba4e721

Browse files
author
Otávio Fernandes
committed
Refactoring.
1 parent c1979a8 commit ba4e721

File tree

4 files changed

+93
-81
lines changed

4 files changed

+93
-81
lines changed

pkg/vault-handler/config.go

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
package vaulthandler
22

33
import (
4-
"errors"
54
"fmt"
65
)
76

87
// Config object for vault-handler.
98
type Config struct {
109
DryRun bool // dry-run flag
1110
OutputDir string // output directory path
11+
InputDir string // input directory, when uploading
1212
VaultAddr string // vault api endpoint
1313
VaultToken string // vault token
1414
VaultRoleID string // vault approle role-id
@@ -18,18 +18,21 @@ type Config struct {
1818
// Validate configuration object.
1919
func (c *Config) Validate() error {
2020
if c.VaultAddr == "" {
21-
return errors.New("vault-addr is not informed")
21+
return fmt.Errorf("vault-addr is not informed")
2222
}
2323
if c.VaultToken == "" && c.VaultRoleID == "" && c.VaultSecretID == "" {
24-
return errors.New("inform vault-token, or vault-role-id and secret-id")
24+
return fmt.Errorf("inform vault-token, or vault-role-id and secret-id")
2525
}
2626
if c.VaultToken != "" && (c.VaultRoleID != "" || c.VaultSecretID != "") {
27-
return errors.New("vault-token can't be used in combination with role-id or secret-id")
27+
return fmt.Errorf("vault-token can't be used in combination with role-id or secret-id")
2828
}
29-
if c.OutputDir == "" {
30-
return errors.New("output-dir is not informed")
29+
if c.InputDir == "" && c.OutputDir == "" {
30+
return fmt.Errorf("both input-dir and output-dir are empty")
3131
}
32-
if !isDir(c.OutputDir) {
32+
if c.InputDir != "" && !isDir(c.InputDir) {
33+
return fmt.Errorf("input-dir '%s' is not found", c.InputDir)
34+
}
35+
if c.OutputDir != "" && !isDir(c.OutputDir) {
3336
return fmt.Errorf("output-dir '%s' is not found", c.OutputDir)
3437
}
3538

pkg/vault-handler/file.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ func (f *File) Zip() error {
2222
var buffer bytes.Buffer
2323
var err error
2424

25+
originalPayloadLen := len(f.payload)
2526
gz := gzip.NewWriter(&buffer)
2627

2728
if _, err = gz.Write(f.payload); err != nil {
@@ -35,6 +36,8 @@ func (f *File) Zip() error {
3536
return err
3637
}
3738

39+
log.Printf("[File] Zipping payload, before and after: '%d'/'%d' bytes ",
40+
originalPayloadLen, len(f.payload))
3841
f.payload = buffer.Bytes()
3942
return nil
4043
}
@@ -45,6 +48,7 @@ func (f *File) Unzip() error {
4548
var bufferOut bytes.Buffer
4649
var err error
4750

51+
originalPayloadLen := len(f.payload)
4852
bufferIn := bytes.NewBuffer(f.payload)
4953
if reader, err = gzip.NewReader(bufferIn); err != nil {
5054
return err
@@ -53,6 +57,8 @@ func (f *File) Unzip() error {
5357
return err
5458
}
5559

60+
log.Printf("[File] Unzipping payload, before and after: '%d'/'%d' bytes ",
61+
originalPayloadLen, len(f.payload))
5662
f.payload = bufferOut.Bytes()
5763
return nil
5864
}
@@ -75,9 +81,15 @@ func (f *File) Read(baseDir string) error {
7581

7682
// Write contents to file-system.
7783
func (f *File) Write(baseDir string) error {
84+
log.Printf("[File] Writting '%d' bytes on '%s'", len(f.payload), f.fileName())
7885
return ioutil.WriteFile(f.FilePath(baseDir), f.payload, 0600)
7986
}
8087

88+
// Name exposes the file name from properties.
89+
func (f *File) Name() string {
90+
return f.properties.Name
91+
}
92+
8193
// fileName compose file name based on group and SecretData settings.
8294
func (f *File) fileName() string {
8395
return fmt.Sprintf("%s.%s.%s", f.group, f.properties.Name, f.properties.Extension)

pkg/vault-handler/handler.go

Lines changed: 35 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -11,31 +11,6 @@ type Handler struct {
1111
vault *Vault // vault api instance
1212
}
1313

14-
// persist a slice of bytes to file-system.
15-
func (h *Handler) persist(group string, data *SecretData, payload []byte) error {
16-
var err error
17-
18-
file := NewFile(group, data, payload)
19-
20-
if data.Unzip {
21-
log.Print("[Handler] Extracting ZIP payload.")
22-
if err = file.Unzip(); err != nil {
23-
return err
24-
}
25-
}
26-
27-
if h.config.DryRun {
28-
log.Printf("[DRY-RUN] File '%s' is not written to file-system!",
29-
file.FilePath(h.config.OutputDir))
30-
} else {
31-
if err = file.Write(h.config.OutputDir); err != nil {
32-
return err
33-
}
34-
}
35-
36-
return nil
37-
}
38-
3914
// Authenticate against vault either via token directly or via AppRole, must be invoked before other
4015
// actions using the API.
4116
func (h *Handler) Authenticate() error {
@@ -54,14 +29,6 @@ func (h *Handler) Authenticate() error {
5429
return nil
5530
}
5631

57-
// composeVaultPath based in the current SecretData.
58-
func (h *Handler) composeVaultPath(secrets Secrets, data SecretData) string {
59-
if !data.NameAsSubPath {
60-
return secrets.Path
61-
}
62-
return path.Join(secrets.Path, data.Name)
63-
}
64-
6532
// Download files from vault based on manifest.
6633
func (h *Handler) Download(manifest *Manifest) error {
6734
var err error
@@ -71,20 +38,28 @@ func (h *Handler) Download(manifest *Manifest) error {
7138
log.Printf("[Handler/Download] [%s] Vault path '%s'", group, secrets.Path)
7239

7340
for _, data := range secrets.Data {
41+
var payload []byte
42+
7443
log.Printf("[Handler/Download] [%s] Reading data from Vault '%s.%s' (unzip: %v)",
7544
group, data.Name, data.Extension, data.Unzip)
7645

7746
vaultPath := h.composeVaultPath(secrets, data)
78-
log.Printf("[Handler/Download] [%s] '%s' path in Vault: '%s'", data.Name, group, vaultPath)
47+
log.Printf("[Handler/Download] [%s] '%s' path in Vault: '%s'",
48+
data.Name, group, vaultPath)
7949

80-
// loading secret from vault
81-
payload := []byte{}
8250
if payload, err = h.vault.Read(vaultPath, data.Name); err != nil {
8351
return err
8452
}
8553

86-
// saving data to disk
87-
if err = h.persist(group, &data, payload); err != nil {
54+
file := NewFile(group, &data, payload)
55+
56+
if data.Unzip {
57+
if err = file.Unzip(); err != nil {
58+
return err
59+
}
60+
}
61+
62+
if err = h.persist(file); err != nil {
8863
return err
8964
}
9065
}
@@ -128,6 +103,20 @@ func (h *Handler) Upload(manifest *Manifest) error {
128103
return nil
129104
}
130105

106+
// persist a slice of bytes to file-system.
107+
func (h *Handler) persist(file *File) error {
108+
if h.config.DryRun {
109+
log.Printf("[DRY-RUN] File '%s' is not written to file-system!",
110+
file.FilePath(h.config.OutputDir))
111+
} else {
112+
if err := file.Write(h.config.OutputDir); err != nil {
113+
return err
114+
}
115+
}
116+
return nil
117+
}
118+
119+
// dispense a file payload to Vault server.
131120
func (h *Handler) dispense(file *File, vaultPath string) error {
132121
var data = make(map[string]interface{})
133122
var err error
@@ -145,6 +134,14 @@ func (h *Handler) dispense(file *File, vaultPath string) error {
145134
return nil
146135
}
147136

137+
// composeVaultPath based in the current SecretData.
138+
func (h *Handler) composeVaultPath(secrets Secrets, data SecretData) string {
139+
if !data.NameAsSubPath {
140+
return secrets.Path
141+
}
142+
return path.Join(secrets.Path, data.Name)
143+
}
144+
148145
// NewHandler instantiates a new application.
149146
func NewHandler(config *Config) (*Handler, error) {
150147
var err error

pkg/vault-handler/vault.go

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,32 @@ type Vault struct {
1515
token string
1616
}
1717

18-
// extractKey coming from Read method, where the user can choose one key to be taken out of the data
19-
// read from Vault.
20-
func (v *Vault) extractKey(payload map[string]interface{}, key string) ([]byte, error) {
21-
var data string
22-
var exists bool
18+
// AppRoleAuth execute approle authentication.
19+
func (v *Vault) AppRoleAuth(roleID, secretID string) error {
20+
var secret *vaultapi.Secret
21+
var err error
2322

24-
if _, exists = payload["data"]; exists {
25-
log.Print("[Vault] Using V2 API style, extracting 'data' from payload.")
26-
payload = payload["data"].(map[string]interface{})
23+
log.Printf("[Vault] Starting AppRole authentication.")
24+
authData := map[string]interface{}{"role_id": roleID, "secret_id": secretID}
25+
if secret, err = v.client.Logical().Write("auth/approle/login", authData); err != nil {
26+
return err
2727
}
28-
29-
if data, exists = payload[key].(string); !exists {
30-
return nil, fmt.Errorf("cannot extract key '%s' from vault payload", key)
28+
if secret.Auth == nil || secret.Auth.ClientToken == "" {
29+
return errors.New("no authentication data is returned from vault")
3130
}
3231

33-
dataAsBytes := []byte(data)
34-
log.Printf("Obtained '%d' bytes from key '%s'", len(dataAsBytes), key)
35-
return dataAsBytes, nil
32+
log.Printf("[Vault] Obtained a token via AppRole.")
33+
// saving token for next API calls.
34+
v.token = secret.Auth.ClientToken
35+
v.setHeaders()
36+
37+
return nil
38+
}
39+
40+
// TokenAuth execute token based authentication.
41+
func (v *Vault) TokenAuth(token string) {
42+
v.token = token
43+
v.setHeaders()
3644
}
3745

3846
// Read data from a given vault path and key name, and returning a slice of bytes with payload.
@@ -77,32 +85,24 @@ func (v *Vault) setHeaders() {
7785
v.client.SetToken(v.token)
7886
}
7987

80-
// AppRoleAuth execute approle authentication.
81-
func (v *Vault) AppRoleAuth(roleID, secretID string) error {
82-
var secret *vaultapi.Secret
83-
var err error
88+
// extractKey coming from Read method, where the user can choose one key to be taken out of the data
89+
// read from Vault.
90+
func (v *Vault) extractKey(payload map[string]interface{}, key string) ([]byte, error) {
91+
var data string
92+
var exists bool
8493

85-
log.Printf("[Vault] Starting AppRole authentication.")
86-
authData := map[string]interface{}{"role_id": roleID, "secret_id": secretID}
87-
if secret, err = v.client.Logical().Write("auth/approle/login", authData); err != nil {
88-
return err
89-
}
90-
if secret.Auth == nil || secret.Auth.ClientToken == "" {
91-
return errors.New("no authentication data is returned from vault")
94+
if _, exists = payload["data"]; exists {
95+
log.Print("[Vault] Using V2 API style, extracting 'data' from payload.")
96+
payload = payload["data"].(map[string]interface{})
9297
}
9398

94-
log.Printf("[Vault] Obtained a token via AppRole.")
95-
// saving token for next API calls.
96-
v.token = secret.Auth.ClientToken
97-
v.setHeaders()
98-
99-
return nil
100-
}
99+
if data, exists = payload[key].(string); !exists {
100+
return nil, fmt.Errorf("cannot extract key '%s' from vault payload", key)
101+
}
101102

102-
// TokenAuth execute token based authentication.
103-
func (v *Vault) TokenAuth(token string) {
104-
v.token = token
105-
v.setHeaders()
103+
dataAsBytes := []byte(data)
104+
log.Printf("[Vault] Obtained '%d' bytes from key '%s'", len(dataAsBytes), key)
105+
return dataAsBytes, nil
106106
}
107107

108108
// NewVault creates a Vault instance, by bootstrapping it's API client.

0 commit comments

Comments
 (0)