Skip to content

Commit

Permalink
feat(http): add http forwarder
Browse files Browse the repository at this point in the history
  • Loading branch information
Darkness4 committed Dec 1, 2023
1 parent 092f4fd commit 41a86a0
Show file tree
Hide file tree
Showing 10 changed files with 210 additions and 71 deletions.
30 changes: 21 additions & 9 deletions cmd/dpsproxy-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ var (
httpListenAddress string
keysDir string

insecure bool
insecure bool
anonymous bool

dbFile string
)
Expand Down Expand Up @@ -193,6 +194,12 @@ var app = &cli.App{
Destination: &insecure,
Usage: "Allow CSRF tokens in insecure connections.",
},
&cli.BoolFlag{
Name: "anonymous",
Value: false,
Destination: &anonymous,
Usage: "Allow anonymous login.",
},
},
Suggest: true,
Action: func(cCtx *cli.Context) error {
Expand Down Expand Up @@ -319,20 +326,25 @@ var app = &cli.App{
}
r.Get("/*", renderFn)

server := proxyssh.NewServer(
sshListenAddress,
&config,
jwt.Secret(jwtSecret),
routes,
publicDomain,
anonymous,
)

go func() {
server := proxyssh.NewServer(
sshListenAddress,
&config,
jwt.Secret(jwtSecret),
routes,
publicDomain,
)
err := server.Serve(ctx)
log.Fatal().Err(err).Msg("ssh crashed")
}()

log.Info().Msg("listening")
return http.ListenAndServe(httpListenAddress, csrf.Protect(key, csrf.Secure(!insecure))(r))
return http.ListenAndServe(
httpListenAddress,
server.ForwardHTTP(csrf.Protect(key, csrf.Secure(!insecure))(r)),
)
},
}

Expand Down
5 changes: 4 additions & 1 deletion database/queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ UPDATE nonces SET expiration = ? WHERE nonce = ? RETURNING nonce;

---

-- name: GetRoute :one
-- name: GetRouteByUserAddress :one
SELECT * FROM routes WHERE user_address = ? LIMIT 1;

-- name: GetRoute :one
SELECT * FROM routes WHERE route = ? LIMIT 1;

-- name: SetRoute :one
UPDATE routes SET route = ?, port = ? WHERE user_address = ? RETURNING route;

Expand Down
15 changes: 13 additions & 2 deletions database/queries.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 27 additions & 32 deletions database/route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,37 +5,16 @@ import (
"context"
"database/sql"
"errors"
"math/rand"

"github.com/deepsquare-io/proxy/database"
"github.com/deepsquare-io/proxy/utils"
)

const subdomainLength = 8

func generateSubdomain() string {
// Define the character set for the subdomain
charSet := "abcdefghijklmnopqrstuvwxyz0123456789"

// Generate a random subdomain of the specified length
subdomain := make([]byte, subdomainLength)
for i := range subdomain {
subdomain[i] = charSet[rand.Intn(len(charSet))]
}

return string(subdomain)
}

const minPort = 30001
const maxPort = 65535

func generateRandomPort() int64 {
return rand.Int63n(maxPort-minPort+1) + minPort
}

// Repository defines the route methods.
type Repository interface {
GenerateRoute(ctx context.Context, userAddress string) (route string, port int64, err error)
Get(ctx context.Context, userAddress string) (route string, port int64, err error)
GetByUserAddress(ctx context.Context, userAddress string) (database.Route, error)
Get(ctx context.Context, route string) (database.Route, error)
Count(ctx context.Context) (int64, error)
}

