Skip to content

Commit

Permalink
print helpful error when IP address not allowed to access psql (#139)
Browse files Browse the repository at this point in the history
  • Loading branch information
kitemongerer authored Nov 22, 2024
1 parent 3be9b13 commit 0f5ccfa
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion pkg/tui/views/psql.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package views
import (
"context"
"fmt"
"io"
"net"
"net/http"
"os/exec"

tea "github.com/charmbracelet/bubbletea"
Expand Down Expand Up @@ -76,14 +79,62 @@ func loadDataPSQL(ctx context.Context, in *PSQLInput) (*exec.Cmd, error) {
return nil, err
}

connectionInfo, err := postgres.NewRepo(c).GetPostgresConnectionInfo(ctx, in.PostgresID)
pgc := postgres.NewRepo(c)

pg, err := pgc.GetPostgres(ctx, in.PostgresID)
if err != nil {
return nil, err
}

// only check access if error is nil in case ipify is down
userIP, ok := getUserIP()
if ok {
hasAccess, err := hasAccessToPostgres(pg, userIP)
if err != nil {
return nil, err
}

if !hasAccess {
return nil, fmt.Errorf("IP address (%s) not in allow list for %s", userIP, pg.Name)
}
}

connectionInfo, err := pgc.GetPostgresConnectionInfo(ctx, in.PostgresID)
if err != nil {
return nil, err
}

return exec.Command(string(in.Tool), connectionInfo.ExternalConnectionString), nil
}

func hasAccessToPostgres(pg *client.PostgresDetail, userIP net.IP) (bool, error) {
for _, allowedIPs := range pg.IpAllowList {
_, cidr, err := net.ParseCIDR(allowedIPs.CidrBlock)
if err != nil {
return false, err
}

if cidr.Contains(userIP) {
return true, nil
}
}
return false, nil
}

func getUserIP() (net.IP, bool) {
userIPRes, err := http.Get("https://api.ipify.org")
if err != nil {
return nil, false
}

userIPBytes, err := io.ReadAll(userIPRes.Body)
if err != nil {
return nil, false
}

return net.ParseIP(string(userIPBytes)), true
}

func (v *PSQLView) Init() tea.Cmd {
if v.postgresTable != nil {
return v.postgresTable.Init()
Expand Down

0 comments on commit 0f5ccfa

Please sign in to comment.