-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinject.go
98 lines (78 loc) · 2.31 KB
/
inject.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package envelope
import (
"fmt"
"io"
"io/ioutil"
"strings"
"github.com/ansel1/merry"
"github.com/mikesimons/traverser"
)
// InjectEncrypted inject the secret encrypted.
func (s *Envelope) InjectEncrypted(alias string, input io.Reader, key string, value io.Reader, format string) ([]byte, error) {
inputData, codec, err := injectHelper(input, format)
if err != nil {
return nil, err
}
encrypted, err := s.EncryptWithOpts(
alias,
value,
EncryptOpts{
Encoder: Base64Encoder,
WithPrefix: true,
},
)
if err != nil {
return []byte(""), err
}
err = setKey(inputData, encrypted, key)
if err != nil {
return nil, err
}
ret, err := codec.Marshal(&inputData)
if err != nil {
return []byte(""), merry.Wrap(err).WithUserMessage("error marshalling output")
}
return ret, nil
}
// InjectNotEncrypted inject the secret not encrypted. This can be used together with Encrypt()
func (s *Envelope) InjectNotEncrypted(alias string, input io.Reader, key string, value []byte, format string) ([]byte, error) {
inputData, codec, err := injectHelper(input, format)
if err != nil {
return nil, err
}
encrypted := value
err = setKey(inputData, encrypted, key)
if err != nil {
return nil, err
}
ret, err := codec.Marshal(&inputData)
if err != nil {
return []byte(""), merry.Wrap(err).WithUserMessage("error marshalling output")
}
return ret, nil
}
// injectHelper is a helper function for InjectEncrypted and InjectNotEncrypted
func injectHelper(input io.Reader, format string) (interface{}, structuredCodec, error) {
codec, err := codecForFormat(format)
if err != nil {
return nil, structuredCodec{}, merry.Wrap(err).WithUserMessage("unrecognized format").WithValue("format", format)
}
var inputData interface{}
inputBytes, err := ioutil.ReadAll(input)
if err != nil {
return nil, structuredCodec{}, err
}
err = codec.Unmarshal(inputBytes, &inputData)
if err != nil {
return nil, structuredCodec{}, merry.Wrap(err).WithUserMessage("could not decode input").WithValue("format", format)
}
return inputData, codec, nil
}
func setKey(inputData interface{}, encrypted interface{}, key string) error {
splitKey := strings.Split(key, ".")
err := traverser.SetKey(inputData, splitKey, fmt.Sprintf("%s", encrypted))
if err != nil {
return merry.Wrap(err).WithValue("key", key)
}
return nil
}