Skip to content

Commit 49306c6

Browse files
authored
Merge pull request moby#50500 from thaJeztah/registry_fix_linting
registry: fix assorted linting issues
2 parents 6cea771 + 6ed00d5 commit 49306c6

File tree

8 files changed

+66
-51
lines changed

8 files changed

+66
-51
lines changed

registry/auth.go

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,9 +40,9 @@ type staticCredentialStore struct {
4040

4141
// NewStaticCredentialStore returns a credential store
4242
// which always returns the same credential values.
43-
func NewStaticCredentialStore(auth *registry.AuthConfig) auth.CredentialStore {
43+
func NewStaticCredentialStore(ac *registry.AuthConfig) auth.CredentialStore {
4444
return staticCredentialStore{
45-
auth: auth,
45+
auth: ac,
4646
}
4747
}
4848

@@ -60,7 +60,7 @@ func (scs staticCredentialStore) RefreshToken(*url.URL, string) string {
6060
return scs.auth.IdentityToken
6161
}
6262

63-
func (scs staticCredentialStore) SetRefreshToken(*url.URL, string, string) {
63+
func (staticCredentialStore) SetRefreshToken(*url.URL, string, string) {
6464
}
6565

6666
// loginV2 tries to login to the v2 registry server. The given registry
@@ -131,12 +131,15 @@ func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifi
131131
// to just its hostname. It is used to match credentials, which may be either
132132
// stored as hostname or as hostname including scheme (in legacy configuration
133133
// files).
134-
func ConvertToHostname(url string) string {
135-
stripped := url
136-
if strings.HasPrefix(stripped, "http://") {
137-
stripped = strings.TrimPrefix(stripped, "http://")
138-
} else if strings.HasPrefix(stripped, "https://") {
139-
stripped = strings.TrimPrefix(stripped, "https://")
134+
func ConvertToHostname(maybeURL string) string {
135+
stripped := maybeURL
136+
if scheme, remainder, ok := strings.Cut(stripped, "://"); ok {
137+
switch scheme {
138+
case "http", "https":
139+
stripped = remainder
140+
default:
141+
// unknown, or no scheme; doing nothing for now, as we never did.
142+
}
140143
}
141144
stripped, _, _ = strings.Cut(stripped, "/")
142145
return stripped
@@ -175,9 +178,9 @@ func (err PingResponseError) Error() string {
175178
// PingV2Registry attempts to ping a v2 registry and on success return a
176179
// challenge manager for the supported authentication types.
177180
// If a response is received but cannot be interpreted, a PingResponseError will be returned.
178-
func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, error) {
181+
func PingV2Registry(endpoint *url.URL, authTransport http.RoundTripper) (challenge.Manager, error) {
179182
pingClient := &http.Client{
180-
Transport: transport,
183+
Transport: authTransport,
181184
Timeout: 15 * time.Second,
182185
}
183186
endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/"

registry/config.go

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -168,14 +168,15 @@ skip:
168168
if _, err := ValidateIndexName(r); err != nil {
169169
return err
170170
}
171-
if strings.HasPrefix(strings.ToLower(r), "http://") {
172-
log.G(context.TODO()).Warnf("insecure registry %s should not contain 'http://' and 'http://' has been removed from the insecure registry config", r)
173-
r = r[7:]
174-
} else if strings.HasPrefix(strings.ToLower(r), "https://") {
175-
log.G(context.TODO()).Warnf("insecure registry %s should not contain 'https://' and 'https://' has been removed from the insecure registry config", r)
176-
r = r[8:]
177-
} else if hasScheme(r) {
178-
return invalidParamf("insecure registry %s should not contain '://'", r)
171+
if scheme, host, ok := strings.Cut(r, "://"); ok {
172+
switch strings.ToLower(scheme) {
173+
case "http", "https":
174+
log.G(context.TODO()).Warnf("insecure registry %[1]s should not contain '%[2]s' and '%[2]ss' has been removed from the insecure registry config", r, scheme)
175+
r = host
176+
default:
177+
// unsupported scheme
178+
return invalidParamf("insecure registry %s should not contain '://'", r)
179+
}
179180
}
180181
// Check if CIDR was passed to --insecure-registry
181182
_, ipnet, err := net.ParseCIDR(r)
@@ -240,18 +241,18 @@ func (config *serviceConfig) isSecureIndex(indexName string) bool {
240241
// for mocking in unit tests.
241242
var lookupIP = net.LookupIP
242243

243-
// isCIDRMatch returns true if URLHost matches an element of cidrs. URLHost is a URL.Host (`host:port` or `host`)
244+
// isCIDRMatch returns true if urlHost matches an element of cidrs. urlHost is a URL.Host ("host:port" or "host")
244245
// where the `host` part can be either a domain name or an IP address. If it is a domain name, then it will be
245246
// resolved to IP addresses for matching. If resolution fails, false is returned.
246-
func isCIDRMatch(cidrs []*registry.NetIPNet, URLHost string) bool {
247+
func isCIDRMatch(cidrs []*registry.NetIPNet, urlHost string) bool {
247248
if len(cidrs) == 0 {
248249
return false
249250
}
250251

251-
host, _, err := net.SplitHostPort(URLHost)
252+
host, _, err := net.SplitHostPort(urlHost)
252253
if err != nil {
253-
// Assume URLHost is a host without port and go on.
254-
host = URLHost
254+
// Assume urlHost is a host without port and go on.
255+
host = urlHost
255256
}
256257

257258
var addresses []net.IP

registry/errors.go

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,13 @@ import (
88
)
99

1010
func translateV2AuthError(err error) error {
11-
switch e := err.(type) {
12-
case *url.Error:
13-
switch e2 := e.Err.(type) {
14-
case errcode.Error:
15-
switch e2.Code {
16-
case errcode.ErrorCodeUnauthorized:
17-
return unauthorizedErr{err}
18-
}
11+
var e *url.Error
12+
if errors.As(err, &e) {
13+
var e2 errcode.Error
14+
if errors.As(e, &e2) && errors.Is(e2.Code, errcode.ErrorCodeUnauthorized) {
15+
return unauthorizedErr{err}
1916
}
2017
}
21-
2218
return err
2319
}
2420

registry/registry_mock_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,4 +116,5 @@ func TestPing(t *testing.T) {
116116
}
117117
assert.Equal(t, res.StatusCode, http.StatusOK, "")
118118
assert.Equal(t, res.Header.Get("Server"), "docker-tests/mock")
119+
_ = res.Body.Close()
119120
}

registry/registry_test.go

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -363,15 +363,6 @@ func TestNewIndexInfo(t *testing.T) {
363363
},
364364
}
365365

366-
testIndexInfo := func(t *testing.T, config *serviceConfig, expectedIndexInfos map[string]*registry.IndexInfo) {
367-
for indexName, expected := range expectedIndexInfos {
368-
t.Run(indexName, func(t *testing.T) {
369-
actual := newIndexInfo(config, indexName)
370-
assert.Check(t, is.DeepEqual(actual, expected))
371-
})
372-
}
373-
}
374-
375366
expectedIndexInfos := map[string]*registry.IndexInfo{
376367
IndexName: {
377368
Name: IndexName,
@@ -399,7 +390,12 @@ func TestNewIndexInfo(t *testing.T) {
399390
},
400391
}
401392
t.Run("no mirrors", func(t *testing.T) {
402-
testIndexInfo(t, emptyServiceConfig, expectedIndexInfos)
393+
for indexName, expected := range expectedIndexInfos {
394+
t.Run(indexName, func(t *testing.T) {
395+
actual := newIndexInfo(emptyServiceConfig, indexName)
396+
assert.Check(t, is.DeepEqual(actual, expected))
397+
})
398+
}
403399
})
404400

405401
expectedIndexInfos = map[string]*registry.IndexInfo{
@@ -494,7 +490,12 @@ func TestNewIndexInfo(t *testing.T) {
494490
InsecureRegistries: []string{"example.com"},
495491
})
496492
assert.NilError(t, err)
497-
testIndexInfo(t, config, expectedIndexInfos)
493+
for indexName, expected := range expectedIndexInfos {
494+
t.Run(indexName, func(t *testing.T) {
495+
actual := newIndexInfo(config, indexName)
496+
assert.Check(t, is.DeepEqual(actual, expected))
497+
})
498+
}
498499
})
499500

500501
expectedIndexInfos = map[string]*registry.IndexInfo{
@@ -546,7 +547,12 @@ func TestNewIndexInfo(t *testing.T) {
546547
InsecureRegistries: []string{"42.42.0.0/16"},
547548
})
548549
assert.NilError(t, err)
549-
testIndexInfo(t, config, expectedIndexInfos)
550+
for indexName, expected := range expectedIndexInfos {
551+
t.Run(indexName, func(t *testing.T) {
552+
actual := newIndexInfo(config, indexName)
553+
assert.Check(t, is.DeepEqual(actual, expected))
554+
})
555+
}
550556
})
551557
}
552558

registry/search_endpoint_v1.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"crypto/tls"
66
"encoding/json"
77
"errors"
8+
"fmt"
89
"net/http"
910
"net/url"
1011
"strings"
@@ -58,7 +59,12 @@ func newV1Endpoint(ctx context.Context, index *registry.IndexInfo, headers http.
5859
if endpoint.IsSecure {
5960
// If registry is secure and HTTPS failed, show user the error and tell them about `--insecure-registry`
6061
// in case that's what they need. DO NOT accept unknown CA certificates, and DO NOT fall back to HTTP.
61-
return nil, invalidParamf("invalid registry endpoint %s: %v. If this private registry supports only HTTP or HTTPS with an unknown CA certificate, please add `--insecure-registry %s` to the daemon's arguments. In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; simply place the CA certificate at /etc/docker/certs.d/%s/ca.crt", endpoint, err, endpoint.URL.Host, endpoint.URL.Host)
62+
hint := fmt.Sprintf(
63+
". If this private registry supports only HTTP or HTTPS with an unknown CA certificate, add `--insecure-registry %[1]s` to the daemon's arguments. "+
64+
"In the case of HTTPS, if you have access to the registry's CA certificate, no need for the flag; place the CA certificate at /etc/docker/certs.d/%[1]s/ca.crt",
65+
endpoint.URL.Host,
66+
)
67+
return nil, invalidParamf("invalid registry endpoint %s: %v%s", endpoint, err, hint)
6268
}
6369

6470
// registry is insecure and HTTPS failed, fallback to HTTP.
@@ -163,9 +169,9 @@ func (e *v1Endpoint) ping(ctx context.Context) (v1PingResult, error) {
163169

164170
// httpClient returns an HTTP client structure which uses the given transport
165171
// and contains the necessary headers for redirected requests
166-
func httpClient(transport http.RoundTripper) *http.Client {
172+
func httpClient(tr http.RoundTripper) *http.Client {
167173
return &http.Client{
168-
Transport: transport,
174+
Transport: tr,
169175
CheckRedirect: addRequiredHeadersToRedirectedRequests,
170176
}
171177
}

registry/search_session.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"net/http"
1111
"net/http/cookiejar"
1212
"net/url"
13+
"strconv"
1314
"strings"
1415
"sync"
1516

@@ -219,7 +220,7 @@ func (r *session) searchRepositories(ctx context.Context, term string, limit int
219220
if limit < 1 || limit > 100 {
220221
return nil, invalidParamf("limit %d is outside the range of [1, 100]", limit)
221222
}
222-
u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(fmt.Sprintf("%d", limit))
223+
u := r.indexEndpoint.String() + "search?q=" + url.QueryEscape(term) + "&n=" + url.QueryEscape(strconv.Itoa(limit))
223224
log.G(ctx).WithField("url", u).Debug("searchRepositories")
224225

225226
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, http.NoBody)
@@ -236,7 +237,7 @@ func (r *session) searchRepositories(ctx context.Context, term string, limit int
236237
if res.StatusCode != http.StatusOK {
237238
// TODO(thaJeztah): return upstream response body for errors (see https://github.com/moby/moby/issues/27286).
238239
// TODO(thaJeztah): handle other status-codes to return correct error-type
239-
return nil, errUnknown{fmt.Errorf("Unexpected status code %d", res.StatusCode)}
240+
return nil, errUnknown{fmt.Errorf("unexpected status code %d", res.StatusCode)}
240241
}
241242
result := &registry.SearchResults{}
242243
err = json.NewDecoder(res.Body).Decode(result)

registry/search_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import (
1616
)
1717

1818
func spawnTestRegistrySession(t *testing.T) *session {
19+
t.Helper()
1920
authConfig := &registry.AuthConfig{}
2021
endpoint, err := newV1Endpoint(context.Background(), makeIndex("/v1/"), nil)
2122
if err != nil {
@@ -89,7 +90,7 @@ func TestSearchErrors(t *testing.T) {
8990
expectedError string
9091
}{
9192
{
92-
expectedError: "Unexpected status code 500",
93+
expectedError: "unexpected status code 500",
9394
shouldReturnError: true,
9495
},
9596
{

0 commit comments

Comments
 (0)