registry: minor improvements and cleanup

- registry: newIndexInfo(): minor refactor
- registry: loadAllowNondistributableArtifacts() minor refactor
  initialise the slices with a length.
- registry: defaultService.Search(): minor refactor
  Perform all manipulation earlier, so that it's not needed to scroll up
  to learn what's done.
- various other minor cleanups

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
This commit is contained in:
Sebastiaan van Stijn 2022-02-26 14:32:13 +01:00
parent d3c3e2c867
commit 9cb0aa4c91
No known key found for this signature in database
GPG Key ID: 76698F39D527CE8C
4 changed files with 20 additions and 36 deletions

View File

@ -15,10 +15,8 @@ import (
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
const ( // AuthClientID is used the ClientID used for the token server
// AuthClientID is used the ClientID used for the token server const AuthClientID = "docker"
AuthClientID = "docker"
)
type loginCredentialStore struct { type loginCredentialStore struct {
authConfig *types.AuthConfig authConfig *types.AuthConfig
@ -109,8 +107,7 @@ func loginV2(authConfig *types.AuthConfig, endpoint APIEndpoint, userAgent strin
} }
// TODO(dmcgowan): Attempt to further interpret result, status code and error code string // TODO(dmcgowan): Attempt to further interpret result, status code and error code string
err = errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode)) return "", "", errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode))
return "", "", err
} }
func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) { func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, error) {
@ -129,10 +126,9 @@ func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifi
tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions) tokenHandler := auth.NewTokenHandlerWithOptions(tokenHandlerOptions)
basicHandler := auth.NewBasicHandler(creds) basicHandler := auth.NewBasicHandler(creds)
modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)) modifiers = append(modifiers, auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler))
tr := transport.NewTransport(authTransport, modifiers...)
return &http.Client{ return &http.Client{
Transport: tr, Transport: transport.NewTransport(authTransport, modifiers...),
Timeout: 15 * time.Second, Timeout: 15 * time.Second,
}, nil }, nil
} }
@ -146,10 +142,7 @@ func ConvertToHostname(url string) string {
} else if strings.HasPrefix(url, "https://") { } else if strings.HasPrefix(url, "https://") {
stripped = strings.TrimPrefix(url, "https://") stripped = strings.TrimPrefix(url, "https://")
} }
return strings.SplitN(stripped, "/", 2)[0]
nameParts := strings.SplitN(stripped, "/", 2)
return nameParts[0]
} }
// ResolveAuthConfig matches an auth configuration to a server address or a URL // ResolveAuthConfig matches an auth configuration to a server address or a URL

View File

@ -110,12 +110,12 @@ func (config *serviceConfig) loadAllowNondistributableArtifacts(registries []str
} }
} }
config.AllowNondistributableArtifactsCIDRs = make([]*(registry.NetIPNet), 0) config.AllowNondistributableArtifactsCIDRs = make([]*registry.NetIPNet, 0, len(cidrs))
for _, c := range cidrs { for _, c := range cidrs {
config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c) config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c)
} }
config.AllowNondistributableArtifactsHostnames = make([]string, 0) config.AllowNondistributableArtifactsHostnames = make([]string, 0, len(hostnames))
for h := range hostnames { for h := range hostnames {
config.AllowNondistributableArtifactsHostnames = append(config.AllowNondistributableArtifactsHostnames, h) config.AllowNondistributableArtifactsHostnames = append(config.AllowNondistributableArtifactsHostnames, h)
} }
@ -378,13 +378,12 @@ func newIndexInfo(config *serviceConfig, indexName string) (*registry.IndexInfo,
} }
// Construct a non-configured index info. // Construct a non-configured index info.
index := &registry.IndexInfo{ return &registry.IndexInfo{
Name: indexName, Name: indexName,
Mirrors: make([]string, 0), Mirrors: make([]string, 0),
Secure: isSecureIndex(config, indexName),
Official: false, Official: false,
} }, nil
index.Secure = isSecureIndex(config, indexName)
return index, nil
} }
// GetAuthConfigKey special-cases using the full index address of the official // GetAuthConfigKey special-cases using the full index address of the official

View File

@ -67,7 +67,7 @@ func validateEndpoint(endpoint *v1Endpoint) error {
} }
// If registry is insecure and HTTPS failed, fallback to HTTP. // If registry is insecure and HTTPS failed, fallback to HTTP.
logrus.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) logrus.WithError(err).Debugf("error from registry %q marked as insecure - insecurely falling back to HTTP", endpoint)
endpoint.URL.Scheme = "http" endpoint.URL.Scheme = "http"
var err2 error var err2 error
@ -84,14 +84,9 @@ func validateEndpoint(endpoint *v1Endpoint) error {
// trimV1Address trims the version off the address and returns the // trimV1Address trims the version off the address and returns the
// trimmed address or an error if there is a non-V1 version. // trimmed address or an error if there is a non-V1 version.
func trimV1Address(address string) (string, error) { func trimV1Address(address string) (string, error) {
var (
chunks []string
apiVersionStr string
)
address = strings.TrimSuffix(address, "/") address = strings.TrimSuffix(address, "/")
chunks = strings.Split(address, "/") chunks := strings.Split(address, "/")
apiVersionStr = chunks[len(chunks)-1] apiVersionStr := chunks[len(chunks)-1]
if apiVersionStr == "v1" { if apiVersionStr == "v1" {
return strings.Join(chunks[:len(chunks)-1], "/"), nil return strings.Join(chunks[:len(chunks)-1], "/"), nil
} }
@ -168,7 +163,7 @@ func (e *v1Endpoint) ping() (v1PingResult, error) {
Standalone: true, Standalone: true,
} }
if err := json.Unmarshal(jsonString, &info); err != nil { if err := json.Unmarshal(jsonString, &info); err != nil {
logrus.Debugf("Error unmarshaling the _ping v1PingResult: %s", err) logrus.WithError(err).Debug("error unmarshaling _ping response")
// don't stop here. Just assume sane defaults // don't stop here. Just assume sane defaults
} }
if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" {

View File

@ -174,8 +174,11 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
if err != nil { if err != nil {
return nil, err return nil, err
} }
if index.Official {
// If pull "library/foo", it's stored locally under "foo"
remoteName = strings.TrimPrefix(remoteName, "library/")
}
// *TODO: Search multiple indexes.
endpoint, err := newV1Endpoint(index, userAgent, headers) endpoint, err := newV1Endpoint(index, userAgent, headers)
if err != nil { if err != nil {
return nil, err return nil, err
@ -195,7 +198,7 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) v2Client, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes)
if err != nil { if err != nil {
if fErr, ok := err.(fallbackError); ok { if fErr, ok := err.(fallbackError); ok {
logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err) logrus.WithError(fErr.err).Error("cannot use identity token for search, v2 auth not supported")
} else { } else {
return nil, err return nil, err
} }
@ -217,13 +220,7 @@ func (s *defaultService) Search(ctx context.Context, term string, limit int, aut
} }
} }
r := newSession(client, endpoint) return newSession(client, endpoint).searchRepositories(remoteName, limit)
if index.Official {
// If pull "library/foo", it's stored locally under "foo"
remoteName = strings.TrimPrefix(remoteName, "library/")
}
return r.searchRepositories(remoteName, limit)
} }
// ResolveRepository splits a repository name into its components // ResolveRepository splits a repository name into its components