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

Proposal for v2. #120

Merged
merged 20 commits into from
Aug 30, 2023
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,5 @@ examples/timedListener/timedListener

go.work
go.work.sum

cmd/bearerListener/bearerListener
134 changes: 134 additions & 0 deletions cmd/bearerListener/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0

package main

import (
"fmt"
"io"
"net/http"
"os"
"strings"
"time"

"github.com/xmidt-org/webhook-schema"
listener "github.com/xmidt-org/wrp-listener"
"go.uber.org/zap"
)

type eventListener struct {
l *listener.Listener
}

func (el *eventListener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
token, err := el.l.Tokenize(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
fmt.Println("Got a request, but it was not authorized.")
return
}

err = el.l.Authorize(r, token)
if err != nil {
fmt.Println("Got a request, but it was not authorized.")
w.WriteHeader(http.StatusUnauthorized)
return
}

body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
fmt.Println("Got a request, but it had no body.")
w.WriteHeader(http.StatusBadRequest)
return
}

fmt.Println(string(body))

w.WriteHeader(http.StatusOK)
}

func main() {
receiverURL := strings.TrimSpace(os.Getenv("WEBHOOK_TARGET"))
webhookURL := strings.TrimSpace(os.Getenv("WEBHOOK_URL"))
localAddress := strings.TrimSpace(os.Getenv("WEBHOOK_LISTEN_ADDR"))
certFile := strings.TrimSpace(os.Getenv("WEBHOOK_LISTEN_CERT_FILE"))
keyFile := strings.TrimSpace(os.Getenv("WEBHOOK_LISTEN_KEY_FILE"))
contentType := strings.TrimSpace(os.Getenv("WEBHOOK_CONTENT_TYPE"))
events := strings.TrimSpace(os.Getenv("WEBHOOK_EVENTS"))

useTLS := false
if certFile != "" && keyFile != "" {
useTLS = true
}

fmt.Println("WEBHOOK_TARGET : ", receiverURL)
fmt.Println("WEBHOOK_URL : ", webhookURL)
fmt.Println("WEBHOOK_LISTEN_ADDR : ", localAddress)
fmt.Println("WEBHOOK_LISTEN_CERT_FILE: ", certFile)
fmt.Println("WEBHOOK_LISTEN_KEY_FILE : ", keyFile)
fmt.Println("WEBHOOK_CONTENT_TYPE : ", contentType)
fmt.Printf(" use TLS: %t\n", useTLS)

// Create the listener.
r := webhook.Registration{
Config: webhook.DeliveryConfig{
ReceiverURL: receiverURL,
ContentType: contentType,
},
Events: []string{events},
Duration: webhook.CustomDuration(15 * time.Second),
}

sharedSecrets := strings.Split(os.Getenv("WEBHOOK_SHARED_SECRETS"), ",")
for i := range sharedSecrets {
sharedSecrets[i] = strings.TrimSpace(sharedSecrets[i])
}

logger, err := zap.NewDevelopment()
if err != nil {
panic(err)
}

whl, err := listener.New(&r, webhookURL,
listener.AuthBearer(os.Getenv("WEBHOOK_BEARER_TOKEN")),
listener.AcceptSHA1(),
listener.Logger(logger),
listener.Once(),
listener.AcceptedSecrets(sharedSecrets...),
)
if err != nil {
panic(err)
}

fmt.Println(whl.String())

el := eventListener{
l: whl,
}

go func() {
if useTLS {
err := http.ListenAndServeTLS(localAddress, certFile, keyFile, &el) // nolint: gosec
if err != nil {
panic(err)
}
} else {
err := http.ListenAndServe(localAddress, &el) // nolint: gosec
if err != nil {
panic(err)
}
}
}()

// Register for webhook events, using the secret "foobar" as the shared
// secret.
err = whl.Register(sharedSecrets[0])
if err != nil {
panic(err)
}

for {
time.Sleep(1 * time.Minute)
}
}
17 changes: 17 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0

package listener

import (
"errors"
)

var (
ErrInput = errors.New("invalid input")
ErrInvalidAuth = errors.New("invalid auth")
ErrInvalidRegistration = errors.New("invalid registration")
ErrRegistrationFailed = errors.New("registration failed")
ErrRegistrationNotAttempted = errors.New("registration not attempted")
ErrNotAcceptedHash = errors.New("not accepted hash")
)
156 changes: 156 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
// SPDX-FileCopyrightText: 2023 Comcast Cable Communications Management, LLC
// SPDX-License-Identifier: Apache-2.0

package listener_test

import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"time"

"github.com/xmidt-org/webhook-schema"
listener "github.com/xmidt-org/wrp-listener"
)

func startFakeListener() *httptest.Server {
server := httptest.NewServer(
http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
r.Body.Close()

var reg webhook.Registration
_ = json.Unmarshal(body, &reg)

w.WriteHeader(http.StatusOK)
},
),
)

return server
}

type eventListener struct {
l *listener.Listener
}

func (el *eventListener) ServeHTTP(w http.ResponseWriter, r *http.Request) {
token, err := el.l.Tokenize(r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}

err = el.l.Authorize(r, token)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
return
}

body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}

fmt.Println(string(body))

w.WriteHeader(http.StatusOK)
}

func ExampleBasicAuth() { // nolint: govet
server := startFakeListener()
defer server.Close()

// Create the listener.
r := webhook.Registration{
Config: webhook.DeliveryConfig{
ContentType: "application/json",
},
Duration: webhook.CustomDuration(5 * time.Minute),
}

url := server.URL // replace with the URL of the webhook provider
whl, err := listener.New(&r, url,
listener.AuthBasic("username", "password"),
listener.AcceptSHA1(),
listener.AcceptedSecrets("foobar", "carport"),
)
if err != nil {
panic(err)
}

el := eventListener{
l: whl,
}

go func() {
err := http.ListenAndServe(":8080", &el) // nolint: gosec
if err != nil {
panic(err)
}
}()

// Register for webhook events, using the secret "foobar" as the shared
// secret.
err = whl.Register("foobar")
if err != nil {
panic(err)
}

// Output:
}

func ExampleBearerAuth() { // nolint: govet
server := startFakeListener()
defer server.Close()

// Create the listener.
r := webhook.Registration{
Config: webhook.DeliveryConfig{
ContentType: "application/json",
},
Duration: webhook.CustomDuration(5 * time.Minute),
}

sharedSecret := strings.Split(os.Getenv("SHARED_SECRET"), ",")
for i := range sharedSecret {
sharedSecret[i] = strings.TrimSpace(sharedSecret[i])
}

url := server.URL // replace with the URL of the webhook provider
whl, err := listener.New(&r, url,
listener.AuthBearer(os.Getenv("BEARER_TOKEN")),
listener.AcceptSHA1(),
listener.AcceptedSecrets(sharedSecret...),
)
if err != nil {
panic(err)
}

el := eventListener{
l: whl,
}

go func() {
err := http.ListenAndServe(":8081", &el) // nolint: gosec
if err != nil {
panic(err)
}
}()

// Register for webhook events, using the secret "foobar" as the shared
// secret.
err = whl.Register("foobar")
if err != nil {
panic(err)
}

// Output:
}
Loading