-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathclient.go
278 lines (242 loc) · 6.89 KB
/
client.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
//
// Author:: Salim Afiune Maya (<[email protected]>)
// Copyright:: Copyright 2020, Lacework Inc.
// License:: Apache License, Version 2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package api
import (
"context"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/cenkalti/backoff/v4"
"github.com/lacework/go-sdk/v2/lwdomain"
"github.com/pkg/errors"
"go.uber.org/zap"
)
const (
defaultTimeout = 120 * time.Second
defaultTLSTimeout = 123 * time.Second
)
type Client struct {
id string
account string
subaccount string
apiVersion string
baseURL *url.URL
auth *authConfig
c *http.Client
log *zap.Logger
headers map[string]string
callbacks LifecycleCallbacks
retries *backoff.ExponentialBackOff
Policy *PolicyService
V2 *V2Endpoints
}
type Option interface {
apply(c *Client) error
}
type clientFunc func(c *Client) error
func (fn clientFunc) apply(c *Client) error {
return fn(c)
}
// New generates a new Lacework API client
//
// Example of basic usage
//
// lacework, err := api.NewClient("demo")
// if err == nil {
// lacework.Integrations.List()
// }
func NewClient(account string, opts ...Option) (*Client, error) {
if account == "" {
return nil, errors.New("account cannot be empty")
}
// verify if the user provided the full qualified domain name
if strings.Contains(account, ".lacework.net") {
domain, err := lwdomain.New(account)
if err != nil {
return nil, err
}
account = domain.String()
}
baseURL, err := url.Parse(fmt.Sprintf("https://%s.lacework.net", account))
if err != nil {
return nil, err
}
defaultTransport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: defaultTransportDialContext(&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}),
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: defaultTLSTimeout,
ExpectContinueTimeout: 1 * time.Second,
}
c := &Client{
id: newID(),
account: account,
baseURL: baseURL,
apiVersion: "v2",
headers: map[string]string{
"User-Agent": fmt.Sprintf("Go Client/%s", Version),
},
auth: &authConfig{
expiration: DefaultTokenExpiryTime,
},
c: &http.Client{Timeout: defaultTimeout,
Transport: defaultTransport},
}
c.V2 = NewV2Endpoints(c)
// init logger, this could change if a user calls api.WithLogLevel()
c.initLogger("")
for _, opt := range opts {
if err := opt.apply(c); err != nil {
return c, err
}
}
c.log.Info("api client created",
zap.String("url", c.baseURL.String()),
zap.String("version", c.apiVersion),
zap.String("log_level", c.log.Level().CapitalString()),
zap.Int("timeout", c.auth.expiration),
)
return c, nil
}
// CopyClient generates a copy of the provider Lacework API Go client
//
// Example of basic usage
//
// client, err := api.NewClient("demo")
// if err == nil {
// client.Integrations.List()
// }
//
// clientCopy, err := api.CopyClient(client, api.WithOrgAccess())
// if err == nil {
// clientCopy.Integrations.List()
// }
func CopyClient(origin *Client, opts ...Option) (*Client, error) {
dest := new(Client)
*dest = *origin
// no client should have the same ID
dest.id = newID()
for _, opt := range opts {
if err := opt.apply(dest); err != nil {
return dest, err
}
}
return dest, nil
}
// WithSubaccount sets a subaccount into an API client
func WithSubaccount(subaccount string) Option {
return clientFunc(func(c *Client) error {
if subaccount != "" {
c.log.Debug("setting up client", zap.String("subaccount", subaccount))
c.subaccount = subaccount
c.log.Debug("setting up header", zap.String("Account-Name", subaccount))
c.headers["Account-Name"] = subaccount
}
return nil
})
}
// WithTimeout changes the default client timeout
func WithTimeout(timeout time.Duration) Option {
return clientFunc(func(c *Client) error {
c.log.Debug("setting up client", zap.Reflect("timeout", timeout))
c.c.Timeout = timeout
return nil
})
}
// WithRetries sets the retrying policy for API requests
func WithRetries(retries *backoff.ExponentialBackOff) Option {
return clientFunc(func(c *Client) error {
c.log.Debug("setting up retrying policy", zap.Reflect("retries", retries))
c.retries = retries
return nil
})
}
// WithTransport changes the default transport to increase TLSHandshakeTimeout
func WithTransport(transport http.RoundTripper) Option {
return clientFunc(func(c *Client) error {
c.c.Transport = transport
return nil
})
}
// WithURL sets the base URL, this options is only available for test purposes
func WithURL(baseURL string) Option {
return clientFunc(func(c *Client) error {
u, err := url.Parse(baseURL)
if err != nil {
return err
}
c.log.Debug("setting up client", zap.String("url", baseURL))
c.baseURL = u
return nil
})
}
// WithHeader configures a HTTP Header to pass to every request
func WithHeader(header, value string) Option {
return clientFunc(func(c *Client) error {
if header != "" && value != "" {
c.log.Debug("setting up header", zap.String(header, value))
c.headers[header] = value
}
return nil
})
}
// WithOrgAccess sets the Org-Access Header to access the organization level data sets
func WithOrgAccess() Option {
return clientFunc(func(c *Client) error {
c.log.Debug("setting up header", zap.String("Org-Access", "true"))
c.headers["Org-Access"] = "true"
return nil
})
}
// URL returns the base url configured
func (c *Client) URL() string {
return c.baseURL.String()
}
// Retries returns the retrying policy configured
func (c *Client) Retries() *backoff.ExponentialBackOff {
return c.retries
}
// ValidAuth verifies that the client has valid authentication
func (c *Client) ValidAuth() bool {
return c.auth.token != ""
}
// OrgAccess check if the Org-Access header is set to 'true', if so,
// the client is configured to manage org level dataset
func (c *Client) OrgAccess() bool {
return c.headers["Org-Access"] == "true"
}
// newID generates a new client id, this id is useful for logging purposes
// when there are more than one client running on the same machine
func newID() string {
now := time.Now().UTC().UnixNano()
seed := rand.New(rand.NewSource(now))
return strconv.FormatInt(seed.Int63(), 16)
}
func defaultTransportDialContext(dialer *net.Dialer) func(context.Context, string, string) (net.Conn, error) {
return dialer.DialContext
}