Skip to content
Merged
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
12 changes: 6 additions & 6 deletions internal/api/listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ func NewListener(config *config.Config, logger *slog.Logger, icingaClient *icing
mux := http.NewServeMux()
// Register all handler functions here to have a central overview of the API
mux.HandleFunc("GET /healthz", l.handleHealthy)
mux.HandleFunc("POST /webhook", l.handleIncomingAlert)
mux.HandleFunc("POST /webhook", authHandler(l.handleIncomingAlert, config.BearerToken))

l.mux = authHandler(mux, config.BearerToken)
l.mux = mux

return l
}
Expand Down Expand Up @@ -115,25 +115,25 @@ func (l *Listener) Run(ctx context.Context) error {

// authHandler is a Middleware for handling authorization.
// We currently only need Bearer token authorization, since we don't have complex actions in the API.
func authHandler(next http.Handler, expectedToken string) http.Handler {
func authHandler(f func(http.ResponseWriter, *http.Request), expectedToken string) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get the Authorization Header from the request
authHeader := r.Header.Get("Authorization")

scheme, receivedToken, found := strings.Cut(authHeader, " ")

if !found || !strings.EqualFold(scheme, "Bearer") || receivedToken == "" {
http.Error(w, "malformed authorization header", http.StatusUnauthorized)
http.Error(w, "unauthorized. missing or malformed authorization header", http.StatusUnauthorized)
return
}

if receivedToken != expectedToken {
http.Error(w, "invalid token", http.StatusUnauthorized)
http.Error(w, "unauthorized. invalid token", http.StatusUnauthorized)
return
}

// Pass down the request to the next middleware or handler
next.ServeHTTP(w, r)
f(w, r)
})
}

Expand Down
7 changes: 3 additions & 4 deletions internal/api/listener_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,8 @@ func TestAuthHandler_WithOK(t *testing.T) {
w.WriteHeader(http.StatusOK)
}

var handler http.Handler = http.HandlerFunc(h)
handler = authHandler(handler, "foobar123")
var handler http.Handler = authHandler(http.HandlerFunc(h), "foobar123")

w := httptest.NewRecorder()

reqNoType, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
Expand All @@ -69,8 +69,7 @@ func TestAuthHandler_WithFail(t *testing.T) {
w.WriteHeader(http.StatusOK)
}

var handler http.Handler = http.HandlerFunc(h)
handler = authHandler(handler, "foobar123")
var handler http.Handler = authHandler(http.HandlerFunc(h), "foobar123")
w := httptest.NewRecorder()

req, _ := http.NewRequestWithContext(context.Background(), "GET", "/", nil)
Expand Down