Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions middleware/basic_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package middleware

import (
"crypto/subtle"
"fmt"
"net/http"
"strconv"
)

// BasicAuth implements a simple middleware handler for adding basic http auth to a route.
Expand All @@ -28,6 +28,6 @@ func BasicAuth(realm string, creds map[string]string) func(next http.Handler) ht
}

func basicAuthFailed(w http.ResponseWriter, realm string) {
w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
w.Header().Add("WWW-Authenticate", "Basic realm="+strconv.Quote(realm))
w.WriteHeader(http.StatusUnauthorized)
}
27 changes: 27 additions & 0 deletions middleware/basic_auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package middleware

import (
"net/http"
"net/http/httptest"
"testing"
)

func TestBasicAuthEscapesRealm(t *testing.T) {
realm := `admin"ops\zone`
h := BasicAuth(realm, map[string]string{"user": "pass"})(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {},
))

rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
h.ServeHTTP(rr, req)

if rr.Code != http.StatusUnauthorized {
t.Fatalf("status code = %d, want %d", rr.Code, http.StatusUnauthorized)
}

const want = `Basic realm="admin\"ops\\zone"`
if got := rr.Header().Get("WWW-Authenticate"); got != want {
t.Fatalf("WWW-Authenticate = %q, want %q", got, want)
}
}