ref: 1e080e371c0d283c335a163550171bc1eff736ad cisco/sdk/request.go -rw-r--r-- 5.5 KiB View raw
                                                                                
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
package cisco

import (
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

type Route struct {
	Path      string
	Method    string
	Protected bool
}

var InviteGetRoute Route = Route{
	Path:      "/invite",
	Method:    "GET",
	Protected: false,
}

var InviteClaimRoute Route = Route{
	Path:      "/invite/claim",
	Method:    "POST",
	Protected: false,
}

var InviteNewRoute Route = Route{
	Path:      "/invite",
	Method:    "POST",
	Protected: true,
}

var TokenNewRoute Route = Route{
	Path:      "/token/new",
	Method:    "POST",
	Protected: false,
}

var TokenListRoute Route = Route{
	Path:      "/token/list",
	Method:    "GET",
	Protected: true,
}

var TokenRevokeRoute Route = Route{
	Path:      "/token/revoke",
	Method:    "DELETE",
	Protected: true,
}

var AdminUserListRoute Route = Route{
	Path:      "/admin/user/list",
	Method:    "GET",
	Protected: true,
}

var AdminQuotaGetRoute Route = Route{
	Path:      "/admin/quota",
	Method:    "GET",
	Protected: true,
}

var AdminQuotaListRoute Route = Route{
	Path:      "/admin/quota/list",
	Method:    "GET",
	Protected: true,
}

var AdminQuotaCreateRoute Route = Route{
	Path:      "/admin/quota",
	Method:    "PUT",
	Protected: true,
}

var AdminQuotaDeleteRoute Route = Route{
	Path:      "/admin/quota",
	Method:    "DELETE",
	Protected: true,
}

var AdminQuotaUpdateInstanceRoute Route = Route{
	Path:      "/admin/quota/instance",
	Method:    "POST",
	Protected: true,
}

var AdminQuotaUpdateIpv4Route Route = Route{
	Path:      "/admin/quota/ipv4",
	Method:    "POST",
	Protected: true,
}

var AdminQuotaUpdateStorageRoute Route = Route{
	Path:      "/admin/quota/storage",
	Method:    "POST",
	Protected: true,
}

var AdminQuotaUpdateInvitesRoute Route = Route{
	Path:      "/admin/quota/invites",
	Method:    "POST",
	Protected: true,
}

var AdminUserGetRoute Route = Route{
	Path:      "/admin/user",
	Method:    "GET",
	Protected: true,
}

type Request struct {
	Arg  string
	Data interface{}
}

type ApiError struct {
	Code    int    `json:"code"`
	Error   string `json:"error"`
	Details string `json:"details"`
	Doc     string `json:"documentation"`
}

func SendRequest(route Route, req Request) (interface{}, error) {
	var apiError ApiError
	var err error
	var httpReq *http.Request
	var bytes []byte

	client := &http.Client{}
	uri := GlobalConfig.Endpoint + route.Path

	if req.Arg != "" {
		uri += "/" + req.Arg
	}

	if GlobalConfig.Debug == true {
		fmt.Printf("DEBUG: --- New request (%s)\n", time.Now().String())
		fmt.Printf("DEBUG: -> Sending request to endpoint %s\n", GlobalConfig.Endpoint)
		fmt.Printf("DEBUG: -> %s %s\n", route.Method, uri)
	}

	if req.Data == nil {
		httpReq, err = http.NewRequest(route.Method, uri, nil)
	} else {
		bytes, err = json.Marshal(req.Data)
		if err != nil {
			return nil, err
		}

		httpReq, err = http.NewRequest(route.Method, uri, strings.NewReader(string(bytes)))
		sum := md5.Sum(bytes)

		httpReq.Header.Add("Content-type", "application/json")
		httpReq.Header.Add("Content-MD5", hex.EncodeToString(sum[:]))
	}

	httpReq.Header.Add("Date", time.Now().String())

	if route.Protected == true {
		var toSign string

		httpReq.Header.Add("X-Csc-Key", GlobalConfig.Key)
		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: -> Route is marked as protected, signing request\n")
		}

		toSign = route.Method + uri + httpReq.Header.Get("Date") + GlobalConfig.Key
		if req.Data != nil {
			toSign += string(bytes) + httpReq.Header.Get("Content-MD5")
		}

		secretHex, err := hex.DecodeString(GlobalConfig.Secret)
		if err != nil {
			return nil, errors.New("The provided secret is not valid: " + err.Error())
		}

		h := hmac.New(sha256.New, secretHex)
		h.Write([]byte(toSign))
		signature := hex.EncodeToString(h.Sum(nil))
		httpReq.Header.Add("X-Csc-Signature", signature)

		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: -> String to sign: '%s'\n", toSign)
			fmt.Printf("DEBUG: -> Signature '%s'\n", signature)
		}
	}

	if GlobalConfig.Debug == true {
		if len(httpReq.Header) > 0 {
			fmt.Printf("DEBUG: -> Headers:\n")
		}

		for key, val := range httpReq.Header {
			fmt.Printf("DEBUG: -> \t%s: %s\n", key, val)
		}

		if req.Data != nil {
			fmt.Printf("DEBUG: -> Body\n")
			fmt.Printf("DEBUG: -> %s\n", req.Data)
		}

	}

	if err != nil {
		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: -> Could not create HTTP request: %s\n", err.Error())
			fmt.Printf("DEBUG: --- Request end (%s)\n", time.Now().String())
		}
		return nil, err
	}

	resp, err := client.Do(httpReq)
	if err != nil {
		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: -> Could not execute HTTP Request: %s\n", err.Error())
			fmt.Printf("DEBUG: --- Request end (%s)\n", time.Now().String())
		}
		return nil, err
	}

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: <- Could not read body of response: %s\n", err.Error())
			fmt.Printf("DEBUG: --- Request end (%s)\n", time.Now().String())
		}
		return nil, err
	}

	if GlobalConfig.Debug == true {
		fmt.Printf("DEBUG: <- Received response from %s\n", GlobalConfig.Endpoint)
		fmt.Printf("DEBUG: <- %s\n", data)
	}

	err = json.Unmarshal(data, &apiError)
	if err == nil && apiError.Code != 0 {
		if GlobalConfig.Debug == true {
			fmt.Printf("DEBUG: <- API error detected, parsing JSON\n")
			fmt.Printf("DEBUG: --- Request end (%s)\n", time.Now().String())
		}
		return nil, errors.New(apiError.Error + ": " + apiError.Details)
	}

	if GlobalConfig.Debug == true {
		fmt.Printf("DEBUG: --- Request end (%s)\n", time.Now().String())
	}
	return data, nil
}