2014-12-18 21:30:19 +01:00
|
|
|
package silly
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2015-08-19 23:24:31 +02:00
|
|
|
"github.com/docker/distribution/context"
|
2015-02-11 02:34:04 +01:00
|
|
|
"github.com/docker/distribution/registry/auth"
|
2014-12-18 21:30:19 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func TestSillyAccessController(t *testing.T) {
|
|
|
|
ac := &accessController{
|
|
|
|
realm: "test-realm",
|
|
|
|
service: "test-service",
|
|
|
|
}
|
|
|
|
|
|
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
2016-10-06 02:47:12 +02:00
|
|
|
ctx := context.WithRequest(context.Background(), r)
|
2015-02-04 02:59:24 +01:00
|
|
|
authCtx, err := ac.Authorized(ctx)
|
|
|
|
if err != nil {
|
2014-12-18 21:30:19 +01:00
|
|
|
switch err := err.(type) {
|
|
|
|
case auth.Challenge:
|
2015-07-24 04:39:56 +02:00
|
|
|
err.SetHeaders(w)
|
2015-06-17 03:57:47 +02:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2014-12-18 21:30:19 +01:00
|
|
|
return
|
|
|
|
default:
|
|
|
|
t.Fatalf("unexpected error authorizing request: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-01-29 02:02:09 +01:00
|
|
|
userInfo, ok := authCtx.Value(auth.UserKey).(auth.UserInfo)
|
2015-02-04 02:59:24 +01:00
|
|
|
if !ok {
|
|
|
|
t.Fatal("silly accessController did not set auth.user context")
|
|
|
|
}
|
|
|
|
|
|
|
|
if userInfo.Name != "silly" {
|
|
|
|
t.Fatalf("expected user name %q, got %q", "silly", userInfo.Name)
|
|
|
|
}
|
|
|
|
|
2014-12-18 21:30:19 +01:00
|
|
|
w.WriteHeader(http.StatusNoContent)
|
|
|
|
}))
|
|
|
|
|
|
|
|
resp, err := http.Get(server.URL)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("unexpected error during GET: %v", err)
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
// Request should not be authorized
|
|
|
|
if resp.StatusCode != http.StatusUnauthorized {
|
|
|
|
t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusUnauthorized)
|
|
|
|
}
|
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", server.URL, nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("unexpected error creating new request: %v", err)
|
|
|
|
}
|
|
|
|
req.Header.Set("Authorization", "seriously, anything")
|
|
|
|
|
|
|
|
resp, err = http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("unexpected error during GET: %v", err)
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
// Request should not be authorized
|
|
|
|
if resp.StatusCode != http.StatusNoContent {
|
|
|
|
t.Fatalf("unexpected response status: %v != %v", resp.StatusCode, http.StatusNoContent)
|
|
|
|
}
|
|
|
|
}
|