-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver_test.go
102 lines (87 loc) · 2.37 KB
/
server_test.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
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"sync"
"testing"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/awstesting/unit"
)
func TestPassthrough(t *testing.T) {
for _, tc := range []struct {
Name string
AllowIMDSv1 bool
DisableIMDSv2 bool
}{
{
Name: "Default Behaviour",
AllowIMDSv1: true,
},
{
Name: "IMDSv1 Only",
AllowIMDSv1: true,
DisableIMDSv2: true,
},
{
Name: "IMDSv2 Only",
AllowIMDSv1: false,
},
} {
t.Run(tc.Name, func(t *testing.T) {
mdsvr := httptest.NewServer(&mockMetadataServer{
placementAZ: `us-east-1e`,
})
svr, err := newServer(newMetrics(), nil, ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(mdsvr.URL + "/latest")}), "eu-west-2")
if err != nil {
t.Fatal(err)
}
svr.EnableIMDS1 = tc.AllowIMDSv1
svr.disableIMDSv2 = tc.DisableIMDSv2
svr.debug = true
vsvr := httptest.NewServer(svr)
vmdc := ec2metadata.New(unit.Session, &aws.Config{Endpoint: aws.String(vsvr.URL + "/latest")})
iid, err := vmdc.GetInstanceIdentityDocument()
if err != nil {
t.Fatalf("getting instance identity doc from voucher: %v", err)
}
if iid.Region != "eu-west-2" {
t.Errorf("want instance identity doc region eu-west-2, got: %s", iid.Region)
}
paz, err := vmdc.GetMetadata("placement/availability-zone")
if err != nil {
t.Fatalf("error getting placement az: %v", err)
}
if paz != "us-east-1e" {
t.Errorf("want placement zone us-east-1e, got: %s", iid.Region)
}
})
}
}
type mockMetadataServer struct {
init sync.Once
mux *http.ServeMux
instanceDocument string
placementAZ string
}
func (m *mockMetadataServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.init.Do(func() {
m.mux = http.NewServeMux()
m.mux.HandleFunc("/latest/dynamic/instance-identity/document", func(w http.ResponseWriter, _ *http.Request) {
if m.instanceDocument == "" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
fmt.Fprint(w, m.instanceDocument)
})
m.mux.HandleFunc("/latest/meta-data/placement/availability-zone", func(w http.ResponseWriter, _ *http.Request) {
if m.placementAZ == "" {
http.Error(w, "Not found", http.StatusNotFound)
return
}
fmt.Fprint(w, m.placementAZ)
})
})
m.mux.ServeHTTP(w, r)
}