Skip to content

Commit

Permalink
Test RedactJSONRequestBodies and RedactJSONResponseBodies option on m…
Browse files Browse the repository at this point in the history
…iddleware options
  • Loading branch information
TheTeaCat committed Jan 13, 2025
1 parent 695dd21 commit f4b1375
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions middlewares/http/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,54 @@ func TestValidRequestAndResponse(t *testing.T) {
assert.Equal(t, "{\"description\":\"test description\"}", string(respBody))
}

func TestValidRequestAndResponseWithRedactionEnabled(t *testing.T) {
wg := &sync.WaitGroup{}
wg.Add(1)
var logBatchCallbackErr error
var logEntryReceivedByLogBatchCallback logging.LogEntry
middleware, err := GetMiddleware(&Options{
OpenapiSpecPath: "./test-spec.yaml",
AuthCallbacks: authCallbacks,
EnableRequestValidation: true,
EnableResponseValidation: true,
RedactJSONRequestBodies: true,
RedactJSONResponseBodies: true,
MaxLogAge: time.Nanosecond,
LogBatchCallback: func(logs [][]byte) {
defer wg.Done()
require.Equal(t, 1, len(logs))
logEntryReceivedByLogBatchCallback, logBatchCallbackErr = logging.UnmarshalLogEntry(logs[0])
},
})
require.Nil(t, err)
handler := middleware(healthHandler)
responseRecorder := httptest.NewRecorder()

request := httptest.NewRequest(
"POST", "/implemented/1",
io.NopCloser(bytes.NewBuffer([]byte("{\"description\":\"test description\"}"))),
)
request.Header.Add("Content-Type", "application/json")
request.Header.Add("X-Api-Key", "valid-api-key")
handler.ServeHTTP(responseRecorder, request)

assert.Equal(t, 200, responseRecorder.Code)

require.Contains(t, responseRecorder.HeaderMap, "Content-Type")
require.GreaterOrEqual(t, len(responseRecorder.HeaderMap["Content-Type"]), 1)
assert.Len(t, responseRecorder.HeaderMap["Content-Type"], 1)
assert.Equal(t, "application/json", responseRecorder.HeaderMap["Content-Type"][0])

respBody, err := io.ReadAll(responseRecorder.Body)
require.Nil(t, err)
assert.Equal(t, "{\"description\":\"test description\"}", string(respBody))

// Wait for the log callback to have been called & then run our assertions on the log it received
wg.Wait()
require.Nil(t, logBatchCallbackErr)
require.Equal(t, "{\"description\":\"\"}", logEntryReceivedByLogBatchCallback.Request.Body)
}

func TestNoSpec(t *testing.T) {
wg := &sync.WaitGroup{}
wg.Add(1)
Expand Down

0 comments on commit f4b1375

Please sign in to comment.