package router import ( "net/http" "net/http/httptest" "testing" ) func TestTheAdminAPIAndProfilerWantTheTokenAndThePagesDoNot(t *testing.T) { ok := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(http.StatusOK) }) cases := []struct { pprof bool path, header string want int }{ {false, "/api/v1/models", "", http.StatusUnauthorized}, {false, "/api/v1/models", "Bearer wrong", http.StatusUnauthorized}, {false, "/api/v1/models", "Bearer s3cret-token-of-enough-length-000000", http.StatusOK}, {false, "/api/v1/replicas", "s3cret-token-of-enough-length-000000", http.StatusUnauthorized}, {false, "/debug/pprof/heap", "Bearer s3cret-token-of-enough-length-000000", http.StatusNotFound}, {true, "/debug/pprof/heap", "", http.StatusUnauthorized}, {true, "/debug/pprof/heap", "Bearer s3cret-token-of-enough-length-000000", http.StatusOK}, {false, "/", "", http.StatusOK}, {false, "/nodes/n1", "", http.StatusOK}, {false, "/metrics", "", http.StatusOK}, } for _, c := range cases { h := AdminAuth("s3cret-token-of-enough-length-000000", c.pprof, ok) r := httptest.NewRequest("GET", c.path, nil) if c.header != "" { r.Header.Set("Authorization", c.header) } w := httptest.NewRecorder() h.ServeHTTP(w, r) if w.Code != c.want { t.Errorf("pprof=%v %s %q: %d, want %d", c.pprof, c.path, c.header, w.Code, c.want) } } // No token configured is no access, not open access. w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/api/v1/models", nil) r.Header.Set("Authorization", "Bearer ") AdminAuth("", false, ok).ServeHTTP(w, r) if w.Code != http.StatusUnauthorized { t.Errorf("an empty token let a request in: %d", w.Code) } }