Expand All @@ -54,7 +33,7 @@ func (r *repository) findUnusedPort(ctx context.Context) (int64, error) {
var port int64

for {
port = generateRandomPort()
port = utils.GenerateRandomPort()

used, err := r.Queries.IsPortUsed(ctx, port)
if err != nil {
Expand All @@ -73,7 +52,7 @@ func (r *repository) GenerateRoute(
ctx context.Context,
userAddress string,
) (route string, port int64, err error) {
subdomain := generateSubdomain()
subdomain := utils.GenerateSubdomain()
port, err = r.findUnusedPort(ctx)
if err != nil {
return "", 0, err
Expand Down Expand Up @@ -108,20 +87,36 @@ func (r *repository) set(
return err
}

// GetByUserAddress the value of the route of a user from the database.
func (r *repository) GetByUserAddress(
ctx context.Context,
userAddress string,
) (database.Route, error) {
resp, err := r.Queries.GetRouteByUserAddress(ctx, userAddress)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return database.Route{}, nil
}
return database.Route{}, err
}
return resp, nil
}

// Get the value of the route of a user from the database.
func (r *repository) Get(
ctx context.Context,
userAddress string,
) (route string, port int64, err error) {
resp, err := r.Queries.GetRoute(ctx, userAddress)
route string,
) (database.Route, error) {
resp, err := r.Queries.GetRoute(ctx, route)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", 0, nil
return database.Route{}, nil
}
return "", 0, err
return database.Route{}, err
}
return resp.Route, resp.Port, nil
return resp, nil
}

func (r *repository) Count(
ctx context.Context,
) (int64, error) {
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ require (
github.com/rs/zerolog v1.31.0
github.com/sqlc-dev/sqlc v1.23.0
github.com/urfave/cli/v2 v2.25.7
github.com/yhat/wsutil v0.0.0-20170731153501-1d66fa95c997
golang.org/x/crypto v0.16.0
golang.org/x/sync v0.5.0
)
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -713,6 +713,8 @@ github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCO
github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRTfdpNzjtPYqr8smhKouy9mxVdGPU=
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
github.com/yhat/wsutil v0.0.0-20170731153501-1d66fa95c997 h1:1+FQ4Ns+UZtUiQ4lP0sTCyKSQ0EXoiwAdHZB0Pd5t9Q=
github.com/yhat/wsutil v0.0.0-20170731153501-1d66fa95c997/go.mod h1:DIGbh/f5XMAessMV/uaIik81gkDVjUeQ9ApdaU7wRKE=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d h1:splanxYIlg+5LfHAM6xpdFEAYOk8iySO56hMFq6uLyA=
github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
Expand Down
8 changes: 5 additions & 3 deletions handler/route_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,13 @@ func GenerateRoute(
var route string
var port int64
if refresh {
route, port, err = routes.Get(r.Context(), rep.Address)
r, err := routes.GetByUserAddress(r.Context(), rep.Address)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
route = r.Route
port = r.Port
}
if route == "" {
route, port, err = routes.GenerateRoute(r.Context(), rep.Address)
Expand Down Expand Up @@ -139,12 +141,12 @@ func RetrieveRoute(
return
}

route, port, err := routes.Get(r.Context(), claims.UserID)
rr, err := routes.GetByUserAddress(r.Context(), claims.UserID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}

fmt.Fprint(w, formatResponse(publicDomain, route, port, token, claims.ExpiresAt.Time))
fmt.Fprint(w, formatResponse(publicDomain, rr.Route, rr.Port, token, claims.ExpiresAt.Time))
}
}
6 changes: 5 additions & 1 deletion ssh/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ import (
)

var primaryColor = lipgloss.Color("#9202de")
var borderStyle = lipgloss.NewStyle().Foreground(primaryColor).Padding(1)
var borderStyle = lipgloss.NewStyle().Foreground(primaryColor)
var cellStyle = lipgloss.NewStyle().PaddingRight(1).PaddingLeft(1)

func renderOutput(route string, domain string, port int64) string {
rows := [][]string{
Expand All @@ -21,6 +22,9 @@ func renderOutput(route string, domain string, port int64) string {
Border(lipgloss.NormalBorder()).
BorderStyle(borderStyle).
Headers("Protocol", "URL").
StyleFunc(func(row, col int) lipgloss.Style {
return cellStyle
}).
Rows(rows...).
Render() +
"\n"
Expand Down
Loading

0 comments on commit 41a86a0

Please sign in to comment.