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 25, 2024
1 parent 9c82e79 commit 3ec2d8f
Show file tree
Hide file tree
Showing 6 changed files with 59 additions and 85 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,8 @@ Flags:
-i, --key-id string key id for specified private key
-c, --client-id string client id for specified private key
-l, --listen create webhook events tunel and log incomming events to console
-e --events strings only with -l flag. Log only events of the types specified
--show-webhook-headers only with -l flag. Show http headers come with webhook events
-e --events strings only with -l flag. Log only events of the specified types
--show-webhook-headers only with -l flag. Show http headers coming with webhook events

Global Flags:
--config string config file (default is $HOME/.httpsignature-proxy.yaml)
Expand Down
24 changes: 16 additions & 8 deletions cmd/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,29 +88,37 @@ func init() {
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 userCredentialsCh chan runtime.UserCredentials

var tunnels *runtime.Tunnels
if listen {
userCredentialsCh = make(chan runtime.UserCredentials)
proxyAddress := fmt.Sprintf("http://localhost:%d", port)
tunnels = runtime.CreateTunnels(ll, events, proxyAddress,
func(credentials runtime.UserCredentials) runtime.ApiClient {
return runtime.NewClient(proxyAddress, credentials, cfg.DefaultTimeout)
}, logHeaders)
go tunnels.Start(true)
}

proxy := runtime.NewProxy(cfg, signerConfigs, userCredentialsCh, ll)
if err := proxy.Run(); err == nil {
ll.PrintF("Starting to listen on port %d\n", port)
} else {
panic("Fail to start http proxy: " + err.Error())
}
if tunnels != nil {
go tunnels.Start(userCredentialsCh)
}

ll.PrintLn("Press CTRL-C to exit")
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGTERM, syscall.SIGINT)
<-c

if tunnels != nil {
close(userCredentialsCh)
tunnels.Stop()
}

}

