Skip to content

[UBP] Add tests and functionality to the Stripe webhook handler #11921

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions components/public-api-server/pkg/webhooks/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,12 @@ func NewStripeWebhookHandler() *webhookHandler {
func (h *webhookHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
const maxBodyBytes = int64(65536)

if req.Method != http.MethodPost {
log.Errorf("Bad HTTP method: %s", req.Method)
w.WriteHeader(http.StatusBadRequest)
return
}

req.Body = http.MaxBytesReader(w, req.Body, maxBodyBytes)

event := stripe.Event{}
Expand All @@ -32,6 +38,12 @@ func (h *webhookHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
return
}

if event.Type != "invoice.finalized" {
log.Errorf("Unexpected Stripe event type: %s", event.Type)
w.WriteHeader(http.StatusBadRequest)
return
}

// TODO: verify webhook signature.
// Conditional on there being a secret configured.

Expand Down
117 changes: 117 additions & 0 deletions components/public-api-server/pkg/webhooks/stripe_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
// Copyright (c) 2022 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.

package webhooks

import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"testing"

"github.com/gitpod-io/gitpod/common-go/baseserver"
"github.com/stretchr/testify/require"
"github.com/stripe/stripe-go/v72"
)

// https://stripe.com/docs/api/events/types
const (
invoiceUpdatedEventType = "invoice.updated"
invoiceFinalizedEventType = "invoice.finalized"
customerCreatedEventType = "customer.created"
)

func TestWebhookAcceptsPostRequests(t *testing.T) {
scenarios := []struct {
HttpMethod string
ExpectedStatusCode int
}{
{
HttpMethod: http.MethodPost,
ExpectedStatusCode: http.StatusOK,
},
{
HttpMethod: http.MethodGet,
ExpectedStatusCode: http.StatusBadRequest,
},
{
HttpMethod: http.MethodPut,
ExpectedStatusCode: http.StatusBadRequest,
},
}

srv := baseServerWithStripeWebhook(t)

ev := stripe.Event{Type: invoiceFinalizedEventType}
payload, err := json.Marshal(ev)
require.NoError(t, err)

url := fmt.Sprintf("%s%s", srv.HTTPAddress(), "/webhook")

for _, scenario := range scenarios {
t.Run(scenario.HttpMethod, func(t *testing.T) {
req, err := http.NewRequest(scenario.HttpMethod, url, bytes.NewBuffer(payload))
require.NoError(t, err)

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)

require.Equal(t, scenario.ExpectedStatusCode, resp.StatusCode)
})
}
}

func TestWebhookIgnoresIrrelevantEvents(t *testing.T) {
scenarios := []struct {
EventType string
ExpectedStatusCode int
}{
{
EventType: invoiceFinalizedEventType,
ExpectedStatusCode: http.StatusOK,
},
{
EventType: invoiceUpdatedEventType,
ExpectedStatusCode: http.StatusBadRequest,
},
{
EventType: customerCreatedEventType,
ExpectedStatusCode: http.StatusBadRequest,
},
}

srv := baseServerWithStripeWebhook(t)

url := fmt.Sprintf("%s%s", srv.HTTPAddress(), "/webhook")

for _, scenario := range scenarios {
t.Run(scenario.EventType, func(t *testing.T) {
ev := stripe.Event{Type: scenario.EventType}
payload, err := json.Marshal(ev)
require.NoError(t, err)

req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(payload))
require.NoError(t, err)

resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)

require.Equal(t, scenario.ExpectedStatusCode, resp.StatusCode)
})
}
}

func baseServerWithStripeWebhook(t *testing.T) *baseserver.Server {
t.Helper()

srv := baseserver.NewForTests(t,
baseserver.WithHTTP(baseserver.MustUseRandomLocalAddress(t)),
)
baseserver.StartServerForTests(t, srv)

srv.HTTPMux().Handle("/webhook", NewStripeWebhookHandler())

return srv
}