From 381cbd32cabdcd8ab100817c85e7cf3476bc4e1d Mon Sep 17 00:00:00 2001 From: Marcus Weiner Date: Fri, 28 Apr 2023 03:34:05 +0200 Subject: [PATCH] Fix reading webhook response when content length is unknown (#342) --- api/hooks.go | 9 +++++---- api/signup_test.go | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/api/hooks.go b/api/hooks.go index 481912781..5a8f7410d 100644 --- a/api/hooks.go +++ b/api/hooks.go @@ -117,14 +117,15 @@ func (w *Webhook) trigger() (io.ReadCloser, error) { } dur := time.Since(start) rspLog := hooklog.WithFields(logrus.Fields{ - "status_code": rsp.StatusCode, - "dur": dur.Nanoseconds(), + "status_code": rsp.StatusCode, + "dur": dur.Nanoseconds(), + "content_length": rsp.ContentLength, }) switch rsp.StatusCode { case http.StatusOK, http.StatusNoContent, http.StatusAccepted: - rspLog.Infof("Finished processing webhook in %s", dur) + rspLog.Info("Finished processing webhook") var body io.ReadCloser - if rsp.ContentLength > 0 { + if rsp.Body != http.NoBody && rsp.ContentLength != 0 { body = rsp.Body } return body, nil diff --git a/api/signup_test.go b/api/signup_test.go index 09025ec82..5ab00b715 100644 --- a/api/signup_test.go +++ b/api/signup_test.go @@ -3,6 +3,7 @@ package api import ( "bytes" "encoding/json" + "fmt" "io/ioutil" "net/http" "net/http/httptest" @@ -92,6 +93,7 @@ func (ts *SignupTestSuite) TestWebhookTriggered() { token, err := p.ParseWithClaims(signature, claims, func(token *jwt.Token) (interface{}, error) { return []byte(ts.Config.Webhook.Secret), nil }) + assert.NoError(err) assert.True(token.Valid) assert.Equal(ts.instanceID.String(), claims.Subject) // not configured for multitenancy assert.Equal("gotrue", claims.Issuer) @@ -126,6 +128,16 @@ func (ts *SignupTestSuite) TestWebhookTriggered() { require.True(ok) assert.Len(usermeta, 1) assert.EqualValues(1, usermeta["a"]) + + 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() @@ -155,6 +167,11 @@ func (ts *SignupTestSuite) TestWebhookTriggered() { ts.API.handler.ServeHTTP(w, req) 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) } func (ts *SignupTestSuite) TestFailingWebhook() {