1
0
mirror of https://github.com/juanfont/headscale.git synced 2025-11-10 01:20:58 +01:00

fix: guard every error statement with early return (#2810)

This commit is contained in:
Elyas Asmad 2025-10-22 19:48:07 +08:00 committed by GitHub
parent 8becb7e54a
commit 2c9e98d3f5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -380,7 +380,6 @@ func (h *Headscale) httpAuthenticationMiddleware(next http.Handler) http.Handler
writer http.ResponseWriter,
req *http.Request,
) {
if err := func() error {
log.Trace().
Caller().
Str("client_address", req.RemoteAddr).
@ -388,14 +387,20 @@ func (h *Headscale) httpAuthenticationMiddleware(next http.Handler) http.Handler
authHeader := req.Header.Get("Authorization")
writeUnauthorized := func(statusCode int) {
writer.WriteHeader(statusCode)
if _, err := writer.Write([]byte("Unauthorized")); err != nil {
log.Error().Err(err).Msg("writing HTTP response failed")
}
}
if !strings.HasPrefix(authHeader, AuthPrefix) {
log.Error().
Caller().
Str("client_address", req.RemoteAddr).
Msg(`missing "Bearer " prefix in "Authorization" header`)
writer.WriteHeader(http.StatusUnauthorized)
_, err := writer.Write([]byte("Unauthorized"))
return err
writeUnauthorized(http.StatusUnauthorized)
return
}
valid, err := h.state.ValidateAPIKey(strings.TrimPrefix(authHeader, AuthPrefix))
@ -405,28 +410,15 @@ func (h *Headscale) httpAuthenticationMiddleware(next http.Handler) http.Handler
Err(err).
Str("client_address", req.RemoteAddr).
Msg("failed to validate token")
writer.WriteHeader(http.StatusInternalServerError)
_, err := writer.Write([]byte("Unauthorized"))
return err
writeUnauthorized(http.StatusInternalServerError)
return
}
if !valid {
log.Info().
Str("client_address", req.RemoteAddr).
Msg("invalid token")
writer.WriteHeader(http.StatusUnauthorized)
_, err := writer.Write([]byte("Unauthorized"))
return err
}
return nil
}(); err != nil {
log.Error().
Caller().
Err(err).
Msg("Failed to write HTTP response")
writeUnauthorized(http.StatusUnauthorized)
return
}