Skip to content

Commit

Permalink
private sharing; caddy (#392); sdk refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelquigley committed Aug 30, 2023
1 parent d3c43c3 commit 7bc8976
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 112 deletions.
180 changes: 79 additions & 101 deletions cmd/zrok/sharePrivate.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,18 @@ package main
import (
"fmt"
tea "github.com/charmbracelet/bubbletea"
"github.com/go-openapi/runtime"
httptransport "github.com/go-openapi/runtime/client"
"github.com/openziti/zrok/endpoints"
"github.com/openziti/zrok/endpoints/proxy"
"github.com/openziti/zrok/endpoints/tcpTunnel"
"github.com/openziti/zrok/endpoints/udpTunnel"
"github.com/openziti/zrok/environment"
"github.com/openziti/zrok/rest_client_zrok"
"github.com/openziti/zrok/rest_client_zrok/share"
"github.com/openziti/zrok/rest_model_zrok"
"github.com/openziti/zrok/environment/env_core"
"github.com/openziti/zrok/sdk"
"github.com/openziti/zrok/tui"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"os"
"os/signal"
"strings"
"syscall"
)

Expand All @@ -44,7 +38,7 @@ func newSharePrivateCommand() *sharePrivateCommand {
}
command := &sharePrivateCommand{cmd: cmd}
cmd.Flags().StringArrayVar(&command.basicAuth, "basic-auth", []string{}, "Basic authentication users (<username:password>,...")
cmd.Flags().StringVar(&command.backendMode, "backend-mode", "proxy", "The backend mode {proxy, web, tcpTunnel, udpTunnel}")
cmd.Flags().StringVar(&command.backendMode, "backend-mode", "proxy", "The backend mode {proxy, web, tcpTunnel, udpTunnel, caddy}")
cmd.Flags().BoolVar(&command.headless, "headless", false, "Disable TUI and run headless")
cmd.Flags().BoolVar(&command.insecure, "insecure", false, "Enable insecure TLS certificate validation for <target>")
cmd.Run = command.run
Expand Down Expand Up @@ -74,69 +68,49 @@ func (cmd *sharePrivateCommand) run(_ *cobra.Command, args []string) {
case "udpTunnel":
target = args[0]

case "caddy":
target = args[0]

default:
tui.Error(fmt.Sprintf("invalid backend mode '%v'; expected {proxy, web, tcpTunnel}", cmd.backendMode), nil)
}

env, err := environment.LoadRoot()
root, err := environment.LoadRoot()
if err != nil {
if !panicInstead {
tui.Error("unable to load environment", err)
}
panic(err)
}

if !env.IsEnabled() {
if !root.IsEnabled() {
tui.Error("unable to load environment; did you 'zrok enable'?", nil)
}

zif, err := env.ZitiIdentityNamed(env.EnvironmentIdentityName())
zif, err := root.ZitiIdentityNamed(root.EnvironmentIdentityName())
if err != nil {
if !panicInstead {
tui.Error("unable to load ziti identity configuration", err)
}
panic(err)
}

zrok, err := env.Client()
if err != nil {
if !panicInstead {
tui.Error("unable to create zrok client", err)
}
panic(err)
}

auth := httptransport.APIKeyAuth("X-TOKEN", "header", env.Environment().Token)
req := share.NewShareParams()
req.Body = &rest_model_zrok.ShareRequest{
EnvZID: env.Environment().ZitiIdentity,
ShareMode: string(sdk.PrivateShareMode),
BackendMode: cmd.backendMode,
BackendProxyEndpoint: target,
AuthScheme: string(sdk.None),
req := &sdk.ShareRequest{
BackendMode: sdk.BackendMode(cmd.backendMode),
ShareMode: sdk.PrivateShareMode,
Auth: cmd.basicAuth,
Target: target,
}
if len(cmd.basicAuth) > 0 {
logrus.Infof("configuring basic auth")
req.Body.AuthScheme = string(sdk.Basic)
for _, pair := range cmd.basicAuth {
tokens := strings.Split(pair, ":")
if len(tokens) == 2 {
req.Body.AuthUsers = append(req.Body.AuthUsers, &rest_model_zrok.AuthUser{Username: strings.TrimSpace(tokens[0]), Password: strings.TrimSpace(tokens[1])})
} else {
panic(errors.Errorf("invalid username:password pair '%v'", pair))
}
}
}
resp, err := zrok.Share.Share(req, auth)
shr, err := sdk.CreateShare(root, req)
if err != nil {
if !panicInstead {
tui.Error("unable to create share", err)
}
panic(err)
}

shareDescription := fmt.Sprintf("access your share with: %v", tui.Code.Render(fmt.Sprintf("zrok access private %v", resp.Payload.ShrToken)))
mdl := newShareModel(resp.Payload.ShrToken, []string{shareDescription}, sdk.PrivateShareMode, sdk.BackendMode(cmd.backendMode))
shareDescription := fmt.Sprintf("access your share with: %v", tui.Code.Render(fmt.Sprintf("zrok access private %v", shr.Token)))
mdl := newShareModel(shr.Token, []string{shareDescription}, sdk.PrivateShareMode, sdk.BackendMode(cmd.backendMode))
if !cmd.headless {
proxy.SetCaddyLoggingWriter(mdl)
}
Expand All @@ -145,57 +119,74 @@ func (cmd *sharePrivateCommand) run(_ *cobra.Command, args []string) {
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cmd.destroy(env.Environment().ZitiIdentity, resp.Payload.ShrToken, zrok, auth)
cmd.shutdown(root, shr)
os.Exit(0)
}()

requestsChan := make(chan *endpoints.Request, 1024)
requests := make(chan *endpoints.Request, 1024)

switch cmd.backendMode {
case "proxy":
cfg := &proxy.BackendConfig{
IdentityPath: zif,
EndpointAddress: target,
ShrToken: resp.Payload.ShrToken,
ShrToken: shr.Token,
Insecure: cmd.insecure,
RequestsChan: requestsChan,
Requests: requests,
}
_, err = cmd.proxyBackendMode(cfg)

be, err := proxy.NewBackend(cfg)
if err != nil {
if !panicInstead {
tui.Error("unable to create proxy backend handler", err)
tui.Error("error creating proxy backend", err)
}
panic(err)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running http proxy backend: %v", err)
}
}()

case "web":
cfg := &proxy.CaddyWebBackendConfig{
IdentityPath: zif,
WebRoot: target,
ShrToken: resp.Payload.ShrToken,
Requests: requestsChan,
ShrToken: shr.Token,
Requests: requests,
}
_, err = cmd.webBackendMode(cfg)

be, err := proxy.NewCaddyWebBackend(cfg)
if err != nil {
if !panicInstead {
tui.Error("unable to create web backend handler", err)
}
panic(err)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running http web backend: %v", err)
}
}()

case "tcpTunnel":
cfg := &tcpTunnel.BackendConfig{
IdentityPath: zif,
EndpointAddress: target,
ShrToken: resp.Payload.ShrToken,
RequestsChan: requestsChan,
ShrToken: shr.Token,
RequestsChan: requests,
}

be, err := tcpTunnel.NewBackend(cfg)
if err != nil {
if !panicInstead {
tui.Error("unable to create tcpTunnel backend", err)
}
panic(err)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running tcpTunnel backend: %v", err)
Expand All @@ -206,31 +197,54 @@ func (cmd *sharePrivateCommand) run(_ *cobra.Command, args []string) {
cfg := &udpTunnel.BackendConfig{
IdentityPath: zif,
EndpointAddress: target,
ShrToken: resp.Payload.ShrToken,
RequestsChan: requestsChan,
ShrToken: shr.Token,
RequestsChan: requests,
}

be, err := udpTunnel.NewBackend(cfg)
if err != nil {
if !panicInstead {
tui.Error("unable to create udpTunnel backend", err)
}
panic(err)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running udpTunnel backend: %v", err)
}
}()

case "caddy":
cfg := &proxy.CaddyfileBackendConfig{
CaddyfilePath: target,
Shr: shr,
Requests: requests,
}

be, err := proxy.NewCaddyfileBackend(cfg)
if err != nil {
if !panicInstead {
tui.Error("unable to create caddy backend", err)
}
panic(err)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running caddy backend: %v", err)
}
}()

default:
tui.Error("invalid backend mode", nil)
}

if cmd.headless {
logrus.Infof("allow other to access your share with the following command:\nzrok access private %v", resp.Payload.ShrToken)
logrus.Infof("allow other to access your share with the following command:\nzrok access private %v", shr.Token)
for {
select {
case req := <-requestsChan:
case req := <-requests:
logrus.Infof("%v -> %v %v", req.RemoteAddr, req.Method, req.Path)
}
}
Expand All @@ -243,7 +257,7 @@ func (cmd *sharePrivateCommand) run(_ *cobra.Command, args []string) {
go func() {
for {
select {
case req := <-requestsChan:
case req := <-requests:
prg.Send(req)
}
}
Expand All @@ -253,51 +267,15 @@ func (cmd *sharePrivateCommand) run(_ *cobra.Command, args []string) {
tui.Error("An error occurred", err)
}

close(requestsChan)
cmd.destroy(env.Environment().ZitiIdentity, resp.Payload.ShrToken, zrok, auth)
}
}

func (cmd *sharePrivateCommand) proxyBackendMode(cfg *proxy.BackendConfig) (endpoints.RequestHandler, error) {
be, err := proxy.NewBackend(cfg)
if err != nil {
return nil, errors.Wrap(err, "error creating http proxy backend")
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running http proxy backend: %v", err)
}
}()

return be, nil
}

func (cmd *sharePrivateCommand) webBackendMode(cfg *proxy.CaddyWebBackendConfig) (endpoints.RequestHandler, error) {
be, err := proxy.NewCaddyWebBackend(cfg)
if err != nil {
return nil, errors.Wrap(err, "error creating http web backend")
close(requests)
cmd.shutdown(root, shr)
}

go func() {
if err := be.Run(); err != nil {
logrus.Errorf("error running http web backend: %v", err)
}
}()

return be, nil
}

func (cmd *sharePrivateCommand) destroy(id string, shrToken string, zrok *rest_client_zrok.Zrok, auth runtime.ClientAuthInfoWriter) {
logrus.Debugf("shutting down '%v'", shrToken)
req := share.NewUnshareParams()
req.Body = &rest_model_zrok.UnshareRequest{
EnvZID: id,
ShrToken: shrToken,
}
if _, err := zrok.Share.Unshare(req, auth); err == nil {
logrus.Debugf("shutdown complete")
} else {
logrus.Errorf("error shutting down: %v", err)
func (cmd *sharePrivateCommand) shutdown(root env_core.Root, shr *sdk.Share) {
logrus.Debugf("shutting down '%v'", shr.Token)
if err := sdk.DeleteShare(root, shr); err != nil {
logrus.Errorf("error shutting down '%v': %v", shr.Token, err)
}
logrus.Debugf("shutdown complete")
}
14 changes: 7 additions & 7 deletions cmd/zrok/sharePublic.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,19 +71,19 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) {
tui.Error(fmt.Sprintf("invalid backend mode '%v'; expected {proxy, web}", cmd.backendMode), nil)
}

env, err := environment.LoadRoot()
root, err := environment.LoadRoot()
if err != nil {
if !panicInstead {
tui.Error("unable to load environment", err)
}
panic(err)
}

if !env.IsEnabled() {
if !root.IsEnabled() {
tui.Error("unable to load environment; did you 'zrok enable'?", nil)
}

zif, err := env.ZitiIdentityNamed(env.EnvironmentIdentityName())
zif, err := root.ZitiIdentityNamed(root.EnvironmentIdentityName())
if err != nil {
if !panicInstead {
tui.Error("unable to access ziti identity file", err)
Expand All @@ -98,7 +98,7 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) {
Auth: cmd.basicAuth,
Target: target,
}
shr, err := sdk.CreateShare(env, req)
shr, err := sdk.CreateShare(root, req)
if err != nil {
if !panicInstead {
tui.Error("unable to create share", err)
Expand All @@ -115,7 +115,7 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) {
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cmd.shutdown(env, shr)
cmd.shutdown(root, shr)
os.Exit(0)
}()

Expand All @@ -128,7 +128,7 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) {
EndpointAddress: target,
ShrToken: shr.Token,
Insecure: cmd.insecure,
RequestsChan: requests,
Requests: requests,
}

be, err := proxy.NewBackend(cfg)
Expand Down Expand Up @@ -220,7 +220,7 @@ func (cmd *sharePublicCommand) run(_ *cobra.Command, args []string) {
}

close(requests)
cmd.shutdown(env, shr)
cmd.shutdown(root, shr)
}
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/zrok/shareReserved.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ func (cmd *shareReservedCommand) run(_ *cobra.Command, args []string) {
EndpointAddress: target,
ShrToken: shrToken,
Insecure: cmd.insecure,
RequestsChan: requestsChan,
Requests: requestsChan,
}
_, err := cmd.proxyBackendMode(cfg)
if err != nil {
Expand Down
Loading

0 comments on commit 7bc8976

Please sign in to comment.