/
server.go
347 lines (286 loc) · 9.92 KB
/
server.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/*
Copyright (c) 2022 Purple Clay
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 imds
import (
_ "embed"
"encoding/base64"
"encoding/json"
"net/http"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/purpleclay/imds-mock/pkg/imds/cache"
"github.com/purpleclay/imds-mock/pkg/imds/event"
"github.com/purpleclay/imds-mock/pkg/imds/middleware"
"github.com/purpleclay/imds-mock/pkg/imds/patch"
"github.com/purpleclay/imds-mock/pkg/imds/token"
"github.com/tidwall/gjson"
"go.uber.org/zap"
)
const (
notFound = `<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>404 - Not Found</title>
</head>
<body>
<h1>404 - Not Found</h1>
</body>
</html>`
badRequest = `<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>400 - Bad Request</title>
</head>
<body>
<h1>400 - Bad Request</h1>
</body>
</html>`
// V2TokenTTLHeader defines the HTTP header used by the IMDS service for
// generating a new IMDS session token
V2TokenTTLHeader = "X-aws-ec2-metadata-token-ttl-seconds"
)
//go:embed on-demand.json
var onDemandInstance []byte
// Really crude attempt to protect a byte array from concurrency issues during
// event driven patches
type patchedJSON struct {
data []byte
mu sync.RWMutex
}
func (p *patchedJSON) Bytes() []byte {
p.mu.RLock()
copy := p.data
p.mu.RUnlock()
return copy
}
func (p *patchedJSON) Patch(patcher patch.JSONPatcher) error {
p.mu.Lock()
var err error
p.data, err = patcher.Patch(p.data)
p.mu.Unlock()
return err
}
// Options provides a set of options for configuring the behaviour
// of the IMDS mock
type Options struct {
// AutoStart determines whether the IMDS mock immediately starts
// after initialisation
AutoStart bool
// ExcludeInstanceTags controls if the IMDS mock excludes instance
// tags from its supported list of metadata categories
ExcludeInstanceTags bool
// IMDSv2 enables exclusive V2 support only. All requests must contain
// a valid metadata token, otherwise they will be rejected. By default
// the mock will run with both V1 and V2 support
IMDSv2 bool
// InstanceTags contains a map of key value pairs that are to be
// exposed as instance tags through the IMDS mock
InstanceTags map[string]string
// Port controls the port that is used by the IMDS mock. By default
// it will use port 1338
Port int
// Pretty controls if the JSON outputted by any instance category
// is pretty printed. By default all JSON will be compacted
Pretty bool
// Spot enables the simulation of a spot instance and interruption notice
// through the IMDS mock. By default this will set to false and an on-demand
// instance will be simulated
Spot bool
// SpotAction defines the type of spot interruption event to be raised when
// simulating a spot instance. By default the spot interruption will be
// immediate, but can be delayed by a pre-configured interval
SpotAction SpotActionEvent
}
// SpotActionEvent defines a spot interruption event
type SpotActionEvent struct {
Action patch.SpotInstanceAction
Duration time.Duration
}
// DefaultOptions defines the default set of options that will be applied
// to the IMDS mock upon startup
var DefaultOptions = Options{
AutoStart: true,
ExcludeInstanceTags: false,
IMDSv2: false,
InstanceTags: map[string]string{
"Name": "imds-mock-ec2",
},
Port: 1338,
Pretty: false,
Spot: false,
SpotAction: SpotActionEvent{
Action: patch.TerminateSpotInstanceAction,
Duration: 0 * time.Second,
},
}
// Used as a hashset for quick lookups. Any matched path will just return its value
// and not be used to perform a key lookup
var reservedPaths = map[string]struct{}{
"iam.info": {},
"iam.security-credentials.ssm-access": {},
"spot.instance-action": {},
"events.recommendations.rebalance": {},
}
// Serve configures the IMDS mock using default options to handle HTTP requests
// in the exact same way as the IMDS service accessible from any EC2 instance
func Serve() (*gin.Engine, error) {
return ServeWith(DefaultOptions)
}
// ServeWith configures the IMDS mock based on the incoming options to handle HTTP requests
// in the exact same way as the IMDS service accessible from any EC2 instance
func ServeWith(opts Options) (*gin.Engine, error) {
r := gin.New()
injectGlobalMiddleware(r, opts)
// see: https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies
r.SetTrustedProxies(nil)
// Locally managed cache
memcache := cache.New()
// Manage the patching of the underlying JSON that is served by the IMDS mock
mockResponse := patchedJSON{data: onDemandInstance}
if !opts.ExcludeInstanceTags {
if err := mockResponse.Patch(patch.InstanceTag{Tags: opts.InstanceTags}); err != nil {
return nil, err
}
}
// Event based patching of spot instance
if opts.Spot {
if opts.SpotAction.Duration > 0 {
event.Once(opts.SpotAction.Duration, func() {
if patchErr := mockResponse.Patch(patch.Spot{InstanceAction: opts.SpotAction.Action}); patchErr != nil {
return
}
// Invalidate the cache to ensure the mock returns the new spot instance categories
memcache.Remove("/latest/meta-data", "/latest/meta-data/")
})
} else {
if err := mockResponse.Patch(patch.Spot{InstanceAction: opts.SpotAction.Action}); err != nil {
return nil, err
}
}
}
// Determine the type of auth for each endpoint
authMiddleware := selectAuthMiddleware(opts)
r.GET("/latest/meta-data", authMiddleware, middleware.Cache(memcache), func(c *gin.Context) {
c.String(http.StatusOK, keys(mockResponse.Bytes(), ""))
})
r.GET("/latest/meta-data/*category", authMiddleware, middleware.Cache(memcache), func(c *gin.Context) {
categoryPath := c.Param("category")
if categoryPath == "/" {
// Exact same behaviour as /latest/meta-data
c.String(http.StatusOK, keys(mockResponse.Bytes(), ""))
return
}
// Convert param into gjson path query
categoryPath = strings.TrimSuffix(categoryPath, "/")
categoryPath = strings.ReplaceAll(categoryPath, "/", ".")[1:]
// The IMDS service returns a 404 when attempting to query a field within a JSON instance category
if isReservedPathChild(categoryPath) {
c.Writer.Header().Add("Content-Type", "text/html")
c.String(http.StatusNotFound, notFound)
return
}
res := gjson.GetBytes(mockResponse.Bytes(), categoryPath)
if !res.Exists() {
c.Writer.Header().Add("Content-Type", "text/html")
c.String(http.StatusNotFound, notFound)
return
}
c.Writer.Header().Add("Content-Type", "text/plain")
// If the path returns a JSON object, then return a set of keys
if res.IsObject() && notReservedPath(categoryPath) {
c.String(http.StatusOK, keys(mockResponse.Bytes(), categoryPath))
} else {
c.String(http.StatusOK, res.String())
}
})
// Don't protect the token endpoint with any auth middleware
r.PUT("/latest/api/token", func(c *gin.Context) {
ttl, err := strconv.Atoi(c.Request.Header.Get(V2TokenTTLHeader))
if err == nil && (ttl > 0 && ttl <= token.MaxTTLInSeconds) {
tkn := token.NewV2(ttl)
out, _ := json.Marshal(&tkn)
c.Writer.Header().Add("Content-Type", "text/plain")
c.String(http.StatusOK, base64.StdEncoding.EncodeToString(out))
return
}
c.Writer.Header().Add("Content-Type", "text/html")
c.String(http.StatusBadRequest, badRequest)
})
var err error
if opts.AutoStart {
err = r.Run(":" + strconv.Itoa(opts.Port))
}
return r, err
}
func injectGlobalMiddleware(r *gin.Engine, opts Options) {
logger, _ := zap.NewProduction()
r.Use(middleware.ZapLogger(logger), middleware.ZapRecovery(logger))
if opts.Pretty {
r.Use(middleware.PrettyJSON())
} else {
r.Use(middleware.CompactJSON())
}
}
func selectAuthMiddleware(opts Options) gin.HandlerFunc {
if opts.IMDSv2 {
return middleware.StrictV2()
}
return middleware.V1OptionalV2()
}
func keys(json []byte, path string) string {
// Scan the JSON document, retrieving all of the top-level fields as keys
query := "@keys"
if path != "" {
query = path + ".@keys"
}
keys := gjson.GetBytes(json, query).Array()
categories := make([]string, 0, len(keys))
for _, key := range keys {
k := key.String()
// IMDS service returns a category with a trailing slash, if it is a parent category
query = k
if path != "" {
query = path + "." + k
}
if gjson.GetBytes(json, query).IsObject() {
k = k + "/"
}
categories = append(categories, k)
}
return strings.Join(categories, "\n")
}
func isReservedPathChild(path string) bool {
for key := range reservedPaths {
if strings.HasPrefix(path, key) && path != key {
return true
}
}
return false
}
func notReservedPath(path string) bool {
_, ok := reservedPaths[path]
return !ok
}