52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
package helpers
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"net/http"
|
||
|
|
"net/http/httptest"
|
||
|
|
"testing"
|
||
|
|
|
||
|
|
"tea.chunkbyte.com/kato/go-worm/lib/config"
|
||
|
|
)
|
||
|
|
|
||
|
|
func TestBasicAuth(t *testing.T) {
|
||
|
|
mux := http.NewServeMux()
|
||
|
|
mux.HandleFunc("/openapi", func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
w.WriteHeader(http.StatusOK)
|
||
|
|
})
|
||
|
|
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
|
||
|
|
w.WriteHeader(http.StatusOK)
|
||
|
|
})
|
||
|
|
h := BasicAuth(mux)
|
||
|
|
|
||
|
|
t.Run("openapi public", func(t *testing.T) {
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/openapi", nil)
|
||
|
|
rec := httptest.NewRecorder()
|
||
|
|
h.ServeHTTP(rec, req)
|
||
|
|
if rec.Code != http.StatusOK {
|
||
|
|
t.Fatalf("status = %d, want 200", rec.Code)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
t.Run("protected without creds", func(t *testing.T) {
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||
|
|
rec := httptest.NewRecorder()
|
||
|
|
h.ServeHTTP(rec, req)
|
||
|
|
if rec.Code != http.StatusUnauthorized {
|
||
|
|
t.Fatalf("status = %d, want 401", rec.Code)
|
||
|
|
}
|
||
|
|
if got := rec.Header().Get("WWW-Authenticate"); got == "" {
|
||
|
|
t.Fatal("missing WWW-Authenticate")
|
||
|
|
}
|
||
|
|
})
|
||
|
|
|
||
|
|
t.Run("protected with creds", func(t *testing.T) {
|
||
|
|
req := httptest.NewRequest(http.MethodGet, "/health", nil)
|
||
|
|
req.SetBasicAuth(config.AuthUser, config.AuthPass)
|
||
|
|
rec := httptest.NewRecorder()
|
||
|
|
h.ServeHTTP(rec, req)
|
||
|
|
if rec.Code != http.StatusOK {
|
||
|
|
t.Fatalf("status = %d, want 200", rec.Code)
|
||
|
|
}
|
||
|
|
})
|
||
|
|
}
|