Skip to content

Commit

Permalink
feat: change startup message
Browse files Browse the repository at this point in the history
  • Loading branch information
upvest-mike committed Sep 24, 2024
1 parent 472018b commit 6431135
Show file tree
Hide file tree
Showing 12 changed files with 365 additions and 151 deletions.
90 changes: 90 additions & 0 deletions cmd/listen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
/*
Copyright © 2021 Upvest GmbH <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cmd

import (
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"

"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/upvestco/httpsignature-proxy/service/logger"
"github.com/upvestco/httpsignature-proxy/service/runtime"
)

const (
eventsFlag = "events"
showWebhookHeader = "show-webhook-headers"
)

var (
logHeaders bool
events string
)

var listenCmd = &cobra.Command{
Use: "listen",
Short: "Listen for the webhook events",
Run: func(cmd *cobra.Command, args []string) {
startListener()
},
}

func init() {
RootCmd.AddCommand(listenCmd)
listenCmd.Flags().StringVar(&events, eventsFlag, "", "subscribe for event types")
listenCmd.Flags().BoolVar(&logHeaders, showWebhookHeader, false, "show webhook request headers.")
listenCmd.Flags().IntVarP(&port, portFlag, "p", 3000, "port to start server")
listenCmd.Flags().BoolVarP(&verboseMode, verboseModeFlag, "v", false, "enable verbose mode")
}

func startListener() {
ll := logger.New(verboseMode)
proxyAddress := fmt.Sprintf("http://localhost:%d", port)
var showIntro = false
uc, code, err := runtime.AskForUserCredentials(proxyAddress)
if err != nil {
if errors.Is(err, syscall.ECONNREFUSED) {
panic("No http signature proxy is found")
} else {
panic(err.Error())
}
} else if code != http.StatusAccepted {
panic("The address " + proxyAddress + " is used by some other application. Fail to start webhook listener")
}
if uc.Empty() {
showIntro = true
}

tunnels := runtime.CreateTunnels(ll, strings.Split(events, ","), time.Second, proxyAddress,
func(credentials runtime.UserCredentials) runtime.ApiClient {
return runtime.NewClient(proxyAddress, credentials, time.Second*15)
}, logHeaders)
go tunnels.Start(showIntro)

c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
<-c
if tunnels != nil {
tunnels.Stop()
}
}
62 changes: 29 additions & 33 deletions cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,13 @@ import (
"log"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"

"github.com/spf13/cobra"
"github.com/upvestco/httpsignature-proxy/service/signer/logger"

"github.com/upvestco/httpsignature-proxy/config"
"github.com/upvestco/httpsignature-proxy/service/logger"
"github.com/upvestco/httpsignature-proxy/service/runtime"
"github.com/upvestco/httpsignature-proxy/service/signer"
)
Expand All @@ -41,10 +39,8 @@ const (
clientIDFlag = "client-id"
serverBaseUrlFlag = "server-base-url"
portFlag = "port"
listenFlag = "listen"
eventsFlag = "events"
showWebhookHeader = "show-webhook-headers"
verboseModeFlag = "verbose-mode"
listenFlag = "listen"
)

var (
Expand All @@ -56,9 +52,7 @@ var (
clientID string
port int
verboseMode bool
logHeaders bool
listen bool
events string
)

var startCmd = &cobra.Command{
Expand All @@ -69,12 +63,11 @@ var startCmd = &cobra.Command{
return nil
},
Run: func(cmd *cobra.Command, args []string) {
run()
startProxy()
},
}

func init() {
// Register the start command
RootCmd.AddCommand(startCmd)

startCmd.Flags().StringVarP(&privateKeyFileName, privateKeyFileNameFlag, "f", "", "filename of the private key file")
Expand All @@ -84,38 +77,40 @@ func init() {
startCmd.Flags().StringVarP(&clientID, clientIDFlag, "c", "", "client id for the private key")
startCmd.Flags().BoolVarP(&verboseMode, verboseModeFlag, "v", false, "enable verbose mode")
startCmd.Flags().IntVarP(&port, portFlag, "p", 3000, "port to start server")
startCmd.Flags().BoolVarP(&listen, listenFlag, "l", false, "start Webhook tunnel")
startCmd.Flags().BoolVarP(&listen, listenFlag, "l", false, "enable webhook events listening")
startCmd.Flags().StringVar(&events, eventsFlag, "", "subscribe for event types")
startCmd.Flags().BoolVar(&logHeaders, showWebhookHeader, false, "show webhook request headers.")

}

func run() {
var userCredentialsCh chan runtime.UserCredentials
func startProxy() {
cfg, signerConfigs := initializeSignerConfig()
ll := logger.New(cfg.VerboseMode)
r := runtime.NewRuntime(cfg, signerConfigs, ll)
if err := r.Run(); err == nil {
ll.PrintF("Starting to listen on port %d\n", port)
} else {
panic("Fail to start http proxy: " + err.Error())
}
var tunnels *runtime.Tunnels

cfg, signerConfigs := initializeSignerConfig(logger.New(false))
l := logger.New(cfg.VerboseMode)
if listen {
userCredentialsCh = make(chan runtime.UserCredentials)
tunnels = runtime.CreateTunnels(l, strings.Split(events, ","), cfg.PullDelay, func(credentials runtime.UserCredentials) runtime.ApiClient {
return runtime.NewClient("http://localhost:"+strconv.Itoa(cfg.Port), credentials, cfg.DefaultTimeout)
}, cfg.LogHeaders)
go tunnels.Start(userCredentialsCh)
proxyAddress := fmt.Sprintf("http://localhost:%d", port)
tunnels = runtime.CreateTunnels(ll, strings.Split(events, ","), time.Second, proxyAddress,
func(credentials runtime.UserCredentials) runtime.ApiClient {
return runtime.NewClient(proxyAddress, credentials, time.Second*15)
}, logHeaders)
go tunnels.Start(true)
}
r := runtime.NewRuntime(cfg, signerConfigs, userCredentialsCh, l)
go r.Run()
l.PrintF("Starting to listen on port %d\n", port)

c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
<-c
if userCredentialsCh != nil {
close(userCredentialsCh)
if tunnels != nil {
tunnels.Stop()
}

}

func initializeSignerConfig(l logger.Logger) (*config.Config, map[string]runtime.SignerConfig) {
func initializeSignerConfig() (*config.Config, map[string]runtime.SignerConfig) {
flagConfig := config.KeyConfig{
ClientID: clientID,
BaseConfig: config.BaseConfig{
Expand Down Expand Up @@ -167,13 +162,14 @@ func initializeSignerConfig(l logger.Logger) (*config.Config, map[string]runtime
}
}

l.PrintLn("Private keys initialised:")
fmt.Println("Private keys initialised:")
for i := range keyConfigs {
l.PrintF(" Key %d for clientID %s:\n", i+1, keyConfigs[i].ClientID)
l.PrintF(" - Using private key file %s for HTTP Signatures\n", keyConfigs[i].PrivateKeyFileName)
l.PrintF(" - Using keyID %s for HTTP Signatures\n", keyConfigs[i].KeyID)
l.PrintF(" - Piping all requests to %s\n", keyConfigs[i].BaseUrl)
fmt.Printf(" Key %d for clientID %s:\n", i+1, keyConfigs[i].ClientID)
fmt.Printf(" - Using private key file %s for HTTP Signatures\n", keyConfigs[i].PrivateKeyFileName)
fmt.Printf(" - Using keyID %s for HTTP Signatures\n", keyConfigs[i].KeyID)
fmt.Printf(" - Piping all requests to %s\n", keyConfigs[i].BaseUrl)
}

return cfg, signerConfigs
}

Expand Down
10 changes: 8 additions & 2 deletions service/signer/logger/logger.go → service/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,22 @@ package logger

import (
"fmt"
"net/http"
)

var HttpProxyNoLogging = http.CanonicalHeaderKey("X-HTTP-PROXY-NO-LOGGING")

type Logger interface {
Log(message string)
LogF(format string, a ...interface{})

PrintF(format string, a ...interface{})
Print(message string)
PrintLn(message string)
}

var NoVerboseLogger = New(false)

func New(verboseMode bool) *ConsoleLogger {
return &ConsoleLogger{verboseMode: verboseMode}
}
Expand All @@ -50,12 +56,12 @@ func (l *ConsoleLogger) PrintLn(message string) {

func (l *ConsoleLogger) LogF(format string, a ...interface{}) {
if l.verboseMode {
fmt.Printf(format, a...)
fmt.Printf(format+"\n", a...)
}
}

func (l *ConsoleLogger) Log(message string) {
if l.verboseMode {
fmt.Print(message)
fmt.Print(message + "\n")
}
}
3 changes: 3 additions & 0 deletions service/runtime/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"time"

"github.com/pkg/errors"
"github.com/upvestco/httpsignature-proxy/service/logger"
"github.com/valyala/fastjson"
)

Expand Down Expand Up @@ -66,6 +67,7 @@ func (e *apiClient) Authorise(ctx context.Context, scopes string) error {
}
req.Header.Add("Upvest-Client-Id", e.usersCredentials.ClientID)
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add(logger.HttpProxyNoLogging, "true")

code, body, err := e.io(req)

Expand Down Expand Up @@ -236,4 +238,5 @@ func (e *apiClient) addHeaders(req *http.Request) {
req.Header.Add(upvestClientID, e.usersCredentials.ClientID)
req.Header.Add("Authorization", "Bearer "+e.accessToken)
req.Header.Add("Content-Type", "application/json")
req.Header.Add(logger.HttpProxyNoLogging, "true")
}
Loading

0 comments on commit 6431135

Please sign in to comment.