-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
300 lines (273 loc) · 8.1 KB
/
config.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
package zia
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"net/url"
"regexp"
"strconv"
"sync"
"time"
"github.com/hashicorp/go-retryablehttp"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"
"github.com/zscaler/zscaler-sdk-go/logger"
)
const (
maxIdleConnections int = 40
requestTimeout int = 60
// JSessionIDTimeout = 30 // minutes.
jSessionTimeoutOffset = 5 * time.Minute
contentTypeJSON = "application/json"
cookieName = "JSESSIONID"
MaxNumOfRetries = 100
RetryWaitMaxSeconds = 20
RetryWaitMinSeconds = 5
// API types.
ziaAPIVersion = "api/v1"
ziaAPIAuthURL = "/authenticatedSession"
loggerPrefix = "zia-logger: "
)
// Client ...
type Client struct {
sync.Mutex
userName string
password string
apiKey string
session *Session
sessionRefreshed time.Time // Also indicates last usage
sessionTimeout time.Duration // in minutes
URL string
HTTPClient *http.Client
Logger logger.Logger
UserAgent string
}
// Session ...
type Session struct {
AuthType string `json:"authType"`
ObfuscateAPIKey bool `json:"obfuscateApiKey"`
PasswordExpiryTime int `json:"passwordExpiryTime"`
PasswordExpiryDays int `json:"passwordExpiryDays"`
Source string `json:"source"`
JSessionID string `json:"jSessionID,omitempty"`
}
// Credentials ...
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
APIKey string `json:"apiKey"`
TimeStamp string `json:"timestamp"`
}
func obfuscateAPIKey(apiKey, timeStamp string) (string, error) {
// check min required size
if len(timeStamp) < 6 || len(apiKey) < 12 {
return "", errors.New("time stamp or api key doesn't have required sizes")
}
seed := apiKey
high := timeStamp[len(timeStamp)-6:]
highInt, _ := strconv.Atoi(high)
low := fmt.Sprintf("%06d", highInt>>1)
key := ""
for i := 0; i < len(high); i++ {
index, _ := strconv.Atoi((string)(high[i]))
key += (string)(seed[index])
}
for i := 0; i < len(low); i++ {
index, _ := strconv.Atoi((string)(low[i]))
key += (string)(seed[index+2])
}
return key, nil
}
// NewClient Returns a Client from credentials passed as parameters.
func NewClient(username, password, apiKey, ziaCloud, userAgent string) (*Client, error) {
logger := logger.GetDefaultLogger(loggerPrefix)
httpClient := getHTTPClient(logger)
url := fmt.Sprintf("https://zsapi.%s.net/%s", ziaCloud, ziaAPIVersion)
if ziaCloud == "zspreview" {
url = fmt.Sprintf("https://admin.%s.net/%s", ziaCloud, ziaAPIVersion)
}
cli := Client{
userName: username,
password: password,
apiKey: apiKey,
HTTPClient: httpClient,
URL: url,
Logger: logger,
UserAgent: userAgent,
}
return &cli, nil
}
// MakeAuthRequestZIA ...
func MakeAuthRequestZIA(credentials *Credentials, url string, client *http.Client, userAgent string) (*Session, error) {
if credentials == nil {
return nil, fmt.Errorf("empty credentials")
}
data, err := json.Marshal(credentials)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url+ziaAPIAuthURL, bytes.NewReader(data))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentTypeJSON)
if userAgent != "" {
req.Header.Add("User-Agent", userAgent)
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("un-successful request with status code: %v", resp.Status)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var session Session
err = json.Unmarshal(body, &session)
if err != nil {
return nil, err
}
// We get the whole string match as session ID
session.JSessionID, err = extractJSessionIDFromHeaders(resp.Header)
if err != nil {
return nil, err
}
return &session, nil
}
func extractJSessionIDFromHeaders(header http.Header) (string, error) {
sessionIdStr := header.Get("Set-Cookie")
if sessionIdStr == "" {
return "", fmt.Errorf("no Set-Cookie header received")
}
regex := regexp.MustCompile("JSESSIONID=(.*?);")
// look for the first match we find
result := regex.FindStringSubmatch(sessionIdStr)
if len(result) < 2 {
return "", fmt.Errorf("couldn't find JSESSIONID in header value")
}
return result[1], nil
}
func getCurrentTimestampMilisecond() string {
return fmt.Sprintf("%d", time.Now().UnixNano()/int64(time.Millisecond))
}
// RefreshSession .. The caller should require lock.
func (c *Client) refreshSession() error {
timeStamp := getCurrentTimestampMilisecond()
obfuscatedKey, err := obfuscateAPIKey(c.apiKey, timeStamp)
if err != nil {
return err
}
credentialData := Credentials{
Username: c.userName,
Password: c.password,
APIKey: obfuscatedKey,
TimeStamp: timeStamp,
}
session, err := MakeAuthRequestZIA(&credentialData, c.URL, c.HTTPClient, c.UserAgent)
if err != nil {
return err
}
c.session = session
c.sessionRefreshed = time.Now()
return nil
}
// checkSession synce new session if its over the timeout limit.
func (c *Client) checkSession() error {
c.Lock()
defer c.Unlock()
// One call to this function is allowed at a time caller must call lock.
if c.session == nil {
err := c.refreshSession()
if err != nil {
c.Logger.Printf("[ERROR] failed to get session id: %v\n", err)
return err
}
} else {
now := time.Now()
// Refresh if session has expire time (diff than -1) & c.sessionTimeout less than jSessionTimeoutOffset time remaining. You never refresh on exact timeout.
if c.session.PasswordExpiryTime > 0 && c.sessionRefreshed.Add(c.sessionTimeout-jSessionTimeoutOffset).Before(now) {
err := c.refreshSession()
if err != nil {
c.Logger.Printf("[ERROR] failed to refresh session id: %v\n", err)
return err
}
}
}
url, err := url.Parse(c.URL)
if err != nil {
c.Logger.Printf("[ERROR] failed to parse url %s: %v\n", c.URL, err)
return err
}
if c.HTTPClient.Jar == nil {
c.HTTPClient.Jar, err = cookiejar.New(nil)
if err != nil {
c.Logger.Printf("[ERROR] failed to create new http cookie jar %v\n", err)
return err
}
}
c.HTTPClient.Jar.SetCookies(url, []*http.Cookie{
{
Name: cookieName,
Value: c.session.JSessionID,
},
})
return nil
}
func (c *Client) GetContentType() string {
return contentTypeJSON
}
func getHTTPClient(logger logger.Logger) *http.Client {
retryableClient := retryablehttp.NewClient()
retryableClient.RetryWaitMin = time.Second * time.Duration(RetryWaitMinSeconds)
retryableClient.RetryWaitMax = time.Second * time.Duration(RetryWaitMaxSeconds)
retryableClient.RetryMax = MaxNumOfRetries
retryableClient.CheckRetry = checkRetry
retryableClient.Logger = logger
retryableClient.HTTPClient.Timeout = time.Duration(requestTimeout) * time.Second
retryableClient.HTTPClient.Transport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
MaxIdleConnsPerHost: maxIdleConnections,
}
retryableClient.HTTPClient.Transport = logging.NewSubsystemLoggingHTTPTransport("gozscaler", retryableClient.HTTPClient.Transport)
return retryableClient.StandardClient()
}
func containsInt(codes []int, code int) bool {
for _, a := range codes {
if a == code {
return true
}
}
return false
}
// getRetryOnStatusCodes return a list of http status codes we want to apply retry on.
// Return empty slice to enable retry on all connection & server errors.
// Or return []int{429} to retry on only TooManyRequests error.
func getRetryOnStatusCodes() []int {
return []int{http.StatusTooManyRequests}
}
// Used to make http client retry on provided list of response status codes.
func checkRetry(ctx context.Context, resp *http.Response, err error) (bool, error) {
// do not retry on context.Canceled or context.DeadlineExceeded
if ctx.Err() != nil {
return false, ctx.Err()
}
if resp != nil && containsInt(getRetryOnStatusCodes(), resp.StatusCode) {
return true, nil
}
return retryablehttp.DefaultRetryPolicy(ctx, resp, err)
}
func (c *Client) Logout() error {
_, err := c.Request(ziaAPIAuthURL, "DELETE", nil, "application/json")
if err != nil {
return err
}
return nil
}