2014-12-18 12:30:19 -08:00
|
|
|
package silly
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
2020-08-24 13:18:39 +02:00
|
|
|
"github.com/distribution/distribution/v3/registry/auth"
|
2014-12-18 12:30:19 -08: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) {
|
2023-10-24 16:41:54 -04:00
|
|
|
grant, err := ac.Authorized(r)
|
2015-02-03 17:59:24 -08:00
|
|
|
if err != nil {
|
2014-12-18 12:30:19 -08:00
|
|
|
switch err := err.(type) {
|
|
|
|
case auth.Challenge:
|
2018-09-20 14:53:34 -07:00
|
|
|
err.SetHeaders(r, w)
|
2015-06-16 18:57:47 -07:00
|
|
|
w.WriteHeader(http.StatusUnauthorized)
|
2014-12-18 12:30:19 -08:00
|
|
|
return
|
|
|
|
default:
|
|
|
|
t.Fatalf("unexpected error authorizing request: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-24 16:41:54 -04:00
|
|
|
if grant == nil {
|
|
|
|
t.Fatal("silly accessController did not return auth grant")
|
2015-02-03 17:59:24 -08:00
|
|
|
}
|
|
|
|
|
2023-10-24 16:41:54 -04:00
|
|
|
if grant.User.Name != "silly" {
|
|
|
|
t.Fatalf("expected user name %q, got %q", "silly", grant.User.Name)
|
2015-02-03 17:59:24 -08:00
|
|
|
}
|
|
|
|
|
2014-12-18 12:30:19 -08: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)
|
|
|
|
}
|
|
|
|
|
2022-11-02 23:31:23 +01:00
|
|
|
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
|
2014-12-18 12:30:19 -08:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
}
|