Skip to content

Commit

Permalink
prometheus#71 Skip basic auth for OPTIONS http method
Browse files Browse the repository at this point in the history
The OPTIONS needed for CORS requests

Signed-off-by: Sergey Ponomarev <stokito@gmail.com>
  • Loading branch information
stokito committed Jan 28, 2022
1 parent 48868f5 commit f041fc8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
3 changes: 2 additions & 1 deletion web/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,8 @@ func (u *webHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(k, v)
}

if len(c.Users) == 0 {
// If OPTIONS method or none users configured then skip auth check
if r.Method == http.MethodOptions || len(c.Users) == 0 {
u.handler.ServeHTTP(w, r)
return
}
Expand Down
44 changes: 44 additions & 0 deletions web/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,3 +172,47 @@ func TestHTTPHeaders(t *testing.T) {
}
}
}

// TestBasicAuthIsNotNeededForMethodOptions validates that OPTIONS method is always allowed
func TestBasicAuthIsNotNeededForMethodOptions(t *testing.T) {
server := &http.Server{
Addr: port,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Origin", "https://example.com:8080")
w.Header().Set("Access-Control-Expose-Headers", "Date")
w.Header().Set("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
w.Header().Set("Access-Control-Allow-Headers", "Accept,Authorization,Date,Content-Type,Origin")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.WriteHeader(http.StatusNoContent)
}
w.WriteHeader(http.StatusMethodNotAllowed)
}),
}

done := make(chan struct{})
t.Cleanup(func() {
if err := server.Shutdown(context.Background()); err != nil {
t.Fatal(err)
}
<-done
})

go func() {
ListenAndServe(server, "testdata/web_config_users_noTLS.good.yml", testlogger)
close(done)
}()

client := &http.Client{}
req, err := http.NewRequest("OPTIONS", "http://localhost"+port, nil)
if err != nil {
t.Fatal(err)
}
r, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
if r.StatusCode != 204 {
t.Fatalf("bad return code, expected %d, got %d", 204, r.StatusCode)
}
}

0 comments on commit f041fc8

Please sign in to comment.