File: distribution_error_test.go

package info (click to toggle)
golang-github-containers-image 5.36.1-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 5,152 kB
  • sloc: sh: 267; makefile: 100
file content (234 lines) | stat: -rw-r--r-- 8,000 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
// Code below is taken from https://github.com/distribution/distribution/blob/a4d9db5a884b70be0c96dd6a7a9dbef4f2798c51/registry/client/errors.go
// Copyright 2022 github.com/distribution/distribution authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package docker

import (
	"bytes"
	"io"
	"net/http"
	"strings"
	"testing"

	"github.com/docker/distribution/registry/api/errcode"
)

func TestHandleErrorResponse401InvalidTokenChallenge(t *testing.T) {
	json := []byte(`{"errors":[{"code":"UNKNOWN","message":"some unknown error"}]}`)
	challenge := `Bearer realm="example.io",
error="invalid_token",
error_description="The access token expired"`
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
		Header: http.Header{
			http.CanonicalHeaderKey("WWW-Authenticate"): []string{challenge},
		},
	}
	err := handleErrorResponse(response)
	if err == nil {
		t.Fatal("Expected handleErrorResponse to return error, got nil.")
	}

	expectedMsg := "unauthorized: The access token expired"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse401InsufficientScopeChallenge(t *testing.T) {
	json := []byte(`{"errors":[{"code":"UNKNOWN","message":"some unknown error"}]}`)
	challenge := `Bearer realm="example.io",
error="insufficient_scope",
error_description="Insufficient permission"`
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
		Header: http.Header{
			http.CanonicalHeaderKey("WWW-Authenticate"): []string{challenge},
		},
	}
	err := handleErrorResponse(response)
	if err == nil {
		t.Fatal("Expected handleErrorResponse to return error, got nil.")
	}

	expectedMsg := "denied: Insufficient permission"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse401InvalidTokenWithoutDescription(t *testing.T) {
	json := []byte(`{"errors":[{"code":"UNKNOWN","message":"some unknown error"}]}`)
	challenge := `Bearer realm="example.io",
error="invalid_token"`
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
		Header: http.Header{
			http.CanonicalHeaderKey("WWW-Authenticate"): []string{challenge},
		},
	}
	err := handleErrorResponse(response)
	if err == nil {
		t.Fatal("Expected handleErrorResponse to return error, got nil.")
	}

	expectedMsg := errcode.ErrorCodeUnauthorized.Message()
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse401UnexpectedChallenge(t *testing.T) {
	json := []byte(`{"errors":[{"code":"UNKNOWN","message":"some unknown error"}]}`)
	challenge := `Bearer realm="example.io",
error="invalid_request",
error_description="The request is missing a required parameter"`
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
		Header: http.Header{
			http.CanonicalHeaderKey("WWW-Authenticate"): []string{challenge},
		},
	}
	err := handleErrorResponse(response)
	if err == nil {
		t.Fatal("Expected handleErrorResponse to return error, got nil.")
	}

	expectedMsg := "unknown: some unknown error"
	if err.Error() != expectedMsg {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse403InsufficientScopeChallenge(t *testing.T) {
	json := []byte(`{"errors":[{"code":"UNKNOWN","message":"some unknown error"}]}`)
	challenge := `Bearer realm="example.io",
error="insufficient_scope",
error_description="Insufficient permission"`
	response := &http.Response{
		Status:     "403 Forbidden",
		StatusCode: 403,
		Body:       io.NopCloser(bytes.NewReader(json)),
		Header: http.Header{
			http.CanonicalHeaderKey("WWW-Authenticate"): []string{challenge},
		},
	}
	err := handleErrorResponse(response)
	if err == nil {
		t.Fatal("Expected handleErrorResponse to return error, got nil.")
	}

	expectedMsg := "unknown: some unknown error"
	if err.Error() != expectedMsg {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse401ValidBody(t *testing.T) {
	json := []byte("{\"errors\":[{\"code\":\"UNAUTHORIZED\",\"message\":\"action requires authentication\"}]}")
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
	}
	err := handleErrorResponse(response)

	expectedMsg := "unauthorized: action requires authentication"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponse401WithInvalidBody(t *testing.T) {
	json := []byte("{invalid json}")
	response := &http.Response{
		Status:     "401 Unauthorized",
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewReader(json)),
	}
	err := handleErrorResponse(response)

	expectedMsg := "unauthorized: authentication required"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponseExpectedStatusCode400ValidBody(t *testing.T) {
	json := []byte("{\"errors\":[{\"code\":\"DIGEST_INVALID\",\"message\":\"provided digest does not match\"}]}")
	response := &http.Response{
		Status:     "400 Bad Request",
		StatusCode: 400,
		Body:       io.NopCloser(bytes.NewReader(json)),
	}
	err := handleErrorResponse(response)

	expectedMsg := "digest invalid: provided digest does not match"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponseExpectedStatusCode404EmptyErrorSlice(t *testing.T) {
	json := []byte(`{"randomkey": "randomvalue"}`)
	response := &http.Response{
		Status:     "404 Not Found",
		StatusCode: 404,
		Body:       io.NopCloser(bytes.NewReader(json)),
	}
	err := handleErrorResponse(response)

	expectedMsg := `error parsing HTTP 404 response body: no error details found in HTTP response body: "{\"randomkey\": \"randomvalue\"}"`
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponseExpectedStatusCode404InvalidBody(t *testing.T) {
	json := []byte("{invalid json}")
	response := &http.Response{
		Status:     "404 Not Found",
		StatusCode: 404,
		Body:       io.NopCloser(bytes.NewReader(json)),
	}
	err := handleErrorResponse(response)

	expectedMsg := "error parsing HTTP 404 response body: invalid character 'i' looking for beginning of object key string: \"{invalid json}\""
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}

func TestHandleErrorResponseUnexpectedStatusCode501(t *testing.T) {
	response := &http.Response{
		Status:     "501 Not Implemented",
		StatusCode: 501,
		Body:       io.NopCloser(bytes.NewReader([]byte("{\"Error Encountered\" : \"Function not implemented.\"}"))),
	}
	err := handleErrorResponse(response)

	expectedMsg := "received unexpected HTTP status: 501 Not Implemented"
	if !strings.Contains(err.Error(), expectedMsg) {
		t.Errorf("Expected \"%s\", got: \"%s\"", expectedMsg, err.Error())
	}
}