This repository has been archived by the owner on Mar 12, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathclient.go
276 lines (227 loc) · 8.08 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
package licensing
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"strings"
"github.com/docker/libtrust"
"github.com/docker/licensing/lib/errors"
"github.com/docker/licensing/lib/go-auth/jwt"
"github.com/docker/licensing/lib/go-clientlib"
"github.com/docker/licensing/model"
)
const (
trialProductID = "docker-ee-trial"
trialRatePlanID = "free-trial"
)
// Client represents the licensing package interface, including methods for authentication and interaction with Docker
// licensing, accounts, and billing services
type Client interface {
LoginViaAuth(ctx context.Context, username, password string) (authToken string, err error)
GetHubUserOrgs(ctx context.Context, authToken string) (orgs []model.Org, err error)
GetHubUserByName(ctx context.Context, username string) (user *model.User, err error)
VerifyLicense(ctx context.Context, license model.IssuedLicense) (res *model.CheckResponse, err error)
GenerateNewTrialSubscription(ctx context.Context, authToken, dockerID string) (subscriptionID string, err error)
ListSubscriptions(ctx context.Context, authToken, dockerID string) (response []*model.Subscription, err error)
ListSubscriptionsDetails(ctx context.Context, authToken, dockerID string) (response []*model.SubscriptionDetail, err error)
DownloadLicenseFromHub(ctx context.Context, authToken, subscriptionID string) (license *model.IssuedLicense, err error)
ParseLicense(license []byte) (parsedLicense *model.IssuedLicense, err error)
StoreLicense(ctx context.Context, dclnt WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error
LoadLocalLicense(ctx context.Context, dclnt WrappedDockerClient) (*model.Subscription, error)
SummarizeLicense(res *model.CheckResponse) *model.Subscription
}
func (c *client) LoginViaAuth(ctx context.Context, username, password string) (string, error) {
creds, err := c.login(ctx, username, password)
if err != nil {
return "", errors.Wrap(err, errors.Fields{
"username": username,
})
}
return creds.Token, nil
}
func (c *client) GetHubUserOrgs(ctx context.Context, authToken string) ([]model.Org, error) {
ctx = jwt.NewContext(ctx, authToken)
orgs, err := c.getUserOrgs(ctx, model.PaginationParams{})
if err != nil {
return nil, errors.WithMessage(err, "Failed to get orgs for user")
}
return orgs, nil
}
func (c *client) GetHubUserByName(ctx context.Context, username string) (*model.User, error) {
user, err := c.getUserByName(ctx, username)
if err != nil {
return nil, errors.Wrap(err, errors.Fields{
"username": username,
})
}
return user, nil
}
func (c *client) VerifyLicense(ctx context.Context, license model.IssuedLicense) (*model.CheckResponse, error) {
res, err := c.check(ctx, license)
if err != nil {
return nil, errors.WithMessage(err, "Failed to verify license")
}
return res, nil
}
func (c *client) GenerateNewTrialSubscription(ctx context.Context, authToken, dockerID string) (string, error) {
ctx = jwt.NewContext(ctx, authToken)
sub, err := c.createSubscription(ctx, &model.SubscriptionCreationRequest{
Name: "Docker Enterprise Free Trial",
DockerID: dockerID,
ProductID: trialProductID,
ProductRatePlan: trialRatePlanID,
Eusa: &model.EusaState{
Accepted: true,
},
})
if err != nil {
return "", errors.Wrap(err, errors.Fields{
"docker_id": dockerID,
})
}
return sub.ID, nil
}
// ListSubscriptions returns basic descriptions of all subscriptions to docker enterprise products for the given dockerID
func (c *client) ListSubscriptions(ctx context.Context, authToken, dockerID string) ([]*model.Subscription, error) {
ctx = jwt.NewContext(ctx, authToken)
subs, err := c.listSubscriptions(ctx, map[string]string{"docker_id": dockerID})
if err != nil {
return nil, errors.Wrap(err, errors.Fields{
"docker_id": dockerID,
})
}
// filter out non docker licenses
dockerSubs := []*model.Subscription{}
for _, sub := range subs {
if !strings.HasPrefix(sub.ProductID, "docker") {
continue
}
dockerSubs = append(dockerSubs, sub)
}
return dockerSubs, nil
}
// ListDetailedSubscriptions returns detailed subscriptions to docker enterprise products for the given dockerID
func (c *client) ListSubscriptionsDetails(ctx context.Context, authToken, dockerID string) ([]*model.SubscriptionDetail, error) {
ctx = jwt.NewContext(ctx, authToken)
subs, err := c.listSubscriptionsDetails(ctx, map[string]string{"docker_id": dockerID})
if err != nil {
return nil, errors.Wrap(err, errors.Fields{
"docker_id": dockerID,
})
}
// filter out non docker licenses
dockerSubs := []*model.SubscriptionDetail{}
for _, sub := range subs {
if !strings.HasPrefix(sub.ProductID, "docker") {
continue
}
dockerSubs = append(dockerSubs, sub)
}
return dockerSubs, nil
}
func (c *client) DownloadLicenseFromHub(ctx context.Context, authToken, subscriptionID string) (*model.IssuedLicense, error) {
ctx = jwt.NewContext(ctx, authToken)
license, err := c.getLicenseFile(ctx, subscriptionID)
if err != nil {
return nil, errors.Wrap(err, errors.Fields{
"subscriptionID": subscriptionID,
})
}
return license, nil
}
func (c *client) ParseLicense(license []byte) (*model.IssuedLicense, error) {
parsedLicense := &model.IssuedLicense{}
// The file may contain a leading BOM, which will choke the
// json deserializer.
license = bytes.Trim(license, "\xef\xbb\xbf")
if err := json.Unmarshal(license, &parsedLicense); err != nil {
return nil, errors.WithMessage(err, "failed to parse license")
}
return parsedLicense, nil
}
type client struct {
publicKeys []libtrust.PublicKey
hclient *http.Client
baseURI url.URL
}
// Config holds licensing client configuration
type Config struct {
BaseURI url.URL
HTTPClient *http.Client
// used by licensing client to validate an issued license
PublicKeys []string
}
func errorSummary(body []byte) string {
var be struct {
Message string `json:"message"`
}
jsonErr := json.Unmarshal(body, &be)
if jsonErr != nil {
return clientlib.DefaultErrorSummary(body)
}
return be.Message
}
// New creates a new licensing Client
func New(config *Config) (Client, error) {
publicKeys, err := unmarshalPublicKeys(config.PublicKeys)
if err != nil {
return nil, err
}
hclient := config.HTTPClient
if hclient == nil {
hclient = &http.Client{}
}
return &client{
baseURI: config.BaseURI,
hclient: hclient,
publicKeys: publicKeys,
}, nil
}
func unmarshalPublicKeys(publicKeys []string) ([]libtrust.PublicKey, error) {
trustKeys := make([]libtrust.PublicKey, len(publicKeys))
for i, publicKey := range publicKeys {
trustKey, err := unmarshalPublicKey(publicKey)
if err != nil {
return nil, err
}
trustKeys[i] = trustKey
}
return trustKeys, nil
}
func unmarshalPublicKey(publicKey string) (libtrust.PublicKey, error) {
pemBytes, err := base64.StdEncoding.DecodeString(publicKey)
if err != nil {
return nil, errors.Wrapf(err, errors.Fields{
"public_key": publicKey,
}, "decode public key failed")
}
key, err := libtrust.UnmarshalPublicKeyPEM(pemBytes)
if err != nil {
return nil, errors.Wrapf(err, errors.Fields{
"public_key": publicKey,
}, "unmarshal public key failed")
}
return key, nil
}
func (c *client) doReq(ctx context.Context, method string, url *url.URL, opts ...clientlib.RequestOption) (*http.Request, *http.Response, error) {
return clientlib.Do(ctx, method, url.String(), append(c.requestDefaults(), opts...)...)
}
func (c *client) doRequestNoAuth(ctx context.Context, method string, url *url.URL, opts ...clientlib.RequestOption) (*http.Request, *http.Response, error) {
return clientlib.Do(ctx, method, url.String(), append(c.requestDefaults(), opts...)...)
}
func (c *client) requestDefaults() []clientlib.RequestOption {
return []clientlib.RequestOption{
func(req *clientlib.Request) {
tok, _ := jwt.FromContext(req.Context())
req.Header.Add("Authorization", "Bearer "+tok)
req.ErrorSummary = errorSummary
req.Client = c.hclient
},
}
}
func (c *client) StoreLicense(ctx context.Context, dclnt WrappedDockerClient, licenses *model.IssuedLicense, localRootDir string) error {
return StoreLicense(ctx, dclnt, licenses, localRootDir)
}