Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WebSocket handler for WebUI database sessions #49749

Merged
merged 20 commits into from
Dec 14, 2024
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
0e2468e
feat(web): add websocket handler for database webui sessions
gabrielcorado Dec 4, 2024
1a70cc5
refactor: move common structs into a separate package
gabrielcorado Dec 5, 2024
add121d
refactor(web): use ALPN local proxy to dial databases
gabrielcorado Dec 5, 2024
25f7e6e
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 5, 2024
7a6fd3b
feat(repl): add default registry
gabrielcorado Dec 5, 2024
bbb6b38
refactor(web): code review suggestions
gabrielcorado Dec 12, 2024
6ef2712
refactor: update repl config parameters
gabrielcorado Dec 12, 2024
0db0613
refactor: move default getter implementation
gabrielcorado Dec 13, 2024
b76c6f7
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 13, 2024
6237ed0
feat(web): add supports_interactive field on dbs
gabrielcorado Dec 13, 2024
46df432
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 13, 2024
010445e
refactor: code review suggestions
gabrielcorado Dec 13, 2024
9cb2b71
refactor: update database REPL interfaces
gabrielcorado Dec 13, 2024
4c67214
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 13, 2024
e773a87
chore(web): remove debug print
gabrielcorado Dec 13, 2024
b344080
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 13, 2024
df26468
feat: register postgres repl
gabrielcorado Dec 14, 2024
0e094b9
refactor(web): update MakeDatabase to receive access checker and inte…
gabrielcorado Dec 14, 2024
c05b558
Merge branch 'master' into gabrielcorado/pg-webui-handler
gabrielcorado Dec 14, 2024
a53effd
chore(web): remove unused function
gabrielcorado Dec 14, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions lib/client/alpn.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,14 +85,33 @@ type ALPNAuthTunnelConfig struct {
// RouteToDatabase contains the destination server that must receive the connection.
// Specific for database proxying.
RouteToDatabase proto.RouteToDatabase

// TLSCert specifies the TLS certificate used on the proxy connection.
TLSCert *tls.Certificate
}

func (c *ALPNAuthTunnelConfig) CheckAndSetDefaults(ctx context.Context) error {
if c.AuthClient == nil {
return trace.BadParameter("missing auth client")
}

if c.TLSCert == nil {
tlsCert, err := getUserCerts(ctx, c.AuthClient, c.MFAResponse, c.Expires, c.RouteToDatabase, c.ConnectionDiagnosticID)
if err != nil {
return trace.BadParameter("failed to parse private key: %v", err)
}

c.TLSCert = &tlsCert
}

return nil
}

