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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
|
package resolver
import (
"context"
"encoding/base64"
"fmt"
"maps"
"net/http"
"sort"
"strings"
"sync"
"time"
"github.com/containerd/containerd/remotes/docker"
"github.com/containerd/containerd/remotes/docker/auth"
remoteserrors "github.com/containerd/containerd/remotes/errors"
cerrdefs "github.com/containerd/errdefs"
"github.com/moby/buildkit/session"
sessionauth "github.com/moby/buildkit/session/auth"
log "github.com/moby/buildkit/util/bklog"
"github.com/moby/buildkit/util/flightcontrol"
"github.com/moby/buildkit/version"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
const defaultExpiration = 60
type authHandlerNS struct {
counter int64 // needs to be 64bit aligned for 32bit systems
handlers map[string]*authHandler
muHandlers sync.Mutex
hosts map[string][]docker.RegistryHost
muHosts sync.Mutex
sm *session.Manager
g flightcontrol.Group[[]docker.RegistryHost]
}
func newAuthHandlerNS(sm *session.Manager) *authHandlerNS {
return &authHandlerNS{
handlers: map[string]*authHandler{},
hosts: map[string][]docker.RegistryHost{},
sm: sm,
}
}
func (a *authHandlerNS) get(ctx context.Context, host string, sm *session.Manager, g session.Group) *authHandler {
if g != nil {
if iter := g.SessionIterator(); iter != nil {
for {
id := iter.NextSession()
if id == "" {
break
}
h, ok := a.handlers[host+"/"+id]
if ok {
h.lastUsed = time.Now()
return h
}
}
}
}
// link another handler
for k, h := range a.handlers {
parts := strings.SplitN(k, "/", 2)
if len(parts) != 2 {
continue
}
if parts[0] == host {
if h.authority != nil {
session, ok, err := sessionauth.VerifyTokenAuthority(ctx, host, h.authority, sm, g)
if err == nil && ok {
a.handlers[host+"/"+session] = h
h.lastUsed = time.Now()
return h
}
} else {
session, username, password, err := sessionauth.CredentialsFunc(sm, g)(host)
if err == nil {
if username == h.common.Username && password == h.common.Secret {
a.handlers[host+"/"+session] = h
h.lastUsed = time.Now()
return h
}
}
}
}
}
return nil
}
func (a *authHandlerNS) set(host, session string, h *authHandler) {
a.handlers[host+"/"+session] = h
}
func (a *authHandlerNS) delete(h *authHandler) {
maps.DeleteFunc(a.handlers, func(_ string, v *authHandler) bool {
return v == h
})
}
type dockerAuthorizer struct {
client *http.Client
sm *session.Manager
session session.Group
handlers *authHandlerNS
}
func newDockerAuthorizer(client *http.Client, handlers *authHandlerNS, sm *session.Manager, group session.Group) *dockerAuthorizer {
return &dockerAuthorizer{
client: client,
handlers: handlers,
sm: sm,
session: group,
}
}
// Authorize handles auth request.
func (a *dockerAuthorizer) Authorize(ctx context.Context, req *http.Request) error {
a.handlers.muHandlers.Lock()
defer a.handlers.muHandlers.Unlock()
// skip if there is no auth handler
ah := a.handlers.get(ctx, req.URL.Host, a.sm, a.session)
if ah == nil {
return nil
}
auth, err := ah.authorize(ctx, a.sm, a.session)
if err != nil {
return err
}
req.Header.Set("Authorization", auth)
return nil
}
func (a *dockerAuthorizer) getCredentials(host string) (sessionID, username, secret string, err error) {
return sessionauth.CredentialsFunc(a.sm, a.session)(host)
}
func (a *dockerAuthorizer) AddResponses(ctx context.Context, responses []*http.Response) error {
a.handlers.muHandlers.Lock()
defer a.handlers.muHandlers.Unlock()
last := responses[len(responses)-1]
host := last.Request.URL.Host
handler := a.handlers.get(ctx, host, a.sm, a.session)
for _, c := range auth.ParseAuthHeader(last.Header) {
if c.Scheme == auth.BearerAuth {
var oldScopes []string
if err := invalidAuthorization(c, responses); err != nil {
a.handlers.delete(handler)
if handler != nil {
oldScopes = handler.common.Scopes
}
handler = nil
// this hacky way seems to be best method to detect that error is fatal and should not be retried with a new token
if c.Parameters["error"] == "insufficient_scope" && parseScopes(oldScopes).contains(parseScopes(strings.Split(c.Parameters["scope"], " "))) {
return err
}
}
// reuse existing handler
//
// assume that one registry will return the common
// challenge information, including realm and service.
// and the resource scope is only different part
// which can be provided by each request.
if handler != nil {
return nil
}
var username, secret string
session, pubKey, err := sessionauth.GetTokenAuthority(ctx, host, a.sm, a.session)
if err != nil {
return err
}
if pubKey == nil {
session, username, secret, err = a.getCredentials(host)
if err != nil {
return err
}
}
common, err := auth.GenerateTokenOptions(ctx, host, username, secret, c)
if err != nil {
return err
}
common.Scopes = parseScopes(append(common.Scopes, oldScopes...)).normalize()
a.handlers.set(host, session, newAuthHandler(host, a.client, c.Scheme, pubKey, common))
return nil
} else if c.Scheme == auth.BasicAuth {
session, username, secret, err := a.getCredentials(host)
if err != nil {
return err
}
if username != "" && secret != "" {
common := auth.TokenOptions{
Username: username,
Secret: secret,
}
a.handlers.set(host, session, newAuthHandler(host, a.client, c.Scheme, nil, common))
return nil
}
}
}
return errors.Wrap(cerrdefs.ErrNotImplemented, "failed to find supported auth scheme")
}
// authResult is used to control limit rate.
type authResult struct {
token string
expires time.Time
}
// authHandler is used to handle auth request per registry server.
type authHandler struct {
g flightcontrol.Group[*authResult]
client *http.Client
// only support basic and bearer schemes
scheme auth.AuthenticationScheme
// common contains common challenge answer
common auth.TokenOptions
// scopedTokens caches token indexed by scopes, which used in
// bearer auth case
scopedTokens map[string]*authResult
scopedTokensMu sync.Mutex
lastUsed time.Time
host string
authority *[32]byte
}
func newAuthHandler(host string, client *http.Client, scheme auth.AuthenticationScheme, authority *[32]byte, opts auth.TokenOptions) *authHandler {
return &authHandler{
host: host,
client: client,
scheme: scheme,
common: opts,
scopedTokens: map[string]*authResult{},
lastUsed: time.Now(),
authority: authority,
}
}
func (ah *authHandler) authorize(ctx context.Context, sm *session.Manager, g session.Group) (string, error) {
switch ah.scheme {
case auth.BasicAuth:
return ah.doBasicAuth()
case auth.BearerAuth:
return ah.doBearerAuth(ctx, sm, g)
default:
return "", errors.Wrapf(cerrdefs.ErrNotImplemented, "failed to find supported auth scheme: %s", string(ah.scheme))
}
}
func (ah *authHandler) doBasicAuth() (string, error) {
username, secret := ah.common.Username, ah.common.Secret
if username == "" || secret == "" {
return "", errors.New("failed to handle basic auth because missing username or secret")
}
auth := base64.StdEncoding.EncodeToString([]byte(username + ":" + secret))
return fmt.Sprintf("Basic %s", auth), nil
}
func (ah *authHandler) doBearerAuth(ctx context.Context, sm *session.Manager, g session.Group) (token string, err error) {
// copy common tokenOptions
to := ah.common
to.Scopes = parseScopes(docker.GetTokenScopes(ctx, to.Scopes)).normalize()
// Docs: https://docs.docker.com/registry/spec/auth/scope
scoped := strings.Join(to.Scopes, " ")
res, err := ah.g.Do(ctx, scoped, func(ctx context.Context) (*authResult, error) {
ah.scopedTokensMu.Lock()
r, exist := ah.scopedTokens[scoped]
ah.scopedTokensMu.Unlock()
if exist {
if r.expires.IsZero() || r.expires.After(time.Now()) {
return r, nil
}
}
r, err := ah.fetchToken(ctx, sm, g, to)
if err != nil {
return nil, err
}
ah.scopedTokensMu.Lock()
ah.scopedTokens[scoped] = r
ah.scopedTokensMu.Unlock()
return r, nil
})
if err != nil || res == nil {
return "", err
}
return res.token, nil
}
func (ah *authHandler) fetchToken(ctx context.Context, sm *session.Manager, g session.Group, to auth.TokenOptions) (r *authResult, err error) {
var issuedAt time.Time
var expires int
var token string
defer func() {
token = fmt.Sprintf("Bearer %s", token)
if err == nil {
r = &authResult{token: token}
if issuedAt.IsZero() {
issuedAt = time.Now()
}
if exp := issuedAt.Add(time.Duration(float64(expires)*0.9) * time.Second); time.Now().Before(exp) {
r.expires = exp
}
}
}()
if ah.authority != nil {
resp, err := sessionauth.FetchToken(ctx, &sessionauth.FetchTokenRequest{
ClientID: "buildkit-client",
Host: ah.host,
Realm: to.Realm,
Service: to.Service,
Scopes: to.Scopes,
}, sm, g)
if err != nil {
return nil, err
}
if resp.ExpiresIn == 0 {
resp.ExpiresIn = defaultExpiration
}
expires = int(resp.ExpiresIn)
// We later check issuedAt.isZero, which would return
// false if converted from zero Unix time. Therefore,
// zero time value in response is handled separately
if resp.IssuedAt == 0 {
issuedAt = time.Time{}
} else {
issuedAt = time.Unix(resp.IssuedAt, 0)
}
token = resp.Token
return nil, nil
}
hdr := http.Header{}
hdr.Set("User-Agent", version.UserAgent())
// fetch token for the resource scope
if to.Secret != "" {
defer func() {
err = errors.Wrap(err, "failed to fetch oauth token")
}()
// try GET first because Docker Hub does not support POST
// switch once support has landed
resp, err := auth.FetchToken(ctx, ah.client, nil, to)
if err != nil {
var errStatus remoteserrors.ErrUnexpectedStatus
if errors.As(err, &errStatus) {
// retry with POST request
// As of September 2017, GCR is known to return 404.
// As of February 2018, JFrog Artifactory is known to return 401.
if (errStatus.StatusCode == 405 && to.Username != "") || errStatus.StatusCode == 404 || errStatus.StatusCode == 401 {
resp, err := auth.FetchTokenWithOAuth(ctx, ah.client, hdr, "buildkit-client", to)
if err != nil {
return nil, err
}
if resp.ExpiresIn == 0 {
resp.ExpiresIn = defaultExpiration
}
issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
token = resp.AccessToken
return nil, nil
}
log.G(ctx).WithFields(logrus.Fields{
"status": errStatus.Status,
"body": string(errStatus.Body),
}).Debugf("token request failed")
}
return nil, err
}
if resp.ExpiresIn == 0 {
resp.ExpiresIn = defaultExpiration
}
issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
token = resp.Token
return nil, nil
}
// do request anonymously
resp, err := auth.FetchToken(ctx, ah.client, hdr, to)
if err != nil {
return nil, errors.Wrap(err, "failed to fetch anonymous token")
}
if resp.ExpiresIn == 0 {
resp.ExpiresIn = defaultExpiration
}
issuedAt, expires = resp.IssuedAt, resp.ExpiresIn
token = resp.Token
return nil, nil
}
func invalidAuthorization(c auth.Challenge, responses []*http.Response) error {
errStr := c.Parameters["error"]
if errStr == "" {
return nil
}
n := len(responses)
if n == 1 || (n > 1 && !sameRequest(responses[n-2].Request, responses[n-1].Request)) {
return nil
}
return errors.Wrapf(docker.ErrInvalidAuthorization, "server message: %s", errStr)
}
func sameRequest(r1, r2 *http.Request) bool {
if r1.Method != r2.Method {
return false
}
if *r1.URL != *r2.URL {
return false
}
return true
}
type scopes map[string]map[string]struct{}
func parseScopes(s []string) scopes {
// https://docs.docker.com/registry/spec/auth/scope/
m := map[string]map[string]struct{}{}
for _, scopeStr := range s {
// The scopeStr may have strings that contain multiple scopes separated by a space.
for _, scope := range strings.Split(scopeStr, " ") {
parts := strings.SplitN(scope, ":", 3)
names := []string{parts[0]}
if len(parts) > 1 {
names = append(names, parts[1])
}
var actions []string
if len(parts) == 3 {
actions = append(actions, strings.Split(parts[2], ",")...)
}
name := strings.Join(names, ":")
ma, ok := m[name]
if !ok {
ma = map[string]struct{}{}
m[name] = ma
}
for _, a := range actions {
ma[a] = struct{}{}
}
}
}
return m
}
func (s scopes) normalize() []string {
names := make([]string, 0, len(s))
for n := range s {
names = append(names, n)
}
sort.Strings(names)
out := make([]string, 0, len(s))
for _, n := range names {
actions := make([]string, 0, len(s[n]))
for a := range s[n] {
actions = append(actions, a)
}
sort.Strings(actions)
out = append(out, n+":"+strings.Join(actions, ","))
}
return out
}
func (s scopes) contains(s2 scopes) bool {
for n := range s2 {
v, ok := s[n]
if !ok {
return false
}
for a := range s2[n] {
if _, ok := v[a]; !ok {
return false
}
}
}
return true
}
|