func initializeSignerConfig() (*config.Config, map[string]runtime.SignerConfig) {
Expand Down
33 changes: 14 additions & 19 deletions service/runtime/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,20 @@ var (
)

type Handler struct {
signerConfigs map[string]SignerConfig
cfg *config.Config
requestSigner request.Signer
log logger.Logger
currentUserCredentials UserCredentials
signerConfigs map[string]SignerConfig
cfg *config.Config
requestSigner request.Signer
log logger.Logger
userCredentialsCh chan UserCredentials
}

func newHandler(cfg *config.Config, signerConfigs map[string]SignerConfig, log logger.Logger) *Handler {
func newHandler(cfg *config.Config, signerConfigs map[string]SignerConfig, userCredentialsCh chan UserCredentials, log logger.Logger) *Handler {
return &Handler{
cfg: cfg,
log: log,
requestSigner: request.New(log),
signerConfigs: signerConfigs,
cfg: cfg,
log: log,
requestSigner: request.New(log),
signerConfigs: signerConfigs,
userCredentialsCh: userCredentialsCh,
}
}

Expand Down Expand Up @@ -183,22 +184,16 @@ func (h *Handler) getClientIDFromBody(req *http.Request) (string, error) {
}

func (h *Handler) ServeHTTP(rw http.ResponseWriter, inReq *http.Request) {
path := inReq.URL.Path
if path == "/proxy-pass" && inReq.Method == http.MethodGet {
data, _ := json.Marshal(h.currentUserCredentials)
h.writeResponse(rw, http.StatusAccepted, nil, data)
return
}
ll := h.log
if len(inReq.Header.Get(logger.HttpProxyNoLogging)) > 0 {
ll = logger.NoVerboseLogger
}
requestBody := h.proxy(rw, inReq, ll)

path := inReq.URL.Path
if path == tokenEndpoint && requestBody != nil {
uc := h.parseAuthTokenBody(requestBody)
if !uc.Empty() {
h.currentUserCredentials = uc
if !uc.Empty() && h.userCredentialsCh != nil {
h.userCredentialsCh <- uc
}
}
}
Expand Down
26 changes: 14 additions & 12 deletions service/runtime/runtime.go → service/runtime/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,33 +27,35 @@ import (
"github.com/upvestco/httpsignature-proxy/service/signer/schema"
)

type Runtime struct {
cfg *config.Config
signerConfigs map[string]SignerConfig
logger logger.Logger
server *http.Server
type Proxy struct {
cfg *config.Config
signerConfigs map[string]SignerConfig
logger logger.Logger
server *http.Server
userCredentialsCh chan UserCredentials
}

type SignerConfig struct {
SignBuilder schema.SigningSchemeBuilder
KeyConfig config.BaseConfig
}

func NewRuntime(cfg *config.Config, signerConfigs map[string]SignerConfig, logger logger.Logger) Runtime {
return Runtime{
cfg: cfg,
logger: logger,
signerConfigs: signerConfigs,
func NewProxy(cfg *config.Config, signerConfigs map[string]SignerConfig, userCredentialsCh chan UserCredentials, logger logger.Logger) Proxy {
return Proxy{
cfg: cfg,
logger: logger,
signerConfigs: signerConfigs,
userCredentialsCh: userCredentialsCh,
}
}

func (r *Runtime) Run() error {
func (r *Proxy) Run() error {
addr := net.JoinHostPort("localhost", fmt.Sprintf("%d", r.cfg.Port))
listener, err := net.Listen("tcp", addr)
if err != nil {
return errors.Wrap(err, "Listen")
}
handler := newHandler(r.cfg, r.signerConfigs, r.logger)
handler := newHandler(r.cfg, r.signerConfigs, r.userCredentialsCh, r.logger)
r.server = &http.Server{
Handler: handler,
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,16 +56,16 @@ qFs3oIGIa4fr1C7SXmMyCohmJznOH3kGu73fV6GJkdc=
)

func TestRuntime_Run(t *testing.T) {
suite.Run(t, &TestRuntimeSuite{})
suite.Run(t, &TestProxySuite{})
}

type TestRuntimeSuite struct {
type TestProxySuite struct {
suite.Suite
testServ *testService
clientID uuid.UUID
}

func (s *TestRuntimeSuite) SetupSuite() {
func (s *TestProxySuite) SetupSuite() {
s.clientID = uuid.New()
cfg := &config.Config{
Port: runtimePort,
Expand All @@ -84,15 +84,15 @@ func (s *TestRuntimeSuite) SetupSuite() {
},
}
s.setupTestService()
s.setupRuntime(cfg)
s.setupProxy(cfg)
}

func (s *TestRuntimeSuite) setupTestService() {
func (s *TestProxySuite) setupTestService() {
s.testServ = &testService{}
s.testServ.Start(s.T())
}

func (s *TestRuntimeSuite) setupRuntime(cfg *config.Config) {
func (s *TestProxySuite) setupProxy(cfg *config.Config) {
signerConfigs := make(map[string]SignerConfig)
for i := range cfg.KeyConfigs {
privateSchemeBuilder, err := signer.NewLocalPrivateSchemeBuilderFromSeed(privateTestKey, &cfg.KeyConfigs[i])
Expand All @@ -102,12 +102,12 @@ func (s *TestRuntimeSuite) setupRuntime(cfg *config.Config) {
KeyConfig: cfg.KeyConfigs[i].BaseConfig,
}
}
r := NewRuntime(cfg, signerConfigs, logger.New(false))
r := NewProxy(cfg, signerConfigs, nil, logger.New(false))
require.NoError(s.T(), r.Run())
time.Sleep(1 * time.Second)
}

func (s *TestRuntimeSuite) Test_RuntimeRun() {
func (s *TestProxySuite) Test_ProxyRun() {
url := fmt.Sprintf("http://localhost:%d/%s", runtimePort, "endpoint?param=val")
pl := []byte("This is the body")
body := bytes.NewBuffer(pl)
Expand Down
41 changes: 5 additions & 36 deletions service/runtime/tunnels.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ import (
"encoding/json"
"io"
"net/http"
"os"
"sync"
"syscall"
"time"

"github.com/pkg/errors"
Expand Down Expand Up @@ -90,26 +88,17 @@ func AskForUserCredentials(proxyAddress string) (UserCredentials, int, error) {
return uc, resp.StatusCode, nil
}

func (e *Tunnels) Start(showIntro bool) {
if showIntro {
e.logger.Print(cyan("############################################################\n"))
e.logger.Print(cyan("To start listening webhook events - send /auth/token request\n"))
e.logger.Print(cyan("############################################################\n"))
}
func (e *Tunnels) Start(userCredentialsCh chan UserCredentials) {
e.logger.Print(cyan("############################################################\n"))
e.logger.Print(cyan("To start listening webhook events - send /auth/token request\n"))
e.logger.Print(cyan("############################################################\n"))
ctx, cancel := context.WithCancel(context.Background())
e.cancel = cancel
tc := time.NewTicker(time.Millisecond * 500)
defer tc.Stop()
for {
select {
case <-ctx.Done():
return
case <-tc.C:
uc, proxyIsGone := e.readUserCredentials()
if proxyIsGone {
e.logger.Log("Proxy is gone. Exiting.")
os.Exit(0)
}
case uc := <-userCredentialsCh:
if uc.Empty() {
continue
}
Expand All @@ -131,26 +120,6 @@ func (e *Tunnels) Start(showIntro bool) {
}
}

var emptyUserCredentials = UserCredentials{}

func (e *Tunnels) readUserCredentials() (UserCredentials, bool) {
uc, code, err := AskForUserCredentials(e.proxyAddress)
if err != nil {
if errors.Is(err, syscall.ECONNREFUSED) {
return emptyUserCredentials, true
}
e.logger.Log(err.Error())
return emptyUserCredentials, false
}
if code != http.StatusAccepted {
return emptyUserCredentials, false
}
if uc.Empty() {
return emptyUserCredentials, false
}
return uc, false
}

type tunnelsMap struct {
tunnels map[string]*tunnel
lo *sync.Mutex
Expand Down

0 comments on commit 3ec2d8f

Please sign in to comment.