2020-12-06 13:21:04 +01:00
|
|
|
package auth
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"errors"
|
|
|
|
|
"fmt"
|
2023-04-12 17:15:12 +02:00
|
|
|
"io"
|
2020-12-06 13:21:04 +01:00
|
|
|
"net/http"
|
|
|
|
|
"net/url"
|
|
|
|
|
"strings"
|
2025-11-14 14:30:37 +00:00
|
|
|
"sync"
|
|
|
|
|
"time"
|
2022-09-04 04:56:29 -07:00
|
|
|
|
|
|
|
|
"github.com/containrrr/watchtower/pkg/registry/helpers"
|
|
|
|
|
"github.com/containrrr/watchtower/pkg/types"
|
2023-10-04 12:17:38 +02:00
|
|
|
ref "github.com/distribution/reference"
|
2022-09-04 04:56:29 -07:00
|
|
|
"github.com/sirupsen/logrus"
|
2020-12-06 13:21:04 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// ChallengeHeader is the HTTP Header containing challenge instructions
|
|
|
|
|
const ChallengeHeader = "WWW-Authenticate"
|
|
|
|
|
|
|
|
|
|
// GetToken fetches a token for the registry hosting the provided image
|
|
|
|
|
func GetToken(container types.Container, registryAuth string) (string, error) {
|
2023-04-12 17:15:12 +02:00
|
|
|
normalizedRef, err := ref.ParseNormalizedNamed(container.ImageName())
|
|
|
|
|
if err != nil {
|
2020-12-06 13:21:04 +01:00
|
|
|
return "", err
|
|
|
|
|
}
|
2023-04-12 17:15:12 +02:00
|
|
|
|
|
|
|
|
URL := GetChallengeURL(normalizedRef)
|
|
|
|
|
logrus.WithField("URL", URL.String()).Debug("Built challenge URL")
|
2020-12-06 13:21:04 +01:00
|
|
|
|
|
|
|
|
var req *http.Request
|
|
|
|
|
if req, err = GetChallengeRequest(URL); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
client := &http.Client{}
|
|
|
|
|
var res *http.Response
|
|
|
|
|
if res, err = client.Do(req); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
2020-12-09 16:18:07 +01:00
|
|
|
defer res.Body.Close()
|
2020-12-06 13:21:04 +01:00
|
|
|
v := res.Header.Get(ChallengeHeader)
|
|
|
|
|
|
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
|
"status": res.Status,
|
|
|
|
|
"header": v,
|
|
|
|
|
}).Debug("Got response to challenge request")
|
|
|
|
|
|
|
|
|
|
challenge := strings.ToLower(v)
|
|
|
|
|
if strings.HasPrefix(challenge, "basic") {
|
|
|
|
|
if registryAuth == "" {
|
|
|
|
|
return "", fmt.Errorf("no credentials available")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return fmt.Sprintf("Basic %s", registryAuth), nil
|
|
|
|
|
}
|
|
|
|
|
if strings.HasPrefix(challenge, "bearer") {
|
2023-04-12 17:15:12 +02:00
|
|
|
return GetBearerHeader(challenge, normalizedRef, registryAuth)
|
2020-12-06 13:21:04 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return "", errors.New("unsupported challenge type from registry")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetChallengeRequest creates a request for getting challenge instructions
|
|
|
|
|
func GetChallengeRequest(URL url.URL) (*http.Request, error) {
|
|
|
|
|
req, err := http.NewRequest("GET", URL.String(), nil)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return nil, err
|
|
|
|
|
}
|
|
|
|
|
req.Header.Set("Accept", "*/*")
|
|
|
|
|
req.Header.Set("User-Agent", "Watchtower (Docker)")
|
|
|
|
|
return req, nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetBearerHeader tries to fetch a bearer token from the registry based on the challenge instructions
|
2023-04-12 17:15:12 +02:00
|
|
|
func GetBearerHeader(challenge string, imageRef ref.Named, registryAuth string) (string, error) {
|
2020-12-06 13:21:04 +01:00
|
|
|
client := http.Client{}
|
|
|
|
|
|
2025-11-14 14:30:37 +00:00
|
|
|
authURL, err := GetAuthURL(challenge, imageRef)
|
2020-12-06 13:21:04 +01:00
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-14 14:30:37 +00:00
|
|
|
// Build cache key from the auth realm, service and scope
|
|
|
|
|
cacheKey := authURL.String()
|
|
|
|
|
|
|
|
|
|
// Check cache first
|
|
|
|
|
if token := getCachedToken(cacheKey); token != "" {
|
|
|
|
|
return fmt.Sprintf("Bearer %s", token), nil
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-06 13:21:04 +01:00
|
|
|
var r *http.Request
|
|
|
|
|
if r, err = http.NewRequest("GET", authURL.String(), nil); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if registryAuth != "" {
|
2020-12-20 19:23:49 +01:00
|
|
|
logrus.Debug("Credentials found.")
|
2020-12-06 13:21:04 +01:00
|
|
|
r.Header.Add("Authorization", fmt.Sprintf("Basic %s", registryAuth))
|
|
|
|
|
} else {
|
|
|
|
|
logrus.Debug("No credentials found.")
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var authResponse *http.Response
|
|
|
|
|
if authResponse, err = client.Do(r); err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
2025-11-14 14:30:37 +00:00
|
|
|
defer authResponse.Body.Close()
|
2020-12-06 13:21:04 +01:00
|
|
|
|
2023-04-12 17:15:12 +02:00
|
|
|
body, _ := io.ReadAll(authResponse.Body)
|
2020-12-06 13:21:04 +01:00
|
|
|
tokenResponse := &types.TokenResponse{}
|
|
|
|
|
|
|
|
|
|
err = json.Unmarshal(body, tokenResponse)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return "", err
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-14 14:30:37 +00:00
|
|
|
// Cache token if ExpiresIn provided
|
|
|
|
|
if tokenResponse.Token != "" {
|
|
|
|
|
storeToken(cacheKey, tokenResponse.Token, tokenResponse.ExpiresIn)
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-06 13:21:04 +01:00
|
|
|
return fmt.Sprintf("Bearer %s", tokenResponse.Token), nil
|
|
|
|
|
}
|
|
|
|
|
|
2025-11-14 14:30:37 +00:00
|
|
|
// token cache implementation
|
|
|
|
|
type cachedToken struct {
|
|
|
|
|
token string
|
|
|
|
|
expiresAt time.Time
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var (
|
|
|
|
|
tokenCache = map[string]cachedToken{}
|
|
|
|
|
tokenCacheMu = &sync.Mutex{}
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// now is a package-level function returning current time. It is a variable so tests
|
|
|
|
|
// can override it for deterministic behavior.
|
|
|
|
|
var now = time.Now
|
|
|
|
|
|
|
|
|
|
// getCachedToken returns token string if present and not expired, otherwise empty
|
|
|
|
|
func getCachedToken(key string) string {
|
|
|
|
|
tokenCacheMu.Lock()
|
|
|
|
|
defer tokenCacheMu.Unlock()
|
|
|
|
|
if ct, ok := tokenCache[key]; ok {
|
|
|
|
|
if ct.expiresAt.IsZero() || now().Before(ct.expiresAt) {
|
|
|
|
|
return ct.token
|
|
|
|
|
}
|
|
|
|
|
// expired
|
|
|
|
|
delete(tokenCache, key)
|
|
|
|
|
}
|
|
|
|
|
return ""
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// storeToken stores token with optional ttl (seconds). ttl<=0 means no expiry.
|
|
|
|
|
func storeToken(key, token string, ttl int) {
|
|
|
|
|
tokenCacheMu.Lock()
|
|
|
|
|
defer tokenCacheMu.Unlock()
|
|
|
|
|
ct := cachedToken{token: token}
|
|
|
|
|
if ttl > 0 {
|
|
|
|
|
ct.expiresAt = now().Add(time.Duration(ttl) * time.Second)
|
|
|
|
|
}
|
|
|
|
|
tokenCache[key] = ct
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-06 13:21:04 +01:00
|
|
|
// GetAuthURL from the instructions in the challenge
|
2023-04-12 17:15:12 +02:00
|
|
|
func GetAuthURL(challenge string, imageRef ref.Named) (*url.URL, error) {
|
2020-12-06 13:21:04 +01:00
|
|
|
loweredChallenge := strings.ToLower(challenge)
|
|
|
|
|
raw := strings.TrimPrefix(loweredChallenge, "bearer")
|
|
|
|
|
|
|
|
|
|
pairs := strings.Split(raw, ",")
|
|
|
|
|
values := make(map[string]string, len(pairs))
|
|
|
|
|
|
|
|
|
|
for _, pair := range pairs {
|
|
|
|
|
trimmed := strings.Trim(pair, " ")
|
2023-04-12 08:18:00 +02:00
|
|
|
if key, val, ok := strings.Cut(trimmed, "="); ok {
|
|
|
|
|
values[key] = strings.Trim(val, `"`)
|
|
|
|
|
}
|
2020-12-06 13:21:04 +01:00
|
|
|
}
|
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
|
"realm": values["realm"],
|
|
|
|
|
"service": values["service"],
|
|
|
|
|
}).Debug("Checking challenge header content")
|
|
|
|
|
if values["realm"] == "" || values["service"] == "" {
|
|
|
|
|
|
|
|
|
|
return nil, fmt.Errorf("challenge header did not include all values needed to construct an auth url")
|
|
|
|
|
}
|
|
|
|
|
|
2022-09-04 04:56:29 -07:00
|
|
|
authURL, _ := url.Parse(values["realm"])
|
2020-12-06 13:21:04 +01:00
|
|
|
q := authURL.Query()
|
|
|
|
|
q.Add("service", values["service"])
|
2020-12-21 18:06:14 +01:00
|
|
|
|
2023-04-12 17:15:12 +02:00
|
|
|
scopeImage := ref.Path(imageRef)
|
2020-12-21 18:06:14 +01:00
|
|
|
|
2020-12-06 13:21:04 +01:00
|
|
|
scope := fmt.Sprintf("repository:%s:pull", scopeImage)
|
2023-04-12 17:15:12 +02:00
|
|
|
logrus.WithFields(logrus.Fields{"scope": scope, "image": imageRef.Name()}).Debug("Setting scope for auth token")
|
2020-12-06 13:21:04 +01:00
|
|
|
q.Add("scope", scope)
|
|
|
|
|
|
|
|
|
|
authURL.RawQuery = q.Encode()
|
|
|
|
|
return authURL, nil
|
|
|
|
|
}
|
|
|
|
|
|
2023-04-12 17:15:12 +02:00
|
|
|
// GetChallengeURL returns the URL to check auth requirements
|
|
|
|
|
// for access to a given image
|
|
|
|
|
func GetChallengeURL(imageRef ref.Named) url.URL {
|
|
|
|
|
host, _ := helpers.GetRegistryAddress(imageRef.Name())
|
2020-12-06 13:21:04 +01:00
|
|
|
|
|
|
|
|
URL := url.URL{
|
|
|
|
|
Scheme: "https",
|
|
|
|
|
Host: host,
|
|
|
|
|
Path: "/v2/",
|
|
|
|
|
}
|
2023-04-12 17:15:12 +02:00
|
|
|
return URL
|
2020-12-06 13:21:04 +01:00
|
|
|
}
|