Add unit tests for singleAuthHeader

Also rename it to parseSingleAuthHeader

Should not change behavior.

Signed-off-by: Miloslav Trmač <mitr@redhat.com>
This commit is contained in:
Miloslav Trmač
2021-09-11 20:24:07 +02:00
parent b162d8868c
commit ff003928b2
2 changed files with 40 additions and 3 deletions

View File

@ -115,7 +115,7 @@ func getAuthCredentials(r *http.Request) (*types.DockerAuthConfig, string, error
}
// Fallback to looking for a single-auth header (i.e., one config).
authConfigs, err = singleAuthHeader(r)
authConfigs, err = parseSingleAuthHeader(r)
if err != nil {
return nil, "", err
}
@ -309,9 +309,9 @@ func imageAuthToDockerAuth(authConfig types.DockerAuthConfig) dockerAPITypes.Aut
}
}
// singleAuthHeader extracts a DockerAuthConfig from the request's header.
// parseSingleAuthHeader extracts a DockerAuthConfig from the request's header.
// The header content is a single DockerAuthConfig.
func singleAuthHeader(r *http.Request) (map[string]types.DockerAuthConfig, error) {
func parseSingleAuthHeader(r *http.Request) (map[string]types.DockerAuthConfig, error) {
authHeader := r.Header.Get(string(XRegistryAuthHeader))
authConfig := dockerAPITypes.AuthConfig{}
// Accept "null" and handle it as empty value for compatibility reason with Docker.

View File

@ -68,6 +68,43 @@ func TestAuthConfigsToAuthFile(t *testing.T) {
}
}
func TestParseSingleAuthHeader(t *testing.T) {
for _, tc := range []struct {
input string
shouldErr bool
expected map[string]types.DockerAuthConfig
}{
{
input: "", // An empty (or missing) header
expected: map[string]types.DockerAuthConfig{"0": {}},
},
{
input: "null",
expected: map[string]types.DockerAuthConfig{"0": {}},
},
// Invalid JSON
{input: "@", shouldErr: true},
// Success
{
input: base64.URLEncoding.EncodeToString([]byte(`{"username":"u1","password":"p1"}`)),
expected: map[string]types.DockerAuthConfig{
"0": {Username: "u1", Password: "p1"},
},
},
} {
req, err := http.NewRequest(http.MethodPost, "/", nil)
require.NoError(t, err, tc.input)
req.Header.Set(XRegistryAuthHeader.String(), tc.input)
res, err := parseSingleAuthHeader(req)
if tc.shouldErr {
assert.Error(t, err, tc.input)
} else {
require.NoError(t, err, tc.input)
assert.Equal(t, tc.expected, res, tc.input)
}
}
}
func TestParseMultiAuthHeader(t *testing.T) {
for _, tc := range []struct {
input string