Skip to content

Commit

Permalink
Fix trigger response handling for streamed 0 length response body (#345)
Browse files Browse the repository at this point in the history
  • Loading branch information
paulo authored May 5, 2023
1 parent 381cbd3 commit 3fabd3f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
15 changes: 14 additions & 1 deletion api/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"encoding/hex"
"encoding/json"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/httptrace"
Expand Down Expand Up @@ -239,8 +240,20 @@ func triggerHook(ctx context.Context, hookURL *url.URL, secret string, conn *sto
}
}()
if err == nil && body != nil {
// handle case where response from the trigger is streamed but has no
// Body
data, err := ioutil.ReadAll(body)
if err != nil {
return internalServerError("Webhook returned malformed BODY: %v", err).WithInternalError(err)
}

if len(data) == 0 {
return nil
}

bodyReader := bytes.NewReader(data)
webhookRsp := &WebhookResponse{}
decoder := json.NewDecoder(body)
decoder := json.NewDecoder(bodyReader)
if err = decoder.Decode(webhookRsp); err != nil {
return internalServerError("Webhook returned malformed JSON: %v", err).WithInternalError(err)
}
Expand Down
14 changes: 2 additions & 12 deletions api/signup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package api
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -131,13 +130,6 @@ func (ts *SignupTestSuite) TestWebhookTriggered() {

w.WriteHeader(http.StatusOK)
w.(http.Flusher).Flush() // needed so we don't set a content-length

pl := `{
"app_metadata": {
"roles": ["dev"]
}
}`
fmt.Fprint(w, pl)
}))
defer svr.Close()

Expand Down Expand Up @@ -168,10 +160,8 @@ func (ts *SignupTestSuite) TestWebhookTriggered() {
assert.Equal(http.StatusOK, w.Code)
assert.Equal(1, callCount)

var user models.User
require.NoError(json.NewDecoder(w.Body).Decode(&user))

assert.EqualValues(models.JSONMap{"roles": []interface{}{"dev"}}, user.AppMetaData)
// http stdlib doesn't set Body as http.NoBody if Content-Length = -1
require.True(w.Result().Body != http.NoBody)
}

func (ts *SignupTestSuite) TestFailingWebhook() {
Expand Down

0 comments on commit 3fabd3f

Please sign in to comment.