Skip to content
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
wants to merge 2 commits into
base: fred/approval-service-skeleton-1
Choose a base branch
from
Open
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
152 changes: 152 additions & 0 deletions libs/github/webhook/webhook.go
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.
Copy link
Contributor

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.

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),
)
}
130 changes: 97 additions & 33 deletions tools/approval-service/cmd/approval-service.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
package main

import (
"context"
"fmt"
"log"
"log/slog"
"net/http"
"time"

"github.com/google/go-github/v69/github"
"github.com/gravitational/shared-workflows/libs/github/webhook"
"golang.org/x/sync/errgroup"
)

var logger = slog.Default()

// Process:
// 1. Take in events from CI/CD systems
// 2. Extract common information
Expand Down Expand Up @@ -28,19 +43,22 @@ func main() {
eventSources := []EventSource{
NewGitHubEventSource(processor),
}

for _, eventSource := range eventSources {
_ = eventSource.Setup()
}

done := make(chan struct{}) // TODO replace with error?
// 3. Start event sources
eg, ctx := errgroup.WithContext(context.Background())
for _, eventSource := range eventSources {
_ = eventSource.Run(done)
eg.Go(func() error {
return eventSource.Run(ctx)
})
}

// Block until an event source has a fatal error
<-done
close(done)
if err := eg.Wait(); err != nil {
log.Fatal(err)
}
}

// This contains information needed to process a request
Expand Down Expand Up @@ -99,12 +117,15 @@ type EventSource interface {
Setup() error

// Handle actual requests. This should not block.
Run(chan struct{}) error
Run(ctx context.Context) error
}

type GitHubEventSource struct {
processor ApprovalProcessor
// TODO

deployReviewChan chan *github.DeploymentReviewEvent
addr string
srv *http.Server
}

func NewGitHubEventSource(processor ApprovalProcessor) *GitHubEventSource {
Expand All @@ -114,43 +135,78 @@ func NewGitHubEventSource(processor ApprovalProcessor) *GitHubEventSource {
// Setup GH client, webhook secret, etc.
// https://github.com/go-playground/webhooks may help here
func (ghes *GitHubEventSource) Setup() error {
// TODO
deployReviewChan := make(chan *github.DeploymentReviewEvent)
ghes.deployReviewChan = deployReviewChan

mux := http.NewServeMux()
eventProcessor := webhook.EventHandlerFunc(func(event interface{}) error {
switch event := event.(type) {
case *github.DeploymentReviewEvent:
deployReviewChan <- event
return nil
default:
return fmt.Errorf("unknown event type: %T", event)
}
})
mux.Handle("/webhook", webhook.NewHandler(
eventProcessor,
webhook.WithSecretToken("secret-token"), // TODO: get from config
webhook.WithLogger(logger),
))

ghes.srv = &http.Server{
Addr: ghes.addr,
Handler: mux,
}

return nil
}

// Take incoming events and respond to them
func (ghes *GitHubEventSource) Run(done chan struct{}) error {
// If anything errors, deny the request. For safety, maybe `defer`
// the "response" function?
go func() {
// Notify the service that the listener is completely done.
// Normally this should only be hit if there is a fatal error
defer func() { done <- struct{}{} }()
func (ghes *GitHubEventSource) Run(ctx context.Context) error {
errc := make(chan error)

// Incoming webhook payloads
// This should be closed by the webhook listener func
payloads := make(chan interface{})

// Listen for webhook calls
go ghes.listenForPayloads(payloads, done)
// Start the HTTP server
go func() {
logger.Info("Listening for GitHub Webhooks", "address", ghes.addr)
errc <- ghes.srv.ListenAndServe()
close(errc)
}()

for payload := range payloads {
go ghes.processWebhookPayload(payload, done)
// Process incoming events
go func() {
defer close(ghes.deployReviewChan)
logger.Info("Starting GitHub event processor")
for {
select {
case <-ctx.Done():
return
case deployReview := <-ghes.deployReviewChan:
// Process the event
go ghes.processDeploymentReviewEvent(deployReview)
}
}
}()

return nil
}

// Listen for incoming webhook events. Register HTTP routes, start server, etc. Long running, blocking.
func (ghes *GitHubEventSource) listenForPayloads(payloads chan interface{}, done chan struct{}) {
// Once a call is received, it should return a 200 response immediately.
var err error
// This will block until an error occurs or the context is done
select {
case err = <-errc:
ghes.srv.Shutdown(context.Background()) // Ignore error - we're already handling one
case <-ctx.Done():
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err = ghes.srv.Shutdown(ctx)
<-errc // flush the error channel to avoid a goroutine leak
}

// TODO
if err != nil {
return fmt.Errorf("error enconutered while running GitHub event source: %w", err)
}
return nil
}

// Given an event, approve or deny it. This is a long running, blocking function.
func (ghes *GitHubEventSource) processWebhookPayload(payload interface{}, done chan struct{}) {
func (ghes *GitHubEventSource) processDeploymentReviewEvent(payload *github.DeploymentReviewEvent) error {
// Do GitHub-specific checks. Don't approve based off ot this - just deny
// if one fails.
automatedDenial, err := ghes.performAutomatedChecks(payload)
Expand All @@ -170,6 +226,11 @@ func (ghes *GitHubEventSource) processWebhookPayload(payload interface{}, done c
}

_ = ghes.respondToDeployRequest(true, payload)
return nil
}

// Given an event, approve or deny it. This is a long running, blocking function.
func (ghes *GitHubEventSource) processWebhookPayload(payload interface{}, done chan struct{}) {
}

// Turns GH-specific information into "common" information for the approver
Expand All @@ -183,10 +244,13 @@ func (ghes *GitHubEventSource) convertWebhookPayloadToEvent(payload interface{})

// Performs approval checks that are GH-specific. This should only be used to deny requests,
// never approve them.
func (ghes *GitHubEventSource) performAutomatedChecks(payload interface{}) (pass bool, err error) {
func (ghes *GitHubEventSource) performAutomatedChecks(payload *github.DeploymentReviewEvent) (pass bool, err error) {
// Verify request is from Gravitational org repo
// Verify request is from Gravitational org member
// See RFD for additional examples
if *payload.Organization.Login != "gravitational" {
return true, nil
}

return false, nil
}
Expand Down
12 changes: 12 additions & 0 deletions tools/approval-service/go.mod
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
)
18 changes: 18 additions & 0 deletions tools/approval-service/go.sum
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=
Loading