// RunALPNAuthTunnel runs a local authenticated ALPN proxy to another service.
// At least one Route (which defines the service) must be defined
func RunALPNAuthTunnel(ctx context.Context, cfg ALPNAuthTunnelConfig) error {
tlsCert, err := getUserCerts(ctx, cfg.AuthClient, cfg.MFAResponse, cfg.Expires, cfg.RouteToDatabase, cfg.ConnectionDiagnosticID)
if err != nil {
return trace.BadParameter("failed to parse private key: %v", err)
if err := cfg.CheckAndSetDefaults(ctx); err != nil {
return trace.Wrap(err)
}

lp, err := alpnproxy.NewLocalProxy(alpnproxy.LocalProxyConfig{
Expand All @@ -101,7 +120,7 @@ func RunALPNAuthTunnel(ctx context.Context, cfg ALPNAuthTunnelConfig) error {
Protocols: []alpn.Protocol{cfg.Protocol},
Listener: cfg.Listener,
ParentContext: ctx,
Cert: tlsCert,
Cert: *cfg.TLSCert,
}, alpnproxy.WithALPNConnUpgradeTest(ctx, getClusterCACertPool(cfg.AuthClient)))
if err != nil {
return trace.Wrap(err)
Expand Down
72 changes: 72 additions & 0 deletions lib/client/db/repl/repl.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Teleport
// Copyright (C) 2024 Gravitational, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package repl

import (
"context"
"io"
"net"

"github.com/gravitational/trace"

clientproto "github.com/gravitational/teleport/api/client/proto"
)

// NewREPLConfig represents the database REPL constructor config.
type NewREPLConfig struct {
// Client is the user terminal client.
Client io.ReadWriteCloser
// ServerConn is the database server connection.
ServerConn net.Conn
// Route is the session routing information.
Route clientproto.RouteToDatabase
}

// REPLNewFunc defines the constructor function for database REPL
// sessions.
type REPLNewFunc func(context.Context, *NewREPLConfig) (REPLInstance, error)

// REPLInstance represents a REPL instance.
type REPLInstance interface {
// Run executes the REPL. This is a blocking operation.
Run(context.Context) error
}

// REPLGetter is an interface for retrieving REPL constructor functions given
// the database protocol.
type REPLGetter interface {
// GetREPL returns a start function for the specified protocol.
GetREPL(protocol string) (REPLNewFunc, error)
}

// NewREPLGetter creates a new REPL getter given the list of supported REPLs.
func NewREPLGetter(replNewFuncs map[string]REPLNewFunc) REPLGetter {
return &replGetter{m: replNewFuncs}
}

type replGetter struct {
m map[string]REPLNewFunc
}

// GetREPL implements REPLGetter.
func (r *replGetter) GetREPL(dbProtocol string) (REPLNewFunc, error) {
if f, ok := r.m[dbProtocol]; ok {
return f, nil
}

return nil, trace.NotImplemented("REPL not supported for protocol %q", dbProtocol)
}
4 changes: 4 additions & 0 deletions lib/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,10 @@ const (

// WebsocketKubeExec provides latency information for a session.
WebsocketKubeExec = "k"

// WebsocketDatabaseSessionRequest is received when a new database session
// is requested.
WebsocketDatabaseSessionRequest = "d"
)

// The following are cryptographic primitives Teleport does not support in
Expand Down
7 changes: 7 additions & 0 deletions lib/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ import (
_ "github.com/gravitational/teleport/lib/backend/pgbk"
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/cache"
dbrepl "github.com/gravitational/teleport/lib/client/db/repl"
"github.com/gravitational/teleport/lib/cloud"
"github.com/gravitational/teleport/lib/cloud/gcp"
"github.com/gravitational/teleport/lib/cloud/imds"
Expand Down Expand Up @@ -1067,6 +1068,11 @@ func NewTeleport(cfg *servicecfg.Config) (*TeleportProcess, error) {
cfg.PluginRegistry = plugin.NewRegistry()
}

if cfg.DatabaseREPLGetter == nil {
// TODO(gabrielcorado): register PostgreSQL REPL.
cfg.DatabaseREPLGetter = dbrepl.NewREPLGetter(map[string]dbrepl.REPLNewFunc{})
}

var cloudLabels labels.Importer

// Check if we're on a cloud instance, and if we should override the node's hostname.
Expand Down Expand Up @@ -4644,6 +4650,7 @@ func (process *TeleportProcess) initProxyEndpoint(conn *Connector) error {
AutomaticUpgradesChannels: cfg.Proxy.AutomaticUpgradesChannels,
IntegrationAppHandler: connectionsHandler,
FeatureWatchInterval: retryutils.HalfJitter(web.DefaultFeatureWatchInterval * 2),
DatabaseREPLGetter: cfg.DatabaseREPLGetter,
}
webHandler, err := web.NewHandler(webConfig)
if err != nil {
Expand Down
5 changes: 5 additions & 0 deletions lib/service/servicecfg/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (
"github.com/gravitational/teleport/lib/auth/state"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/backend/lite"
dbrepl "github.com/gravitational/teleport/lib/client/db/repl"
"github.com/gravitational/teleport/lib/cloud/imds"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
Expand Down Expand Up @@ -265,6 +266,10 @@ type Config struct {
// AccessGraph represents AccessGraph server config
AccessGraph AccessGraphConfig

// DatabaseREPLGetter is used to retrieve datatabase REPL given the
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// DatabaseREPLGetter is used to retrieve datatabase REPL given the
// DatabaseREPLGetter is used to retrieve datatabase REPL given the

// protocol.
DatabaseREPLGetter dbrepl.REPLGetter

// token is either the token needed to join the auth server, or a path pointing to a file
// that contains the token
//
Expand Down
9 changes: 8 additions & 1 deletion lib/web/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ import (
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/automaticupgrades"
"github.com/gravitational/teleport/lib/client"
dbrepl "github.com/gravitational/teleport/lib/client/db/repl"
"github.com/gravitational/teleport/lib/client/sso"
"github.com/gravitational/teleport/lib/defaults"
dtconfig "github.com/gravitational/teleport/lib/devicetrust/config"
Expand Down Expand Up @@ -315,6 +316,9 @@ type Config struct {
// FeatureWatchInterval is the interval between pings to the auth server
// to fetch new cluster features
FeatureWatchInterval time.Duration

// DatabaseREPLGetter is used for retrieving database REPL.
DatabaseREPLGetter dbrepl.REPLGetter
}

// SetDefaults ensures proper default values are set if
Expand Down Expand Up @@ -834,6 +838,7 @@ func (h *Handler) bindDefaultEndpoints() {
h.GET("/webapi/sites/:site/sessions", h.WithClusterAuth(h.clusterActiveAndPendingSessionsGet)) // get list of active and pending sessions

h.GET("/webapi/sites/:site/kube/exec/ws", h.WithClusterAuthWebSocket(h.podConnect)) // connect to a pod with exec (via websocket, with auth over websocket)
h.GET("/webapi/sites/:site/db/exec/ws", h.WithClusterAuthWebSocket(h.dbConnect))

// Audit events handlers.
h.GET("/webapi/sites/:site/events/search", h.WithClusterAuth(h.clusterSearchEvents)) // search site events
Expand Down Expand Up @@ -3094,7 +3099,7 @@ func (h *Handler) clusterUnifiedResourcesGet(w http.ResponseWriter, request *htt
}
hasFetchedDBUsersAndNames = true
}
db := ui.MakeDatabase(r.GetDatabase(), dbUsers, dbNames, enriched.RequiresRequest)
db := ui.MakeDatabase(r.GetDatabase(), dbUsers, dbNames, enriched.RequiresRequest, h.cfg.DatabaseREPLGetter)
unifiedResources = append(unifiedResources, db)
case types.AppServer:
allowedAWSRoles, err := calculateAppLogins(accessChecker, r, enriched.Logins)
Expand Down Expand Up @@ -3588,6 +3593,7 @@ func (h *Handler) siteNodeConnect(
}

term, err := NewTerminal(ctx, TerminalHandlerConfig{
Logger: h.logger,
Term: req.Term,
SessionCtx: sessionCtx,
UserAuthClient: clt,
Expand Down Expand Up @@ -3740,6 +3746,7 @@ func (h *Handler) podConnect(
ws: ws,
keepAliveInterval: keepAliveInterval,
log: h.log.WithField(teleport.ComponentKey, "pod"),
logger: h.logger.With(teleport.ComponentKey, "pod"),
userClient: clt,
localCA: hostCA,
configServerAddr: serverAddr,
Expand Down
7 changes: 6 additions & 1 deletion lib/web/apiserver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ import (
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/client/conntest"
dbrepl "github.com/gravitational/teleport/lib/client/db/repl"
"github.com/gravitational/teleport/lib/cryptosuites"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
Expand Down Expand Up @@ -210,6 +211,9 @@ type webSuiteConfig struct {

// clock to use for all server components
clock clockwork.FakeClock

// databaseREPLGetter allows setting custom database REPLs.
databaseREPLGetter dbrepl.REPLGetter
}

func newWebSuiteWithConfig(t *testing.T, cfg webSuiteConfig) *WebSuite {
Expand Down Expand Up @@ -508,6 +512,7 @@ func newWebSuiteWithConfig(t *testing.T, cfg webSuiteConfig) *WebSuite {
return &proxyClientCert, nil
},
IntegrationAppHandler: &mockIntegrationAppHandler{},
DatabaseREPLGetter: cfg.databaseREPLGetter,
}

if handlerConfig.HealthCheckAppServer == nil {
Expand Down Expand Up @@ -7476,7 +7481,7 @@ func TestOverwriteDatabase(t *testing.T) {

backendDb, err := env.server.Auth().GetDatabase(context.Background(), req.Name)
require.NoError(t, err)
require.Equal(t, webui.MakeDatabase(backendDb, nil, nil, false), gotDb)
require.Equal(t, webui.MakeDatabase(backendDb, nil, nil, false, dbrepl.NewREPLGetter(map[string]dbrepl.REPLNewFunc{})), gotDb)
},
},
{
Expand Down
Loading
Loading