Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
feat: Increase logging verbosity for error responses
Browse files Browse the repository at this point in the history
  • Loading branch information
B&R committed Mar 20, 2023
1 parent 767707a commit b0f0600
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
38 changes: 38 additions & 0 deletions http/logging.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package http

import (
"bytes"
"encoding/json"
"github.com/gin-gonic/gin"
"github.com/sirupsen/logrus"
"strings"
)

type errorLogWriter struct {
gin.ResponseWriter
body *bytes.Buffer
}

func (w errorLogWriter) Write(b []byte) (int, error) {
if w.Status() > 299 && strings.Contains(w.Header().Get("Content-Type"), "application/json") {
w.body.Write(b)
}
return w.ResponseWriter.Write(b)
}

func responseErrorLoggerMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
blw := &errorLogWriter{body: bytes.NewBufferString(""), ResponseWriter: c.Writer}
c.Writer = blw
c.Next()
if len(blw.body.String()) > 0 {
response := GenericResponseType{}
unmarshalErr := json.Unmarshal(blw.body.Bytes(), &response)
if unmarshalErr != nil {
logrus.Warningln("Cannot parse error response. Probably not in valid format")
return
}
logrus.Errorf("Returned '%s' error, message: '%s'", response.Error, response.Message)
}
}
}
7 changes: 4 additions & 3 deletions http/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ func SpawnHttpApplication(app *core.ApplicationContainer, listenAddr string) err
r := gin.Default()

authMiddleware := createAuthenticationMiddleware(r, app)
errorLoggerMiddleware := responseErrorLoggerMiddleware()

// set a rate limit of 10 requests per minute for IP address to protect against DoS attacks on login and refresh_token endpoints
// for two reasons:
Expand All @@ -26,9 +27,9 @@ func SpawnHttpApplication(app *core.ApplicationContainer, listenAddr string) err
}).Middleware()

router := r.Group("/")
router.POST("/api/stable/auth/login", authRateLimitMiddleware.Middleware(), authMiddleware.LoginHandler)
router.GET("/api/stable/auth/refresh_token", authRateLimitMiddleware.Middleware(), authMiddleware.RefreshHandler)
router.Use(authMiddleware.MiddlewareFunc())
router.POST("/api/stable/auth/login", errorLoggerMiddleware, authRateLimitMiddleware.Middleware(), authMiddleware.LoginHandler)
router.GET("/api/stable/auth/refresh_token", errorLoggerMiddleware, authRateLimitMiddleware.Middleware(), authMiddleware.RefreshHandler)
router.Use(authMiddleware.MiddlewareFunc(), errorLoggerMiddleware)
{
addLookupUserRoute(router, app, defaultRateLimitMiddleware)
addWhoamiRoute(router, app, defaultRateLimitMiddleware)
Expand Down

0 comments on commit b0f0600

Please sign in to comment.