Merge pull request #1224 from ywk253100/161205_rm_auth_header

Do not add the authentication header to requests which are not sent to registry
This commit is contained in:
Daniel Jiang 2016-12-09 00:48:09 +08:00 committed by GitHub
commit 64ae107fe5
2 changed files with 48 additions and 2 deletions

View File

@ -18,6 +18,8 @@ package auth
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
au "github.com/docker/distribution/registry/client/auth"
@ -37,6 +39,7 @@ type Authorizer interface {
// And it implements interface Modifier
type AuthorizerStore struct {
authorizers []Authorizer
ping *url.URL
challenges []au.Challenge
}
@ -49,15 +52,21 @@ func NewAuthorizerStore(endpoint string, insecure bool, authorizers ...Authorize
Timeout: 30 * time.Second,
}
resp, err := client.Get(buildPingURL(endpoint))
pingURL := buildPingURL(endpoint)
resp, err := client.Get(pingURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
challenges := ParseChallengeFromResponse(resp)
ping, err := url.Parse(pingURL)
if err != nil {
return nil, err
}
return &AuthorizerStore{
authorizers: authorizers,
ping: ping,
challenges: challenges,
}, nil
}
@ -68,6 +77,23 @@ func buildPingURL(endpoint string) string {
// Modify adds authorization to the request
func (a *AuthorizerStore) Modify(req *http.Request) error {
//only handle the requests sent to registry
v2Index := strings.Index(req.URL.Path, "/v2/")
if v2Index == -1 {
return nil
}
ping := url.URL{
Host: req.URL.Host,
Scheme: req.URL.Scheme,
Path: req.URL.Path[:v2Index+4],
}
if ping.Host != a.ping.Host || ping.Scheme != a.ping.Scheme ||
ping.Path != a.ping.Path {
return nil
}
for _, challenge := range a.challenges {
for _, authorizer := range a.authorizers {
if authorizer.Scheme() == challenge.Scheme {

View File

@ -17,6 +17,7 @@ package auth
import (
"net/http"
"net/url"
"strings"
"testing"
@ -64,12 +65,17 @@ func TestModify(t *testing.T) {
Scheme: "bearer",
}
ping, err := url.Parse("http://example.com/v2/")
if err != nil {
t.Fatalf("failed to parse URL: %v", err)
}
as := &AuthorizerStore{
authorizers: []Authorizer{authorizer},
ping: ping,
challenges: []auth.Challenge{challenge},
}
req, err := http.NewRequest("GET", "http://example.com", nil)
req, err := http.NewRequest("GET", "http://example.com/v2/ubuntu/manifests/14.04", nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
@ -86,4 +92,18 @@ func TestModify(t *testing.T) {
if !strings.HasPrefix(header, "Bearer") {
t.Fatal("\"Authorization\" header does not start with \"Bearer\"")
}
req, err = http.NewRequest("GET", "http://example.com", nil)
if err != nil {
t.Fatalf("failed to create request: %v", err)
}
if err = as.Modify(req); err != nil {
t.Fatalf("failed to modify request: %v", err)
}
header = req.Header.Get("Authorization")
if len(header) != 0 {
t.Fatal("\"Authorization\" header should not be added")
}
}