Skip to content

Commit

Permalink
Coprocess plugins should be able to override error messages
Browse files Browse the repository at this point in the history
Use `Request.ReturnOverrides.ResponseError`, and retain compatibility
by serving default error message.
  • Loading branch information
buger committed Aug 4, 2017
1 parent 84b0086 commit 81a35db
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 1 deletion.
7 changes: 6 additions & 1 deletion coprocess.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,12 @@ func (m *CoProcessMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Requ
// Report in health check
ReportHealthCheckValue(m.Spec.Health, KeyFailure, "1")

return errors.New("Key not authorised"), int(returnObject.Request.ReturnOverrides.ResponseCode)
errorMsg := "Key not authorised"
if returnObject.Request.ReturnOverrides.ResponseError != "" {
errorMsg = returnObject.Request.ReturnOverrides.ResponseError
}

return errors.New(errorMsg), int(returnObject.Request.ReturnOverrides.ResponseCode)
}

if returnObject.Request.ReturnOverrides.ResponseCode > 0 {
Expand Down
16 changes: 16 additions & 0 deletions coprocess_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,22 @@ func TestCoProcessReturnOverrides(t *testing.T) {
}
}

func TestCoProcessReturnOverridesErrorMessage(t *testing.T) {
spec := createSpecTest(t, basicCoProcessDef)
chain := buildCoProcessChain(spec, "hook_test_return_overrides_error", coprocess.HookType_Pre, apidef.MiddlewareDriver("python"))
session := createNonThrottledSession()
spec.SessionManager.UpdateSession("abc", session, 60)

recorder := httptest.NewRecorder()

req := testReq(t, "GET", "/headers", nil)
req.Header.Set("authorization", "abc")
chain.ServeHTTP(recorder, req)
if recorder.Code != 401 || recorder.Body.String() != "{\n \"error\": \"custom error message\"\n}" {
t.Fatal("ReturnOverrides HTTP response is invalid", recorder.Code, recorder.Body)
}
}

const basicCoProcessDef = `{
"api_id": "1",
"org_id": "default",
Expand Down
5 changes: 5 additions & 0 deletions coprocess_test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ func applyTestHooks(objectPtr unsafe.Pointer) {
ResponseCode: 200,
ResponseError: "body",
}
case "hook_test_return_overrides_error":
object.Request.ReturnOverrides = &coprocess.ReturnOverrides{
ResponseCode: 401,
ResponseError: "custom error message",
}
case "hook_test_bad_auth_using_id_extractor":
case "hook_test_bad_auth_cp_error":
case "hook_test_successful_auth":
Expand Down

0 comments on commit 81a35db

Please sign in to comment.