| 1 |
package ociauth |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"errors" |
| 8 |
"fmt" |
| 9 |
"io" |
| 10 |
"net/http" |
| 11 |
"net/url" |
| 12 |
"slices" |
| 13 |
"strings" |
| 14 |
"sync" |
| 15 |
"time" |
| 16 |
|
| 17 |
"cuelabs.dev/go/oci/ociregistry" |
| 18 |
) |
| 19 |
|
| 20 |
|
| 21 |
const oauthClientID = "cuelabs-ociauth" |
| 22 |
|
| 23 |
var ErrNoAuth = fmt.Errorf("no authorization token available to add to request") |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
type stdTransport struct { |
| 32 |
config Config |
| 33 |
transport http.RoundTripper |
| 34 |
mu sync.Mutex |
| 35 |
registries map[string]*registry |
| 36 |
} |
| 37 |
|
| 38 |
type StdTransportParams struct { |
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
Config Config |
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
Transport http.RoundTripper |
| 47 |
} |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
func NewStdTransport(p StdTransportParams) http.RoundTripper { |
| 67 |
if p.Config == nil { |
| 68 |
p.Config = emptyConfig{} |
| 69 |
} |
| 70 |
if p.Transport == nil { |
| 71 |
p.Transport = http.DefaultTransport |
| 72 |
} |
| 73 |
return &stdTransport{ |
| 74 |
config: p.Config, |
| 75 |
transport: p.Transport, |
| 76 |
registries: make(map[string]*registry), |
| 77 |
} |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
type registry struct { |
| 82 |
host string |
| 83 |
transport http.RoundTripper |
| 84 |
config Config |
| 85 |
initOnce sync.Once |
| 86 |
initErr error |
| 87 |
|
| 88 |
|
| 89 |
mu sync.Mutex |
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
wwwAuthenticate *authHeader |
| 96 |
|
| 97 |
accessTokens []*scopedToken |
| 98 |
refreshToken string |
| 99 |
basic *userPass |
| 100 |
} |
| 101 |
|
| 102 |
type scopedToken struct { |
| 103 |
|
| 104 |
scope Scope |
| 105 |
|
| 106 |
token string |
| 107 |
|
| 108 |
expires time.Time |
| 109 |
} |
| 110 |
|
| 111 |
type userPass struct { |
| 112 |
username string |
| 113 |
password string |
| 114 |
} |
| 115 |
|
| 116 |
var forever = time.Date(99999, time.January, 1, 0, 0, 0, 0, time.UTC) |
| 117 |
|
| 118 |
|
| 119 |
func (a *stdTransport) RoundTrip(req *http.Request) (*http.Response, error) { |
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
req = req.Clone(req.Context()) |
| 124 |
|
| 125 |
|
| 126 |
|
| 127 |
needBodyClose := true |
| 128 |
defer func() { |
| 129 |
if needBodyClose && req.Body != nil { |
| 130 |
req.Body.Close() |
| 131 |
} |
| 132 |
}() |
| 133 |
|
| 134 |
a.mu.Lock() |
| 135 |
r := a.registries[req.URL.Host] |
| 136 |
if r == nil { |
| 137 |
r = ®istry{ |
| 138 |
host: req.URL.Host, |
| 139 |
config: a.config, |
| 140 |
transport: a.transport, |
| 141 |
} |
| 142 |
a.registries[r.host] = r |
| 143 |
} |
| 144 |
a.mu.Unlock() |
| 145 |
if err := r.init(); err != nil { |
| 146 |
return nil, err |
| 147 |
} |
| 148 |
|
| 149 |
ctx := req.Context() |
| 150 |
requiredScope := RequestInfoFromContext(ctx).RequiredScope |
| 151 |
wantScope := ScopeFromContext(ctx) |
| 152 |
|
| 153 |
if err := r.setAuthorization(ctx, req, requiredScope, wantScope); err != nil { |
| 154 |
return nil, err |
| 155 |
} |
| 156 |
resp, err := r.transport.RoundTrip(req) |
| 157 |
|
| 158 |
|
| 159 |
|
| 160 |
needBodyClose = false |
| 161 |
if err != nil { |
| 162 |
return nil, err |
| 163 |
} |
| 164 |
if resp.StatusCode != http.StatusUnauthorized { |
| 165 |
return resp, nil |
| 166 |
} |
| 167 |
challenge := challengeFromResponse(resp) |
| 168 |
if challenge == nil { |
| 169 |
return resp, nil |
| 170 |
} |
| 171 |
authAdded, tokenAcquired, err := r.setAuthorizationFromChallenge(ctx, req, challenge, requiredScope, wantScope) |
| 172 |
if err != nil { |
| 173 |
resp.Body.Close() |
| 174 |
return nil, err |
| 175 |
} |
| 176 |
if !authAdded { |
| 177 |
|
| 178 |
return resp, nil |
| 179 |
} |
| 180 |
resp.Body.Close() |
| 181 |
|
| 182 |
if req.GetBody != nil { |
| 183 |
req.Body, err = req.GetBody() |
| 184 |
if err != nil { |
| 185 |
return nil, err |
| 186 |
} |
| 187 |
} |
| 188 |
resp, err = r.transport.RoundTrip(req) |
| 189 |
if err != nil { |
| 190 |
return nil, err |
| 191 |
} |
| 192 |
if resp.StatusCode != http.StatusUnauthorized || !tokenAcquired { |
| 193 |
return resp, nil |
| 194 |
} |
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
resp.Body.Close() |
| 199 |
data, err := json.Marshal(&ociregistry.WireErrors{ |
| 200 |
Errors: []ociregistry.WireError{{ |
| 201 |
Code_: ociregistry.ErrDenied.Code(), |
| 202 |
Message: "unauthorized response with freshly acquired auth token", |
| 203 |
}}, |
| 204 |
}) |
| 205 |
if err != nil { |
| 206 |
return nil, fmt.Errorf("cannot marshal response body: %v", err) |
| 207 |
} |
| 208 |
resp.Header.Set("Content-Type", "application/json") |
| 209 |
resp.ContentLength = int64(len(data)) |
| 210 |
resp.Body = io.NopCloser(bytes.NewReader(data)) |
| 211 |
resp.StatusCode = http.StatusForbidden |
| 212 |
resp.Status = http.StatusText(resp.StatusCode) |
| 213 |
return resp, nil |
| 214 |
} |
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
func (r *registry) setAuthorization(ctx context.Context, req *http.Request, requiredScope, wantScope Scope) error { |
| 219 |
r.mu.Lock() |
| 220 |
defer r.mu.Unlock() |
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
r.deleteExpiredTokens(time.Now().UTC().Add(time.Second)) |
| 225 |
|
| 226 |
if accessToken := r.accessTokenForScope(requiredScope); accessToken != nil { |
| 227 |
|
| 228 |
req.Header.Set("Authorization", "Bearer "+accessToken.token) |
| 229 |
return nil |
| 230 |
} |
| 231 |
if r.wwwAuthenticate == nil { |
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
return nil |
| 237 |
} |
| 238 |
if r.refreshToken != "" && r.wwwAuthenticate.scheme == "bearer" { |
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
accessToken, err := r.acquireAccessToken(ctx, requiredScope, wantScope) |
| 248 |
if err != nil { |
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
return fmt.Errorf("cannot acquire access token: %v", err) |
| 253 |
} |
| 254 |
req.Header.Set("Authorization", "Bearer "+accessToken) |
| 255 |
return nil |
| 256 |
} |
| 257 |
if r.wwwAuthenticate.scheme != "bearer" && r.basic != nil { |
| 258 |
req.SetBasicAuth(r.basic.username, r.basic.password) |
| 259 |
return nil |
| 260 |
} |
| 261 |
return nil |
| 262 |
} |
| 263 |
|
| 264 |
func (r *registry) setAuthorizationFromChallenge(ctx context.Context, req *http.Request, challenge *authHeader, requiredScope, wantScope Scope) (authAdded, tokenAcquired bool, _ error) { |
| 265 |
r.mu.Lock() |
| 266 |
defer r.mu.Unlock() |
| 267 |
r.wwwAuthenticate = challenge |
| 268 |
|
| 269 |
switch { |
| 270 |
case r.wwwAuthenticate.scheme == "bearer": |
| 271 |
scope := ParseScope(r.wwwAuthenticate.params["scope"]) |
| 272 |
accessToken, err := r.acquireAccessToken(ctx, scope, wantScope.Union(requiredScope)) |
| 273 |
if err != nil { |
| 274 |
return false, false, err |
| 275 |
} |
| 276 |
req.Header.Set("Authorization", "Bearer "+accessToken) |
| 277 |
return true, true, nil |
| 278 |
case r.basic != nil: |
| 279 |
req.SetBasicAuth(r.basic.username, r.basic.password) |
| 280 |
return true, false, nil |
| 281 |
} |
| 282 |
return false, false, nil |
| 283 |
} |
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
func (r *registry) init() error { |
| 292 |
inner := func() error { |
| 293 |
info, err := r.config.EntryForRegistry(r.host) |
| 294 |
if err != nil { |
| 295 |
return fmt.Errorf("cannot acquire auth info for registry %q: %v", r.host, err) |
| 296 |
} |
| 297 |
r.refreshToken = info.RefreshToken |
| 298 |
if info.AccessToken != "" { |
| 299 |
r.accessTokens = append(r.accessTokens, &scopedToken{ |
| 300 |
scope: UnlimitedScope(), |
| 301 |
token: info.AccessToken, |
| 302 |
expires: forever, |
| 303 |
}) |
| 304 |
} |
| 305 |
if info.Username != "" && info.Password != "" { |
| 306 |
r.basic = &userPass{ |
| 307 |
username: info.Username, |
| 308 |
password: info.Password, |
| 309 |
} |
| 310 |
} |
| 311 |
return nil |
| 312 |
} |
| 313 |
r.initOnce.Do(func() { |
| 314 |
r.initErr = inner() |
| 315 |
}) |
| 316 |
return r.initErr |
| 317 |
} |
| 318 |
|
| 319 |
|
| 320 |
|
| 321 |
|
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
|
| 328 |
func (r *registry) acquireAccessToken(ctx context.Context, requiredScope, wantScope Scope) (string, error) { |
| 329 |
scope := requiredScope.Union(wantScope) |
| 330 |
tok, err := r.acquireToken(ctx, scope) |
| 331 |
if err != nil { |
| 332 |
var herr ociregistry.HTTPError |
| 333 |
if !errors.As(err, &herr) || herr.StatusCode() != http.StatusUnauthorized { |
| 334 |
return "", err |
| 335 |
} |
| 336 |
|
| 337 |
|
| 338 |
|
| 339 |
|
| 340 |
|
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
|
| 348 |
scope = requiredScope |
| 349 |
tok, err = r.acquireToken(ctx, scope) |
| 350 |
if err != nil { |
| 351 |
return "", err |
| 352 |
} |
| 353 |
|
| 354 |
|
| 355 |
} |
| 356 |
if tok.RefreshToken != "" { |
| 357 |
r.refreshToken = tok.RefreshToken |
| 358 |
} |
| 359 |
accessToken := tok.Token |
| 360 |
if accessToken == "" { |
| 361 |
accessToken = tok.AccessToken |
| 362 |
} |
| 363 |
if accessToken == "" { |
| 364 |
return "", fmt.Errorf("no access token found in auth server response") |
| 365 |
} |
| 366 |
var expires time.Time |
| 367 |
now := time.Now().UTC() |
| 368 |
if tok.ExpiresIn == 0 { |
| 369 |
expires = now.Add(60 * time.Second) |
| 370 |
} else { |
| 371 |
expires = now.Add(time.Duration(tok.ExpiresIn) * time.Second) |
| 372 |
} |
| 373 |
r.accessTokens = append(r.accessTokens, &scopedToken{ |
| 374 |
scope: scope, |
| 375 |
token: accessToken, |
| 376 |
expires: expires, |
| 377 |
}) |
| 378 |
|
| 379 |
|
| 380 |
return accessToken, nil |
| 381 |
} |
| 382 |
|
| 383 |
func (r *registry) acquireToken(ctx context.Context, scope Scope) (*wireToken, error) { |
| 384 |
realm := r.wwwAuthenticate.params["realm"] |
| 385 |
if realm == "" { |
| 386 |
return nil, fmt.Errorf("malformed Www-Authenticate header (missing realm)") |
| 387 |
} |
| 388 |
if r.refreshToken != "" { |
| 389 |
v := url.Values{} |
| 390 |
v.Set("scope", scope.String()) |
| 391 |
if service := r.wwwAuthenticate.params["service"]; service != "" { |
| 392 |
v.Set("service", service) |
| 393 |
} |
| 394 |
v.Set("client_id", oauthClientID) |
| 395 |
v.Set("grant_type", "refresh_token") |
| 396 |
v.Set("refresh_token", r.refreshToken) |
| 397 |
req, err := http.NewRequestWithContext(ctx, "POST", realm, strings.NewReader(v.Encode())) |
| 398 |
if err != nil { |
| 399 |
return nil, fmt.Errorf("cannot form HTTP request to %q: %v", realm, err) |
| 400 |
} |
| 401 |
req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 402 |
tok, err := r.doTokenRequest(req) |
| 403 |
if err == nil { |
| 404 |
return tok, nil |
| 405 |
} |
| 406 |
var herr ociregistry.HTTPError |
| 407 |
if !errors.As(err, &herr) || herr.StatusCode() != http.StatusNotFound { |
| 408 |
return tok, err |
| 409 |
} |
| 410 |
|
| 411 |
|
| 412 |
|
| 413 |
|
| 414 |
|
| 415 |
} |
| 416 |
u, err := url.Parse(realm) |
| 417 |
if err != nil { |
| 418 |
return nil, fmt.Errorf("malformed Www-Authenticate header (malformed realm %q): %v", realm, err) |
| 419 |
} |
| 420 |
v := u.Query() |
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
v["scope"] = strings.Split(scope.String(), " ") |
| 425 |
if service := r.wwwAuthenticate.params["service"]; service != "" { |
| 426 |
|
| 427 |
|
| 428 |
v.Set("service", service) |
| 429 |
} |
| 430 |
u.RawQuery = v.Encode() |
| 431 |
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil) |
| 432 |
if err != nil { |
| 433 |
return nil, err |
| 434 |
} |
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
if r.basic != nil { |
| 439 |
req.SetBasicAuth(r.basic.username, r.basic.password) |
| 440 |
} |
| 441 |
return r.doTokenRequest(req) |
| 442 |
} |
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
type wireToken struct { |
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
Token string `json:"token"` |
| 456 |
AccessToken string `json:"access_token,omitempty"` |
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
RefreshToken string `json:"refresh_token"` |
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
|
| 470 |
ExpiresIn int `json:"expires_in"` |
| 471 |
} |
| 472 |
|
| 473 |
func (r *registry) doTokenRequest(req *http.Request) (*wireToken, error) { |
| 474 |
client := &http.Client{ |
| 475 |
Transport: r.transport, |
| 476 |
} |
| 477 |
resp, err := client.Do(req) |
| 478 |
if err != nil { |
| 479 |
return nil, err |
| 480 |
} |
| 481 |
defer resp.Body.Close() |
| 482 |
data, bodyErr := io.ReadAll(resp.Body) |
| 483 |
if resp.StatusCode != http.StatusOK { |
| 484 |
return nil, ociregistry.NewHTTPError(nil, resp.StatusCode, resp, data) |
| 485 |
} |
| 486 |
if bodyErr != nil { |
| 487 |
return nil, fmt.Errorf("error reading response body: %v", err) |
| 488 |
} |
| 489 |
var tok wireToken |
| 490 |
if err := json.Unmarshal(data, &tok); err != nil { |
| 491 |
return nil, fmt.Errorf("malformed JSON token in response: %v", err) |
| 492 |
} |
| 493 |
return &tok, nil |
| 494 |
} |
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
func (r *registry) deleteExpiredTokens(now time.Time) { |
| 500 |
r.accessTokens = slices.DeleteFunc(r.accessTokens, func(tok *scopedToken) bool { |
| 501 |
return now.After(tok.expires) |
| 502 |
}) |
| 503 |
} |
| 504 |
|
| 505 |
func (r *registry) accessTokenForScope(scope Scope) *scopedToken { |
| 506 |
for _, tok := range r.accessTokens { |
| 507 |
if tok.scope.Contains(scope) { |
| 508 |
|
| 509 |
return tok |
| 510 |
} |
| 511 |
} |
| 512 |
return nil |
| 513 |
} |
| 514 |
|
| 515 |
type emptyConfig struct{} |
| 516 |
|
| 517 |
func (emptyConfig) EntryForRegistry(host string) (ConfigEntry, error) { |
| 518 |
return ConfigEntry{}, nil |
| 519 |
} |