Connect backend refactor (#801)

* Move connect backend code to its own package
* Move errors into the connect package
* Add NewBackend func
This commit is contained in:
Dan Sosedoff
2025-11-11 10:19:05 -08:00
committed by GitHub
parent 266a516076
commit 70f62feec8
6 changed files with 133 additions and 117 deletions

View File

@@ -15,6 +15,7 @@ import (
"github.com/sosedoff/pgweb/pkg/bookmarks"
"github.com/sosedoff/pgweb/pkg/client"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connect"
"github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/metrics"
"github.com/sosedoff/pgweb/pkg/queries"
@@ -92,18 +93,18 @@ func GetSessions(c *gin.Context) {
// ConnectWithBackend creates a new connection based on backend resource
func ConnectWithBackend(c *gin.Context) {
// Setup a new backend client
backend := Backend{
Endpoint: command.Opts.ConnectBackend,
Token: command.Opts.ConnectToken,
PassHeaders: strings.Split(command.Opts.ConnectHeaders, ","),
backend := connect.NewBackend(command.Opts.ConnectBackend, command.Opts.ConnectToken)
backend.SetLogger(logger)
if command.Opts.ConnectHeaders != "" {
backend.SetPassHeaders(strings.Split(command.Opts.ConnectHeaders, ","))
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
// Fetch connection credentials
cred, err := backend.FetchCredential(ctx, c.Param("resource"), c)
cred, err := backend.FetchCredential(ctx, c.Param("resource"), c.Request.Header)
if err != nil {
badRequest(c, err)
return

View File

@@ -1,87 +0,0 @@
package api
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Backend represents a third party configuration source
type Backend struct {
Endpoint string
Token string
PassHeaders []string
}
// BackendRequest represents a payload sent to the third-party source
type BackendRequest struct {
Resource string `json:"resource"`
Token string `json:"token"`
Headers map[string]string `json:"headers"`
}
// BackendCredential represents the third-party response
type BackendCredential struct {
DatabaseURL string `json:"database_url"`
}
// FetchCredential sends an authentication request to a third-party service
func (be Backend) FetchCredential(ctx context.Context, resource string, c *gin.Context) (*BackendCredential, error) {
logger.WithField("resource", resource).Debug("fetching database credential")
request := BackendRequest{
Resource: resource,
Token: be.Token,
Headers: map[string]string{},
}
// Pass white-listed client headers to the backend request
for _, name := range be.PassHeaders {
request.Headers[strings.ToLower(name)] = c.Request.Header.Get(name)
}
body, err := json.Marshal(request)
if err != nil {
logger.WithField("resource", resource).Error("backend request serialization error:", err)
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, be.Endpoint, bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("content-type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
logger.WithField("resource", resource).Error("backend credential fetch failed:", err)
return nil, errBackendConnectError
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("backend credential fetch received HTTP status code %v", resp.StatusCode)
logger.
WithField("resource", resource).
WithField("status", resp.StatusCode).
Error(err)
return nil, err
}
cred := &BackendCredential{}
if err := json.NewDecoder(resp.Body).Decode(cred); err != nil {
return nil, err
}
if cred.DatabaseURL == "" {
return nil, errConnStringRequired
}
return cred, nil
}

View File

@@ -1,181 +0,0 @@
package api
import (
"context"
"errors"
"net"
"net/http"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestBackendFetchCredential(t *testing.T) {
examples := []struct {
name string
backend Backend
resourceName string
cred *BackendCredential
reqCtx *gin.Context
ctx func() (context.Context, context.CancelFunc)
err error
}{
{
name: "Bad auth token",
backend: Backend{Endpoint: "http://localhost:5555/unauthorized"},
err: errors.New("backend credential fetch received HTTP status code 401"),
},
{
name: "Backend timeout",
backend: Backend{Endpoint: "http://localhost:5555/timeout"},
ctx: func() (context.Context, context.CancelFunc) {
return context.WithTimeout(context.Background(), time.Millisecond*100)
},
err: errors.New("Unable to connect to the auth backend"),
},
{
name: "Empty response",
backend: Backend{Endpoint: "http://localhost:5555/empty-response"},
err: errors.New("Connection string is required"),
},
{
name: "Missing header",
backend: Backend{Endpoint: "http://localhost:5555/pass-header"},
err: errors.New("backend credential fetch received HTTP status code 400"),
},
{
name: "Require header",
backend: Backend{
Endpoint: "http://localhost:5555/pass-header",
PassHeaders: []string{"x-foo"},
},
reqCtx: &gin.Context{
Request: &http.Request{
Header: http.Header{
"X-Foo": []string{"bar"},
},
},
},
cred: &BackendCredential{DatabaseURL: "postgres://hostname/bar"},
},
{
name: "Success",
backend: Backend{Endpoint: "http://localhost:5555/success"},
cred: &BackendCredential{DatabaseURL: "postgres://hostname/dbname"},
},
}
srvCtx, srvCancel := context.WithTimeout(context.Background(), time.Minute)
defer srvCancel()
startTestBackend(srvCtx, "localhost:5555")
for _, ex := range examples {
t.Run(ex.name, func(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
if ex.ctx != nil {
ctx, cancel = ex.ctx()
}
defer cancel()
reqCtx := ex.reqCtx
if reqCtx == nil {
reqCtx = &gin.Context{
Request: &http.Request{},
}
}
cred, err := ex.backend.FetchCredential(ctx, ex.resourceName, reqCtx)
assert.Equal(t, ex.err, err)
assert.Equal(t, ex.cred, cred)
})
}
}
func startTestBackend(ctx context.Context, listenAddr string) {
router := gin.New()
router.Use(func(c *gin.Context) {
if c.GetHeader("content-type") != "application/json" {
c.AbortWithStatus(http.StatusBadRequest)
}
})
router.POST("/unauthorized", func(c *gin.Context) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
})
router.POST("/timeout", func(c *gin.Context) {
time.Sleep(time.Second)
c.JSON(http.StatusOK, gin.H{})
})
router.POST("/empty-response", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
})
router.POST("/pass-header", func(c *gin.Context) {
req := BackendRequest{}
if err := c.BindJSON(&req); err != nil {
panic(err)
}
header := req.Headers["x-foo"]
if header == "" {
c.AbortWithStatus(http.StatusBadRequest)
return
}
c.JSON(http.StatusOK, gin.H{
"database_url": "postgres://hostname/" + header,
})
})
router.POST("/success", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"database_url": "postgres://hostname/dbname",
})
})
server := &http.Server{Addr: listenAddr, Handler: router}
mustStartServer(server)
go func() {
<-ctx.Done()
if err := server.Shutdown(context.Background()); err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
}
func mustStartServer(server *http.Server) {
go func() {
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
if err := waitForServer(server.Addr, 5); err != nil {
panic(err)
}
}
func waitForServer(addr string, n int) error {
var lastErr error
for i := 0; i < n; i++ {
conn, err := net.Dial("tcp", addr)
if err == nil {
conn.Close()
return nil
}
lastErr = err
time.Sleep(time.Millisecond * 100)
}
return lastErr
}

View File

@@ -7,12 +7,10 @@ import (
var (
errNotConnected = errors.New("Not connected")
errNotPermitted = errors.New("Not permitted")
errConnStringRequired = errors.New("Connection string is required")
errInvalidConnString = errors.New("Invalid connection string")
errSessionRequired = errors.New("Session ID is required")
errSessionLocked = errors.New("Session is locked")
errURLRequired = errors.New("URL parameter is required")
errQueryRequired = errors.New("Query parameter is required")
errDatabaseNameRequired = errors.New("Database name is required")
errBackendConnectError = errors.New("Unable to connect to the auth backend")
)