/
templates.go
246 lines (203 loc) · 6.63 KB
/
templates.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// MIT License
// Copyright (c) [2022] [Bohdan Ivashko (https://github.com/Arriven)]
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Package templates [provides utility functions to enable templating in app configuration]
package templates
import (
"context"
"encoding/base64"
"io"
"math/rand"
"net/http"
"strings"
"text/template"
"time"
"github.com/corpix/uarand"
"github.com/google/uuid"
"go.uber.org/zap"
)
func getURLContent(url string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
buf, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(buf), nil
}
func randomUUID() string {
return uuid.New().String()
}
func randomChar(from string) byte {
if len(from) == 0 {
return 0
}
return from[rand.Intn(len(from))] //nolint:gosec // Cryptographically secure random not required
}
func randomString(n int, from string) string {
b := make([]byte, n)
for i := range b {
b[i] = randomChar(from)
}
return string(b)
}
func randomAlpha(n int) string {
return randomString(n, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
}
func randomAplhaNum(n int) string {
return randomString(n, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
}
// ContextKey used to work with context and not trigger linter
type ContextKey string
func ctxKey(key string) ContextKey {
return ContextKey(key)
}
// Parse a template
func Parse(input string) (*template.Template, error) {
// TODO: consider adding ability to populate custom data
return template.New("tpl").Funcs(template.FuncMap{
"random_uuid": randomUUID,
"random_char": randomChar,
"random_string": randomString,
"random_alpha": randomAlpha,
"random_alphanum": randomAplhaNum,
"random_int_n": rand.Intn,
"random_int": rand.Int,
"random_payload": RandomPayload,
"random_payload_byte": RandomPayloadByte,
"random_ip": RandomIP,
"random_port": RandomPort,
"random_mac_addr": RandomMacAddr,
"random_user_agent": uarand.GetRandom,
"local_ip": LocalIPV4,
"local_ipv4": LocalIPV4,
"local_ipv6": LocalIPV6,
"local_mac_addr": LocalMacAddres,
"resolve_host": ResolveHostIPV4,
"resolve_host_ipv4": ResolveHostIPV4,
"resolve_host_ipv6": ResolveHostIPV6,
"base64_encode": base64.StdEncoding.EncodeToString,
"base64_decode": base64.StdEncoding.DecodeString,
"to_yaml": toYAML,
"from_yaml": fromYAML,
"from_yaml_array": fromYAMLArray,
"to_json": toJSON,
"from_json": fromJSON,
"from_json_array": fromJSONArray,
"from_string_array": fromStringArray,
"join": strings.Join,
"split": strings.Split,
"get_url": getURLContent,
"mod": mod,
"add": add,
"sub": sub,
"umod": umod,
"uadd": uadd,
"usub": usub,
"mod64": mod64,
"add64": add64,
"sub64": sub64,
"umod64": umod64,
"uadd64": uadd64,
"usub64": usub64,
"ctx_key": ctxKey,
"cookie_string": cookieString,
}).Parse(input)
}
// Execute template, returns empty string in case of errors
func Execute(logger *zap.Logger, tpl *template.Template, data any) string {
var res strings.Builder
if err := tpl.Execute(&res, data); err != nil {
logger.Debug("error executing template", zap.Error(err))
return ""
}
return res.String()
}
// ParseAndExecute template, returns input string in case of errors. Expensive operation.
func ParseAndExecute(logger *zap.Logger, input string, data any) string {
tpl, err := Parse(input)
if err != nil {
logger.Debug("error parsing template", zap.Error(err))
return input
}
var output strings.Builder
if err = tpl.Execute(&output, data); err != nil {
logger.Debug("error executing template", zap.Error(err))
return input
}
return output.String()
}
// ParseAndExecuteMapStruct is like ParseAndExecute but takes mapstructure as input
func ParseAndExecuteMapStruct(logger *zap.Logger, input map[string]any, data any) map[string]any {
tpl, err := ParseMapStruct(input)
if err != nil {
logger.Debug("error parsing template", zap.Error(err))
return input
}
return tpl.Execute(logger, data)
}
// MapStruct is a helper structure to parse configs in a format accepted by mapstructure package
type MapStruct struct {
tpl map[string]any
}
// ParseMapStruct is like Parse but takes mapstructure as input
func ParseMapStruct(input map[string]any) (*MapStruct, error) {
result := make(map[string]any)
for key, value := range input {
switch v := value.(type) {
case string:
tpl, err := Parse(v)
if err != nil {
return nil, err
}
result[key] = tpl
case map[string]any:
tpl, err := ParseMapStruct(v)
if err != nil {
return nil, err
}
result[key] = tpl
default:
result[key] = v
}
}
return &MapStruct{tpl: result}, nil
}
// Execute same as regular Execute
func (tpl *MapStruct) Execute(logger *zap.Logger, data any) map[string]any {
result := make(map[string]any)
for key, value := range tpl.tpl {
switch v := value.(type) {
case *template.Template:
result[key] = Execute(logger, v, data)
case *MapStruct:
result[key] = v.Execute(logger, data)
default:
result[key] = v
}
}
return result
}