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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
|
package utils
import (
"bytes"
"errors"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/docker/distribution/registry/api/errcode"
"github.com/stretchr/testify/require"
"golang.org/x/net/context"
"github.com/theupdateframework/notary/tuf/signed"
)
func MockContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return nil
}
func MockBetterErrorHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
return errcode.ErrorCodeUnknown.WithDetail("Test Error")
}
func TestRootHandlerFactory(t *testing.T) {
hand := RootHandlerFactory(context.Background(), nil, &signed.Ed25519{})
handler := hand(MockContextHandler)
if _, ok := interface{}(handler).(http.Handler); !ok {
t.Fatalf("A rootHandler must implement the http.Handler interface")
}
ts := httptest.NewServer(handler)
defer ts.Close()
res, err := http.Get(ts.URL)
require.NoError(t, err)
require.Equal(t, http.StatusOK, res.StatusCode)
}
func TestRootHandlerError(t *testing.T) {
hand := RootHandlerFactory(context.Background(), nil, &signed.Ed25519{})
handler := hand(MockBetterErrorHandler)
ts := httptest.NewServer(handler)
defer ts.Close()
res, err := http.Get(ts.URL)
require.NoError(t, err)
require.Equal(t, http.StatusInternalServerError, res.StatusCode)
content, err := ioutil.ReadAll(res.Body)
require.NoError(t, err)
contentStr := strings.Trim(string(content), "\r\n\t ")
if strings.TrimSpace(contentStr) != `{"errors":[{"code":"UNKNOWN","message":"unknown error","detail":"Test Error"}]}` {
t.Fatalf("Error Body Incorrect: `%s`", content)
}
}
// If no CacheControlConfig is passed, wrapping the handler just returns the handler
func TestWrapWithCacheHeaderNilCacheControlConfig(t *testing.T) {
mux := http.NewServeMux()
wrapped := WrapWithCacheHandler(nil, mux)
require.Equal(t, mux, wrapped)
}
// If the wrapped handler returns a non-200, no matter which CacheControlConfig is
// used, the Cache-Control header not set.
func TestWrapWithCacheHeaderNon200Response(t *testing.T) {
mux := http.NewServeMux()
configs := []CacheControlConfig{NewCacheControlConfig(10, true), NewCacheControlConfig(0, true)}
for _, conf := range configs {
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(conf, mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "", rw.HeaderMap.Get("Cache-Control"))
require.Equal(t, "", rw.HeaderMap.Get("Last-Modified"))
require.Equal(t, "", rw.HeaderMap.Get("Pragma"))
}
}
// If the wrapped handler writes no cache headers whatsoever, and a PublicCacheControl
// is used, the Cache-Control header is set with the given maxAge and re-validate value.
// The Last-Modified header is also set to the beginning of (computer) time. If a
// Pragma header is written is deleted
func TestWrapWithCacheHeaderPublicCacheControlNoCacheHeaders(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("hello!"))
})
mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Pragma", "no-cache")
w.Write([]byte("hello!"))
})
for _, path := range []string{"/", "/a"} {
req := &http.Request{URL: &url.URL{Path: path}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
// must-revalidate is set if revalidate is set to true, and not if revalidate is set to false
for _, revalidate := range []bool{true, false} {
wrapped := WrapWithCacheHandler(NewCacheControlConfig(10, revalidate), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
cacheControl := "public, max-age=10, s-maxage=10"
if revalidate {
cacheControl = cacheControl + ", must-revalidate"
}
require.Equal(t, cacheControl, rw.HeaderMap.Get("Cache-Control"))
lastModified, err := time.Parse(time.RFC1123, rw.HeaderMap.Get("Last-Modified"))
require.NoError(t, err)
require.True(t, lastModified.Equal(time.Time{}))
require.Equal(t, "", rw.HeaderMap.Get("Pragma"))
}
}
}
// If the wrapped handler writes a last modified header, and a PublicCacheControl
// is used, the Cache-Control header is set with the given maxAge and re-validate value.
// The Last-Modified header is not replaced. The Pragma header is deleted though.
func TestWrapWithCacheHeaderPublicCacheControlLastModifiedHeader(t *testing.T) {
now := time.Now()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
SetLastModifiedHeader(w.Header(), now)
w.Header().Set("Pragma", "no-cache")
w.Write([]byte("hello!"))
})
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(NewCacheControlConfig(10, true), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "public, max-age=10, s-maxage=10, must-revalidate", rw.HeaderMap.Get("Cache-Control"))
lastModified, err := time.Parse(time.RFC1123, rw.HeaderMap.Get("Last-Modified"))
require.NoError(t, err)
// RFC1123 does not include nanoseconds
nowToNearestSecond := now.Add(time.Duration(-1 * now.Nanosecond()))
require.True(t, lastModified.Equal(nowToNearestSecond))
require.Equal(t, "", rw.HeaderMap.Get("Pragma"))
}
// If the wrapped handler writes a Cache-Control header, even if the last modified
// header is not written, then the Cache-Control header is not written, nor is a
// Last-Modified header written. The Pragma header is not deleted.
func TestWrapWithCacheHeaderPublicCacheControlCacheControlHeader(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "some invalid cache control value")
w.Header().Set("Pragma", "invalid value")
w.Write([]byte("hello!"))
})
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(NewCacheControlConfig(10, true), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "some invalid cache control value", rw.HeaderMap.Get("Cache-Control"))
require.Equal(t, "", rw.HeaderMap.Get("Last-Modified"))
require.Equal(t, "invalid value", rw.HeaderMap.Get("Pragma"))
}
// If the wrapped handler writes no cache headers whatsoever, and NoCacheControl
// is used, the Cache-Control and Pragma headers are set with no-cache.
func TestWrapWithCacheHeaderNoCacheControlNoCacheHeaders(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Pragma", "invalid value")
w.Write([]byte("hello!"))
})
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(NewCacheControlConfig(0, false), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "max-age=0, no-cache, no-store", rw.HeaderMap.Get("Cache-Control"))
require.Equal(t, "", rw.HeaderMap.Get("Last-Modified"))
require.Equal(t, "no-cache", rw.HeaderMap.Get("Pragma"))
}
// If the wrapped handler writes a last modified header, and NoCacheControl
// is used, the Cache-Control and Pragma headers are set with no-cache without
// messing with the Last-Modified header.
func TestWrapWithCacheHeaderNoCacheControlLastModifiedHeader(t *testing.T) {
now := time.Now()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
SetLastModifiedHeader(w.Header(), now)
w.Write([]byte("hello!"))
})
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(NewCacheControlConfig(0, true), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "max-age=0, no-cache, no-store", rw.HeaderMap.Get("Cache-Control"))
require.Equal(t, "no-cache", rw.HeaderMap.Get("Pragma"))
lastModified, err := time.Parse(time.RFC1123, rw.HeaderMap.Get("Last-Modified"))
require.NoError(t, err)
// RFC1123 does not include nanoseconds
nowToNearestSecond := now.Add(time.Duration(-1 * now.Nanosecond()))
require.True(t, lastModified.Equal(nowToNearestSecond))
}
// If the wrapped handler writes a Cache-Control header, even if the last modified
// header is not written, then the Cache-Control header is not written, nor is a
// Pragma added. The Last-Modified header is untouched.
func TestWrapWithCacheHeaderNoCacheControlCacheControlHeader(t *testing.T) {
now := time.Now()
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "some invalid cache control value")
SetLastModifiedHeader(w.Header(), now)
w.Write([]byte("hello!"))
})
req := &http.Request{URL: &url.URL{Path: "/"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))}
wrapped := WrapWithCacheHandler(NewCacheControlConfig(0, true), mux)
require.NotEqual(t, mux, wrapped)
rw := httptest.NewRecorder()
wrapped.ServeHTTP(rw, req)
require.Equal(t, "some invalid cache control value", rw.HeaderMap.Get("Cache-Control"))
require.Equal(t, "", rw.HeaderMap.Get("Pragma"))
lastModified, err := time.Parse(time.RFC1123, rw.HeaderMap.Get("Last-Modified"))
require.NoError(t, err)
// RFC1123 does not include nanoseconds
nowToNearestSecond := now.Add(time.Duration(-1 * now.Nanosecond()))
require.True(t, lastModified.Equal(nowToNearestSecond))
}
func TestBuildCatalogRecord(t *testing.T) {
r := buildCatalogRecord()
require.Len(t, r, 1)
r0 := r[0]
require.Equal(t, "registry", r0.Resource.Type)
require.Equal(t, "catalog", r0.Resource.Name)
require.Equal(t, "*", r0.Action)
}
func TestDoAuthNonWildcardImage(t *testing.T) {
// success
ac := TestingAccessController{}
r := rootHandler{
auth: ac,
}
rec := httptest.NewRecorder()
_, err := r.doAuth(
context.Background(),
"docker.io/library/alpine",
rec,
&http.Request{URL: &url.URL{Path: "library/alpine"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.NoError(t, err)
require.Equal(t, 200, rec.Code)
// challenge error
e := TestingAuthChallenge{}
ac = TestingAccessController{
Err: &e,
}
r = rootHandler{
auth: ac,
}
rec = httptest.NewRecorder()
_, err = r.doAuth(
context.Background(),
"docker.io/library/alpine",
rec,
&http.Request{URL: &url.URL{Path: "library/alpine"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.Error(t, err)
require.True(t, e.SetHeadersCalled)
require.Equal(t, http.StatusUnauthorized, rec.Code)
// non-challenge error
ac = TestingAccessController{
Err: errors.New("Non challenge error"),
}
r = rootHandler{
auth: ac,
}
rec = httptest.NewRecorder()
_, err = r.doAuth(
context.Background(),
"docker.io/library/alpine",
rec,
&http.Request{URL: &url.URL{Path: "library/alpine"}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.Error(t, err)
require.Equal(t, http.StatusUnauthorized, rec.Code)
}
func TestDoAuthWildcardImage(t *testing.T) {
// success
ac := TestingAccessController{}
r := rootHandler{
auth: ac,
}
rec := httptest.NewRecorder()
_, err := r.doAuth(
context.Background(),
"",
rec,
&http.Request{URL: &url.URL{}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.NoError(t, err)
require.Equal(t, 200, rec.Code)
// challenge error
e := TestingAuthChallenge{}
ac = TestingAccessController{
Err: &e,
}
r = rootHandler{
auth: ac,
}
rec = httptest.NewRecorder()
_, err = r.doAuth(
context.Background(),
"",
rec,
&http.Request{URL: &url.URL{}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.Error(t, err)
require.True(t, e.SetHeadersCalled)
require.Equal(t, http.StatusUnauthorized, rec.Code)
// non-challenge error
ac = TestingAccessController{
Err: errors.New("Non challenge error"),
}
r = rootHandler{
auth: ac,
}
rec = httptest.NewRecorder()
_, err = r.doAuth(
context.Background(),
"",
rec,
&http.Request{URL: &url.URL{}, Body: ioutil.NopCloser(bytes.NewBuffer(nil))},
)
require.Error(t, err)
require.Equal(t, http.StatusUnauthorized, rec.Code)
}
|