fup: allow Fup-Token header for carrying auth credentials

This commit is contained in:
Luke Granger-Brown 2021-03-23 00:58:06 +00:00
parent dbd711ded8
commit 8271714a18
2 changed files with 27 additions and 7 deletions

View file

@ -8,6 +8,18 @@ import (
"github.com/gorilla/mux" "github.com/gorilla/mux"
) )
func tokenFromRequest(r *http.Request) (token string, ok bool) {
// Check for a Fup-Token header.
v := r.Header.Get("Fup-Token")
if v != "" {
return v, true
}
// Check for basic auth.
_, v, ok = r.BasicAuth()
return v, ok
}
func TokenAuthMiddleware(token, realm string) mux.MiddlewareFunc { func TokenAuthMiddleware(token, realm string) mux.MiddlewareFunc {
return func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler {
if token == "" { if token == "" {
@ -28,8 +40,7 @@ func TokenAuthMiddleware(token, realm string) mux.MiddlewareFunc {
http.Error(rw, s, http.StatusUnauthorized) http.Error(rw, s, http.StatusUnauthorized)
} }
// Check for basic auth, first. pw, ok := tokenFromRequest(r)
_, pw, ok := r.BasicAuth()
switch { switch {
case !ok: case !ok:
requestAuth("unparsable or no credentials") requestAuth("unparsable or no credentials")

View file

@ -25,11 +25,12 @@ func TestTokenAuthMiddleware(t *testing.T) {
t.Cleanup(s.Close) t.Cleanup(s.Close)
tcs := []struct { tcs := []struct {
name string name string
path string path string
username, password string password string
wantStatus int headerToken string
wantText string wantStatus int
wantText string
}{{ }{{
name: "root, no creds", name: "root, no creds",
path: "/", path: "/",
@ -46,6 +47,11 @@ func TestTokenAuthMiddleware(t *testing.T) {
path: "/", path: "/",
password: "token", password: "token",
wantStatus: http.StatusOK, wantStatus: http.StatusOK,
}, {
name: "root, with good creds as header",
path: "/",
headerToken: "token",
wantStatus: http.StatusOK,
}, { }, {
name: "raw", name: "raw",
path: "/raw/foo.txt", path: "/raw/foo.txt",
@ -89,6 +95,9 @@ func TestTokenAuthMiddleware(t *testing.T) {
if tc.password != "" { if tc.password != "" {
req.SetBasicAuth("", tc.password) req.SetBasicAuth("", tc.password)
} }
if tc.headerToken != "" {
req.Header.Set("Fup-Token", tc.headerToken)
}
resp, err := s.Client().Do(req) resp, err := s.Client().Do(req)
if err != nil { if err != nil {