-
Notifications
You must be signed in to change notification settings - Fork 76
/
acr.go
262 lines (212 loc) · 6.16 KB
/
acr.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
package acr
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
jwt "github.com/golang-jwt/jwt/v5"
"github.com/jetstack/version-checker/pkg/api"
"github.com/jetstack/version-checker/pkg/client/util"
)
const (
userAgent = "jetstack/version-checker"
)
type Client struct {
*http.Client
Options
cacheMu sync.Mutex
cachedACRClient map[string]*acrClient
}
type acrClient struct {
tokenExpiry time.Time
*autorest.Client
}
type Options struct {
Username string
Password string
RefreshToken string
}
type ACRAccessTokenResponse struct {
AccessToken string `json:"access_token"`
}
type ACRManifestResponse struct {
Manifests []struct {
Digest string `json:"digest"`
CreatedTime time.Time `json:"createdTime"`
Tags []string `json:"tags"`
} `json:"manifests"`
}
func New(opts Options) (*Client, error) {
client := &http.Client{
Timeout: time.Second * 5,
}
if len(opts.RefreshToken) > 0 &&
(len(opts.Username) > 0 || len(opts.Password) > 0) {
return nil, errors.New("cannot specify refresh token as well as username/password")
}
return &Client{
Options: opts,
Client: client,
cachedACRClient: make(map[string]*acrClient),
}, nil
}
func (c *Client) Name() string {
return "acr"
}
func (c *Client) Tags(ctx context.Context, host, repo, image string) ([]api.ImageTag, error) {
client, err := c.getACRClient(ctx, host)
if err != nil {
return nil, err
}
resp, err := c.getManifestsWithClient(ctx, client, host, repo, image)
if err != nil {
return nil, err
}
var manifestResp ACRManifestResponse
if err := json.NewDecoder(resp.Body).Decode(&manifestResp); err != nil {
return nil, fmt.Errorf("%s: failed to decode manifest response: %s",
host, err)
}
var tags []api.ImageTag
for _, manifest := range manifestResp.Manifests {
if len(manifest.Tags) == 0 {
tags = append(tags, api.ImageTag{
SHA: manifest.Digest,
Timestamp: manifest.CreatedTime,
})
continue
}
for _, tag := range manifest.Tags {
tags = append(tags, api.ImageTag{
SHA: manifest.Digest,
Timestamp: manifest.CreatedTime,
Tag: tag,
})
}
}
return tags, nil
}
func (c *Client) getManifestsWithClient(ctx context.Context, client *acrClient, host, repo, image string) (*http.Response, error) {
urlParameters := map[string]interface{}{
"url": "https://" + host,
}
pathParameters := map[string]interface{}{
"name": autorest.Encode("path", util.JoinRepoImage(repo, image)),
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithCustomBaseURL("{url}", urlParameters),
autorest.WithPathParameters("/acr/v1/{name}/_manifests", pathParameters))
req, err := preparer.Prepare(new(http.Request).WithContext(ctx))
if err != nil {
return nil, fmt.Errorf("failed to prepare client: %s", err)
}
resp, err := autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("bad request for image host %s", host)
}
return nil, fmt.Errorf("bad request for image host %s: %s", host, body)
}
return resp, nil
}
func (c *Client) getACRClient(ctx context.Context, host string) (*acrClient, error) {
c.cacheMu.Lock()
defer c.cacheMu.Unlock()
if client, ok := c.cachedACRClient[host]; ok && time.Now().After(client.tokenExpiry) {
return client, nil
}
var (
client *acrClient
err error
)
if len(c.RefreshToken) > 0 {
client, err = c.getAccessTokenClient(ctx, host)
} else {
client, err = c.getBasicAuthClient(host)
}
if err != nil {
return nil, err
}
c.cachedACRClient[host] = client
return client, nil
}
func (c *Client) getBasicAuthClient(host string) (*acrClient, error) {
client := autorest.NewClientWithUserAgent(userAgent)
client.Authorizer = autorest.NewBasicAuthorizer(c.Username, c.Password)
return &acrClient{
Client: &client,
tokenExpiry: time.Unix(1<<63-1, 0),
}, nil
}
func (c *Client) getAccessTokenClient(ctx context.Context, host string) (*acrClient, error) {
client := autorest.NewClientWithUserAgent(userAgent)
urlParameters := map[string]interface{}{
"url": "https://" + host,
}
formDataParameters := map[string]interface{}{
"grant_type": "refresh_token",
"refresh_token": c.RefreshToken,
"scope": "repository:*:*",
"service": host,
}
preparer := autorest.CreatePreparer(
autorest.AsPost(),
autorest.WithCustomBaseURL("{url}", urlParameters),
autorest.WithPath("/oauth2/token"),
autorest.WithFormData(autorest.MapToValues(formDataParameters)))
req, err := preparer.Prepare((&http.Request{}).WithContext(ctx))
if err != nil {
return nil, err
}
resp, err := autorest.SendWithSender(client, req,
autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))
if err != nil {
return nil, fmt.Errorf("%s: failed to request access token: %s",
host, err)
}
var respToken ACRAccessTokenResponse
if err := json.NewDecoder(resp.Body).Decode(&respToken); err != nil {
return nil, fmt.Errorf("%s: failed to decode access token response: %s",
host, err)
}
exp, err := getTokenExpiration(respToken.AccessToken)
if err != nil {
return nil, fmt.Errorf("%s: %s", host, err)
}
token := &adal.Token{
RefreshToken: c.RefreshToken,
AccessToken: respToken.AccessToken,
}
client.Authorizer = autorest.NewBearerAuthorizer(token)
return &acrClient{
tokenExpiry: exp,
Client: &client,
}, nil
}
func getTokenExpiration(tokenString string) (time.Time, error) {
token, err := jwt.Parse(tokenString, nil, jwt.WithoutClaimsValidation())
if err != nil {
return time.Time{}, err
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return time.Time{}, fmt.Errorf("failed to process claims in access token")
}
if exp, ok := claims["exp"].(float64); ok {
timestamp := time.Unix(int64(exp), 0)
return timestamp, nil
}
return time.Time{}, fmt.Errorf("failed to find 'exp' claim in access token")
}