-
Notifications
You must be signed in to change notification settings - Fork 3
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
Implementing GitHub webhook handler #331
Open
doggydogworld
wants to merge
2
commits into
fred/approval-service-skeleton-1
Choose a base branch
from
gus/additions-to-approval-service
base: fred/approval-service-skeleton-1
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+279
−33
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,152 @@ | ||
package webhook | ||
|
||
import ( | ||
"log/slog" | ||
"net/http" | ||
|
||
"github.com/google/go-github/v63/github" | ||
) | ||
|
||
// EventHandlerFunc is a function that handles a webhook event. | ||
// The function should return an error if the event could not be handled. | ||
// If the error is not nil, the webhook will respond with a 500 Internal Server Error. | ||
// | ||
// It is important that this is non-blocking and does not perform any long-running operations. | ||
// GitHub will close the connection if the webhook does not respond within 10 seconds. | ||
// | ||
// Example usage: | ||
// | ||
// func(event interface{}) error { | ||
// switch event := event.(type) { | ||
// case *github.CommitCommentEvent: | ||
// processCommitCommentEvent(event) | ||
// case *github.CreateEvent: | ||
// processCreateEvent(event) | ||
// ... | ||
// } | ||
// return nil | ||
// } | ||
type EventHandlerFunc func(event interface{}) error | ||
|
||
// Handler is an implementation of [http.Handler] that handles GitHub webhook events. | ||
type Handler struct { | ||
eventHandler EventHandlerFunc | ||
secretToken []byte | ||
log *slog.Logger | ||
} | ||
|
||
var _ http.Handler = &Handler{} | ||
|
||
type Opt func(*Handler) error | ||
|
||
// WithSecretToken sets the secret token for the webhook. | ||
// The secret token is used to create a hash of the request body, which is sent in the X-Hub-Signature header. | ||
// If not set, the webhook will not verify the signature of the request. | ||
// | ||
// For more information, see: https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries | ||
func WithSecretToken(secretToken string) Opt { | ||
return func(p *Handler) error { | ||
p.secretToken = []byte(secretToken) | ||
return nil | ||
} | ||
} | ||
|
||
// WithLogger sets the logger for the webhook. | ||
func WithLogger(log *slog.Logger) Opt { | ||
return func(p *Handler) error { | ||
p.log = log | ||
return nil | ||
} | ||
} | ||
|
||
var defaultOpts = []Opt{ | ||
WithLogger(slog.Default()), | ||
} | ||
|
||
// NewHandler creates a new webhook handler. | ||
func NewHandler(eventHandler EventHandlerFunc, opts ...Opt) *Handler { | ||
h := Handler{ | ||
eventHandler: eventHandler, | ||
} | ||
for _, opt := range defaultOpts { | ||
opt(&h) | ||
} | ||
|
||
for _, opt := range opts { | ||
opt(&h) | ||
} | ||
return &h | ||
} | ||
|
||
// Headers is a list of special headers that are sent with a webhook request. | ||
// For more information, see: https://docs.github.com/en/webhooks/webhook-events-and-payloads#delivery-headers | ||
type Headers struct { | ||
// GithubHookID is the unique identifier of the webhook. | ||
GithubHookID string | ||
// GithubEvent is the type of event that triggered the delivery. | ||
GithubEvent string | ||
// GithubDelivery is a globally unique identifier (GUID) to identify the event | ||
GithubDelivery string | ||
// GitHubHookInstallationTargetType is the type of resource where the webhook was created. | ||
GitHubHookInstallationTargetType string | ||
// GitHubHookInstallationTargetID is the unique identifier of the resource where the webhook was created. | ||
GitHubHookInstallationTargetID string | ||
|
||
// HubSignature256 is the HMAC hex digest of the response body. | ||
// Is generated with the SHA-256 algorithm with a shared secret used as the HMAC key. | ||
// This header will be sent if the webhook is configured with a secret. | ||
HubSignature256 string | ||
} | ||
|
||
// ServeHTTP handles a webhook request. | ||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { | ||
defer r.Body.Close() | ||
// Parse headers for debugging and audit purposes. | ||
var head Headers | ||
head.GithubHookID = r.Header.Get("X-GitHub-Hook-ID") | ||
head.GithubEvent = r.Header.Get("X-GitHub-Event") | ||
head.GithubDelivery = r.Header.Get("X-GitHub-Delivery") | ||
head.GitHubHookInstallationTargetType = r.Header.Get("X-GitHub-Hook-Installation-Target-Type") | ||
head.GitHubHookInstallationTargetID = r.Header.Get("X-GitHub-Hook-Installation-Target-ID") | ||
head.HubSignature256 = r.Header.Get("X-Hub-Signature-256") | ||
|
||
if h.secretToken == nil && head.HubSignature256 != "" { | ||
h.log.Warn("received signature but no secret token is set", "github_headers", head) | ||
http.Error(w, "invalid request", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
payload, err := github.ValidatePayload(r, h.secretToken) // If secretToken is empty, the signature will not be verified. | ||
if err != nil { | ||
h.log.Warn("webhook validation failed", "github_headers", head) | ||
http.Error(w, "invalid request", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
event, err := github.ParseWebHook(head.GithubEvent, payload) | ||
if err != nil { | ||
h.log.Error("failed to parse webhook event", "error", err) | ||
http.Error(w, "invalid request", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
if err := h.eventHandler(event); err != nil { | ||
h.log.Error("failed to handle webhook event", "error", err) | ||
http.Error(w, "internal server error", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
// Respond to the request. | ||
w.WriteHeader(http.StatusOK) | ||
} | ||
|
||
func (h *Headers) LogValue() slog.Value { | ||
return slog.GroupValue( | ||
slog.String("github_hook_id", h.GithubHookID), | ||
slog.String("github_event", h.GithubEvent), | ||
slog.String("github_delivery", h.GithubDelivery), | ||
slog.String("github_hook_installation_target_type", h.GitHubHookInstallationTargetType), | ||
slog.String("github_hook_installation_target_id", h.GitHubHookInstallationTargetID), | ||
slog.String("hub_signature_256", h.HubSignature256), | ||
) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,3 +1,15 @@ | ||
module github.com/gravitational/shared-workflows/tools/approval-service | ||
|
||
go 1.23.5 | ||
|
||
require ( | ||
github.com/google/go-github/v69 v69.1.0 | ||
github.com/gravitational/trace v1.5.0 | ||
) | ||
|
||
require ( | ||
github.com/google/go-querystring v1.1.0 // indirect | ||
github.com/stretchr/testify v1.9.0 // indirect | ||
golang.org/x/net v0.34.0 // indirect | ||
golang.org/x/sync v0.11.0 // indirect | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= | ||
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= | ||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= | ||
github.com/google/go-github/v69 v69.1.0 h1:ljzwzEsHsc4qUqyHEJCNA1dMqvoTK3YX2NAaK6iprDg= | ||
github.com/google/go-github/v69 v69.1.0/go.mod h1:xne4jymxLR6Uj9b7J7PyTpkMYstEMMwGZa0Aehh1azM= | ||
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= | ||
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= | ||
github.com/gravitational/trace v1.5.0 h1:JbeL2HDGyzgy7G72Z2hP2gExEyA6Y2p7fCiSjyZwCJw= | ||
github.com/gravitational/trace v1.5.0/go.mod h1:dxezSkKm880IIDx+czWG8fq+pLnXjETBewMgN3jOBlg= | ||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= | ||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= | ||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= | ||
golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= | ||
golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= | ||
golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= | ||
golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= | ||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= | ||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think that we should error if the secret token is empty and a signature is provided. If this happens, we've probably misconfigured something.