2014-12-11 20:55:15 -05:00
|
|
|
package registry
|
|
|
|
|
|
|
|
import (
|
2014-12-12 16:30:12 -05:00
|
|
|
"encoding/json"
|
2014-12-11 20:55:15 -05:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"strings"
|
|
|
|
|
2015-03-29 09:51:08 -04:00
|
|
|
"github.com/docker/docker/pkg/requestdecorator"
|
2014-12-11 20:55:15 -05:00
|
|
|
)
|
|
|
|
|
2014-12-12 16:30:12 -05:00
|
|
|
type tokenResponse struct {
|
|
|
|
Token string `json:"token"`
|
|
|
|
}
|
|
|
|
|
2015-03-29 09:51:08 -04:00
|
|
|
func getToken(username, password string, params map[string]string, registryEndpoint *Endpoint, client *http.Client, factory *requestdecorator.RequestFactory) (token string, err error) {
|
2014-12-11 20:55:15 -05:00
|
|
|
realm, ok := params["realm"]
|
|
|
|
if !ok {
|
|
|
|
return "", errors.New("no realm specified for token auth challenge")
|
|
|
|
}
|
|
|
|
|
|
|
|
realmURL, err := url.Parse(realm)
|
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf("invalid token auth challenge realm: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if realmURL.Scheme == "" {
|
|
|
|
if registryEndpoint.IsSecure {
|
|
|
|
realmURL.Scheme = "https"
|
|
|
|
} else {
|
|
|
|
realmURL.Scheme = "http"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := factory.NewRequest("GET", realmURL.String(), nil)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
reqParams := req.URL.Query()
|
|
|
|
service := params["service"]
|
|
|
|
scope := params["scope"]
|
|
|
|
|
|
|
|
if service != "" {
|
|
|
|
reqParams.Add("service", service)
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, scopeField := range strings.Fields(scope) {
|
|
|
|
reqParams.Add("scope", scopeField)
|
|
|
|
}
|
|
|
|
|
2015-01-30 19:11:47 -05:00
|
|
|
if username != "" {
|
|
|
|
reqParams.Add("account", username)
|
|
|
|
req.SetBasicAuth(username, password)
|
|
|
|
}
|
2014-12-11 20:55:15 -05:00
|
|
|
|
|
|
|
req.URL.RawQuery = reqParams.Encode()
|
|
|
|
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
2014-12-12 16:30:12 -05:00
|
|
|
if resp.StatusCode != http.StatusOK {
|
2014-12-11 20:55:15 -05:00
|
|
|
return "", fmt.Errorf("token auth attempt for registry %s: %s request failed with status: %d %s", registryEndpoint, req.URL, resp.StatusCode, http.StatusText(resp.StatusCode))
|
|
|
|
}
|
|
|
|
|
2014-12-12 16:30:12 -05:00
|
|
|
decoder := json.NewDecoder(resp.Body)
|
|
|
|
|
|
|
|
tr := new(tokenResponse)
|
|
|
|
if err = decoder.Decode(tr); err != nil {
|
|
|
|
return "", fmt.Errorf("unable to decode token response: %s", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if tr.Token == "" {
|
|
|
|
return "", errors.New("authorization server did not include a token in the response")
|
2014-12-11 20:55:15 -05:00
|
|
|
}
|
|
|
|
|
2014-12-12 16:30:12 -05:00
|
|
|
return tr.Token, nil
|
2014-12-11 20:55:15 -05:00
|
|
|
}
|