-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathpivnet.go
More file actions
467 lines (399 loc) · 12.5 KB
/
Copy pathpivnet.go
File metadata and controls
467 lines (399 loc) · 12.5 KB
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
package pivnet
import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"time"
"github.com/pivotal-cf/go-pivnet/v7/download"
"github.com/pivotal-cf/go-pivnet/v7/logger"
)
const (
DefaultHost = "https://network.tanzu.vmware.com"
apiVersion = "/api/v2"
concurrentDownloads = 10
)
type Client struct {
baseURL string
token AccessTokenService
userAgent string
logger logger.Logger
usingUAAToken bool
HTTP *http.Client
downloader download.Client
Auth *AuthService
EULA *EULAsService
ProductFiles *ProductFilesService
ArtifactReferences *ArtifactReferencesService
FederationToken *FederationTokenService
FileGroups *FileGroupsService
Releases *ReleasesService
Products *ProductsService
UserGroups *UserGroupsService
SubscriptionGroups *SubscriptionGroupsService
ReleaseTypes *ReleaseTypesService
ReleaseDependencies *ReleaseDependenciesService
DependencySpecifiers *DependencySpecifiersService
ReleaseUpgradePaths *ReleaseUpgradePathsService
UpgradePathSpecifiers *UpgradePathSpecifiersService
PivnetVersions *PivnetVersionsService
}
type AccessTokenOrLegacyToken struct {
host string
refreshToken string
skipSSLValidation bool
userAgent string
proxyAuthConfig ProxyAuthConfig
}
type QueryParameter struct {
Key string
Value string
}
func (o AccessTokenOrLegacyToken) AccessToken() (string, error) {
const legacyAPITokenLength = 20
if len(o.refreshToken) > legacyAPITokenLength {
baseURL := fmt.Sprintf("%s%s", o.host, apiVersion)
tokenFetcher := NewTokenFetcher(baseURL, o.refreshToken, o.skipSSLValidation, o.userAgent, o.proxyAuthConfig)
accessToken, err := tokenFetcher.GetToken()
if err != nil {
log.Panicf("Exiting with error: %s", err)
return "", err
}
return accessToken, nil
} else {
return o.refreshToken, nil
}
}
func AuthorizationHeader(accessToken string) (string, error) {
const legacyAPITokenLength = 20
if len(accessToken) > legacyAPITokenLength {
return fmt.Sprintf("Bearer %s", accessToken), nil
} else {
return fmt.Sprintf("Token %s", accessToken), nil
}
}
// ProxyAuthConfig contains proxy authentication configuration
type ProxyAuthConfig struct {
ProxyURL string // Proxy URL (e.g., "http://proxy.example.com:8080")
AuthType ProxyAuthType // Type of proxy authentication (basic, spnego)
Username string // Username for proxy authentication
Password string // Password for proxy authentication
Krb5Config string // Path to Kerberos config file (optional, for SPNEGO)
}
type ClientConfig struct {
Host string
UserAgent string
SkipSSLValidation bool
ProxyAuthConfig ProxyAuthConfig // Proxy authentication configuration (optional)
}
//go:generate counterfeiter . AccessTokenService
type AccessTokenService interface {
AccessToken() (string, error)
}
func NewAccessTokenOrLegacyToken(token string, host string, skipSSLValidation bool, userAgentOptional ...string) AccessTokenOrLegacyToken {
var userAgent = ""
if len(userAgentOptional) > 0 {
userAgent = userAgentOptional[0]
}
return AccessTokenOrLegacyToken{
refreshToken: token,
host: host,
skipSSLValidation: skipSSLValidation,
userAgent: userAgent,
proxyAuthConfig: ProxyAuthConfig{},
}
}
// NewAccessTokenOrLegacyTokenWithProxy creates an AccessTokenOrLegacyToken with proxy authentication support
func NewAccessTokenOrLegacyTokenWithProxy(token string, host string, skipSSLValidation bool, proxyAuthConfig ProxyAuthConfig, userAgentOptional ...string) AccessTokenOrLegacyToken {
var userAgent = ""
if len(userAgentOptional) > 0 {
userAgent = userAgentOptional[0]
}
return AccessTokenOrLegacyToken{
refreshToken: token,
host: host,
skipSSLValidation: skipSSLValidation,
userAgent: userAgent,
proxyAuthConfig: proxyAuthConfig,
}
}
// createProxyAuthTransport creates an HTTP transport with proxy authentication
func createProxyAuthTransport(config ClientConfig) (http.RoundTripper, error) {
// Validate required fields for proxy authentication
// Note: For Basic auth, username and password can be empty (though both empty means no auth header)
// For SPNEGO, username, password, and proxyURL are all required (validated in NewSPNEGOProxyAuth)
if config.ProxyAuthConfig.ProxyURL == "" {
return nil, fmt.Errorf("proxy URL is required when proxy authentication is specified")
}
// Parse proxy URL
proxyURL, err := url.Parse(config.ProxyAuthConfig.ProxyURL)
if err != nil {
return nil, fmt.Errorf("failed to parse proxy URL: %w", err)
}
// Create base transport
transport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: config.SkipSSLValidation,
},
Proxy: http.ProxyURL(proxyURL),
}
// Create authenticator
authenticator, err := NewProxyAuthenticator(config.ProxyAuthConfig)
if err != nil {
return nil, fmt.Errorf("failed to create proxy authenticator: %w", err)
}
// Wrap transport with proxy authentication
proxyAuthTransport, err := NewProxyAuthTransport(transport, authenticator)
if err != nil {
return nil, fmt.Errorf("failed to initialize proxy authentication: %w", err)
}
return proxyAuthTransport, nil
}
// initializeClientServices initializes all service endpoints for the client
func initializeClientServices(client *Client, lgr logger.Logger) {
client.Auth = &AuthService{client: *client}
client.EULA = &EULAsService{client: *client}
client.ProductFiles = &ProductFilesService{client: *client}
client.ArtifactReferences = &ArtifactReferencesService{client: *client}
client.FederationToken = &FederationTokenService{client: *client}
client.FileGroups = &FileGroupsService{client: *client}
client.Releases = &ReleasesService{client: *client, l: lgr}
client.Products = &ProductsService{client: *client, l: lgr}
client.UserGroups = &UserGroupsService{client: *client}
client.SubscriptionGroups = &SubscriptionGroupsService{client: *client}
client.ReleaseTypes = &ReleaseTypesService{client: *client}
client.ReleaseDependencies = &ReleaseDependenciesService{client: *client}
client.DependencySpecifiers = &DependencySpecifiersService{client: *client}
client.ReleaseUpgradePaths = &ReleaseUpgradePathsService{client: *client}
client.UpgradePathSpecifiers = &UpgradePathSpecifiersService{client: *client}
client.PivnetVersions = &PivnetVersionsService{client: *client}
}
func NewClient(
token AccessTokenService,
config ClientConfig,
lgr logger.Logger,
) Client {
baseURL := fmt.Sprintf("%s%s", config.Host, apiVersion)
baseTransport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: config.SkipSSLValidation,
},
Proxy: http.ProxyFromEnvironment,
}
httpClient := &http.Client{
Timeout: 10 * time.Minute,
Transport: baseTransport,
}
downloadClient := &http.Client{
Timeout: 0,
Transport: baseTransport,
}
ranger := download.NewRanger(concurrentDownloads)
downloader := download.Client{
HTTPClient: downloadClient,
Ranger: ranger,
Logger: lgr,
Timeout: 30 * time.Second,
}
client := Client{
baseURL: baseURL,
token: token,
userAgent: config.UserAgent,
logger: lgr,
downloader: downloader,
HTTP: httpClient,
}
initializeClientServices(&client, lgr)
return client
}
// NewClientWithProxy creates a new Pivnet client with optional proxy authentication support
func NewClientWithProxy(
token AccessTokenService,
config ClientConfig,
lgr logger.Logger,
) (Client, error) {
var transport http.RoundTripper
var err error
// If proxy authentication is configured, use it; otherwise use standard transport
if config.ProxyAuthConfig.AuthType != "" {
transport, err = createProxyAuthTransport(config)
if err != nil {
return Client{}, err
}
} else {
// Use standard transport with environment proxy support
transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: config.SkipSSLValidation,
},
Proxy: http.ProxyFromEnvironment,
}
}
client := Client{
baseURL: fmt.Sprintf("%s%s", config.Host, apiVersion),
token: token,
userAgent: config.UserAgent,
logger: lgr,
HTTP: &http.Client{
Timeout: 10 * time.Minute,
Transport: transport,
},
downloader: download.Client{
HTTPClient: &http.Client{
Timeout: 0,
Transport: transport,
},
Ranger: download.NewRanger(concurrentDownloads),
Logger: lgr,
Timeout: 30 * time.Second,
},
}
initializeClientServices(&client, lgr)
return client, nil
}
func (c Client) CreateRequest(
requestType string,
endpoint string,
body io.Reader,
) (*http.Request, error) {
u, err := url.Parse(c.baseURL)
if err != nil {
return nil, err
}
endpoint = c.stripHostPrefix(endpoint)
u.Path = u.Path + endpoint
req, err := http.NewRequest(requestType, u.String(), body)
if err != nil {
return nil, err
}
if !isVersionsEndpoint(endpoint) {
accessToken, err := c.token.AccessToken()
if err != nil {
return nil, err
}
authorizationHeader, err := AuthorizationHeader(accessToken)
if err != nil {
return nil, fmt.Errorf("could not create authorization header: %s", err)
}
req.Header.Add("Authorization", authorizationHeader)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", c.userAgent)
return req, nil
}
func (c Client) MakeRequest(
requestType string,
endpoint string,
expectedStatusCode int,
body io.Reader,
) (*http.Response, error) {
req, err := c.CreateRequest(requestType, endpoint, body)
if err != nil {
return nil, err
}
reqBytes, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
c.logger.Debug("Making request", logger.Data{"request": string(reqBytes)})
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
c.logger.Debug("Response status code", logger.Data{"status code": resp.StatusCode})
c.logger.Debug("Response headers", logger.Data{"headers": resp.Header})
if expectedStatusCode > 0 && resp.StatusCode != expectedStatusCode {
return nil, c.handleUnexpectedResponse(resp)
}
return resp, nil
}
func (c Client) MakeRequestWithParams(
requestType string,
endpoint string,
expectedStatusCode int,
params []QueryParameter,
body io.Reader,
) (*http.Response, error) {
req, err := c.CreateRequest(requestType, endpoint, body)
if err != nil {
return nil, err
}
q := req.URL.Query()
for _, param := range params {
q.Add(param.Key, param.Value)
}
req.URL.RawQuery = q.Encode()
reqBytes, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
c.logger.Debug("Making request", logger.Data{"request": string(reqBytes)})
resp, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
c.logger.Debug("Response status code", logger.Data{"status code": resp.StatusCode})
c.logger.Debug("Response headers", logger.Data{"headers": resp.Header})
if expectedStatusCode > 0 && resp.StatusCode != expectedStatusCode {
return nil, c.handleUnexpectedResponse(resp)
}
return resp, nil
}
func (c Client) stripHostPrefix(downloadLink string) string {
if strings.HasPrefix(downloadLink, apiVersion) {
return downloadLink
}
sp := strings.Split(downloadLink, apiVersion)
return sp[len(sp)-1]
}
func (c Client) handleUnexpectedResponse(resp *http.Response) error {
var pErr pivnetErr
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode == http.StatusTooManyRequests {
return newErrTooManyRequests()
}
// We have to handle 500 differently because it has a different structure
if resp.StatusCode == http.StatusInternalServerError {
var internalServerError pivnetInternalServerErr
err = json.Unmarshal(b, &internalServerError)
if err != nil {
return err
}
pErr = pivnetErr{
Message: internalServerError.Error,
}
} else {
err = json.Unmarshal(b, &pErr)
if err != nil {
return fmt.Errorf("could not parse json [%q] \n%s", b, err)
}
}
switch resp.StatusCode {
case http.StatusUnauthorized:
return newErrUnauthorized(pErr.Message)
case http.StatusNotFound:
return newErrNotFound(pErr.Message)
case http.StatusUnavailableForLegalReasons:
return newErrUnavailableForLegalReasons(pErr.Message)
case http.StatusProxyAuthRequired:
return newErrProxyAuthenticationRequired(pErr.Message)
default:
return ErrPivnetOther{
ResponseCode: resp.StatusCode,
Message: pErr.Message,
Errors: pErr.Errors,
}
}
}
func isVersionsEndpoint(endpoint string) bool {
return endpoint == "/versions"
}