diff --git a/docs/release-notes/release-notes-next.md b/docs/release-notes/release-notes-next.md index 4af54cbb..c88e2950 100644 --- a/docs/release-notes/release-notes-next.md +++ b/docs/release-notes/release-notes-next.md @@ -1,5 +1,14 @@ # Next release +## Bug Fixes + +* Fix a connection ownership bug where an embedded pool trader server closed + the shared lnd connection on shutdown. When running as a subserver of + lightning-terminal, stopping the pool daemon tore down the lnd connection + owned by the parent process, breaking lnd access for LiT and all other + integrated subservers. The server now tracks whether it created the + connection itself and only closes owned connections. + ## Breaking Changes * Migrate exported Bitcoin types and dependencies to the btcd v2 modules. diff --git a/rpcserver.go b/rpcserver.go index 085a92bc..2b837c47 100644 --- a/rpcserver.go +++ b/rpcserver.go @@ -132,7 +132,7 @@ func (s *accountStore) PendingBatch() error { // database is created in `serverDir` if it does not yet exist. func newRPCServer(server *Server) (*rpcServer, error) { accountStore := &accountStore{server.db} - lndServices := &server.lndServices.LndServices + lndServices := server.lndServices batchVersion, err := server.determineBatchVersion() if err != nil { return nil, err diff --git a/rpcserver_test.go b/rpcserver_test.go index a78e6498..43ba56e0 100644 --- a/rpcserver_test.go +++ b/rpcserver_test.go @@ -197,9 +197,7 @@ func TestRenewAccount(t *testing.T) { orderManager: orderMgr, marshaler: marshaler, server: &Server{ - lndServices: &lndclient.GrpcLndServices{ - LndServices: lndServices, - }, + lndServices: &lndServices, }, } srv.bestHeight = 100 diff --git a/server.go b/server.go index cccca4cd..2e03b581 100644 --- a/server.go +++ b/server.go @@ -111,8 +111,21 @@ type Server struct { fundingManager *funding.Manager sidecarAcceptor *SidecarAcceptor l402Store *l402.FileStore - lndServices *lndclient.GrpcLndServices - lndClient lnrpc.LightningClient + + // lndServices is the set of lnd services the server uses. It is a + // non-closable view: the closeable connection wrapper is only ever + // held in lndOwner, and only when the server created the connection + // itself (standalone mode). + lndServices *lndclient.LndServices + lndClient lnrpc.LightningClient + + // lndOwner holds the full lnd services wrapper, including its Close + // method, if and only if the server created the lnd connection + // itself (standalone mode via Start). When the server is started as + // a subserver (StartAsSubserver), the lnd connection is shared with + // and owned by the parent process (e.g. LiT) and lndOwner is nil, + // so there is no closable handle to the borrowed connection. + lndOwner *lndclient.GrpcLndServices grpcServer *grpc.Server restProxy *http.Server grpcListener net.Listener @@ -154,14 +167,20 @@ func (s *Server) Start() error { }() var err error - s.lndServices, err = getLnd( + lndGrpc, err := getLnd( s.cfg.Network, s.cfg.Lnd, s.cfg.ShutdownInterceptor, ) if err != nil { return err } + + // We created the lnd connection ourselves, so we own it and are + // responsible for closing it on shutdown. The rest of the server + // only ever sees the non-closable services view. + s.lndOwner = lndGrpc + s.lndServices = &lndGrpc.LndServices shutdownFuncs["lnd"] = func() error { // nolint:unparam - s.lndServices.Close() + s.lndOwner.Close() return nil } @@ -201,7 +220,7 @@ func (s *Server) Start() error { }, RequiredPerms: poolrpc.RequiredPermissions, DBPassword: macDbDefaultPw, - LndClient: &s.lndServices.LndServices, + LndClient: s.lndServices, EphemeralKey: lndclient.SharedKeyNUMS, KeyLocator: lndclient.SharedKeyLocator, }, @@ -379,14 +398,20 @@ func (s *Server) Start() error { // StartAsSubserver is an alternative start method where the RPC server does not // create its own gRPC server but registers on an existing one. func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient, - lndGrpc *lndclient.GrpcLndServices, withMacaroonService bool) error { + lndServices *lndclient.LndServices, withMacaroonService bool) error { if atomic.AddInt32(&s.started, 1) != 1 { return fmt.Errorf("trader can only be started once") } s.lndClient = lndClient - s.lndServices = lndGrpc + + // When starting as a subserver, we get passed in an already + // established connection to lnd that might be shared among other + // subservers. We only receive the non-closable services view: the + // connection is owned by the parent process (e.g. LiT) and it is + // not possible for us to close it. + s.lndServices = lndServices // Print the version before executing either primary directive. log.Infof("Version: %v", Version()) @@ -427,7 +452,7 @@ func (s *Server) StartAsSubserver(lndClient lnrpc.LightningClient, }, RequiredPerms: poolrpc.RequiredPermissions, DBPassword: macDbDefaultPw, - LndClient: &s.lndServices.LndServices, + LndClient: s.lndServices, EphemeralKey: lndclient.SharedKeyNUMS, KeyLocator: lndclient.SharedKeyLocator, }, @@ -550,7 +575,7 @@ func (s *Server) setupClient() error { // create a fixed identity that is used for the whole runtime of the // trader instead. var interceptor Interceptor = l402.NewInterceptor( - &s.lndServices.LndServices, s.l402Store, defaultRPCTimeout, + s.lndServices, s.l402Store, defaultRPCTimeout, defaultL402MaxCost, s.cfg.L402MaxRoutingFee, false, ) if s.cfg.FakeAuth && s.cfg.Network == "mainnet" { @@ -719,7 +744,7 @@ func (s *Server) Stop() error { } } - s.lndServices.Close() + s.stopLnd() s.wg.Wait() if shutdownErr != nil { @@ -728,6 +753,17 @@ func (s *Server) Stop() error { return nil } +// stopLnd closes the connection to lnd, but only if the server created the +// connection itself (standalone mode), in which case lndOwner holds the +// closable wrapper. In subserver mode the connection is owned by the parent +// process (e.g. LiT) and shared with other subservers, closing it here +// would tear down their lnd access as well. +func (s *Server) stopLnd() { + if s.lndOwner != nil { + s.lndOwner.Close() + } +} + // getLnd returns an instance of the lnd services proxy. func getLnd(network string, cfg *LndConfig, interceptor signal.Interceptor) (*lndclient.GrpcLndServices, error) { diff --git a/server_ownership_guard_test.go b/server_ownership_guard_test.go new file mode 100644 index 00000000..7ddae91e --- /dev/null +++ b/server_ownership_guard_test.go @@ -0,0 +1,153 @@ +package pool + +import ( + "bytes" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +// TestLndConnectionOwnershipGuard is a mechanically enforced invariant +// (running as part of the unit tests in CI) that makes sure the lnd +// connection ownership model cannot silently regress: +// +// - StartAsSubserver must never again accept the closable +// *lndclient.GrpcLndServices wrapper, only the non-closable +// *lndclient.LndServices view. +// - No code in this package may call .Close() on an lnd connection +// handle (the services view, the raw client connection or the +// wrapper), except through the designated owner handle lndOwner, +// which is only set in standalone mode. +func TestLndConnectionOwnershipGuard(t *testing.T) { + // allowedCloseReceivers is the exhaustive whitelist of receiver + // expressions on which .Close() may be called on an lnd connection + // handle in this package. The lndOwner field is only non-nil when + // the server created the connection itself. + allowedCloseReceivers := map[string]bool{ + // The server's owner handle, only set in standalone mode. + "s.lndOwner": true, + } + + // forbiddenReceiverComponents are the components (split on '.') + // that no .Close() receiver expression may contain, unless the + // whole expression is whitelisted above. + forbiddenReceiverComponents := []string{ + "lnd", "lndServices", "lndGrpc", "lndClient", "lndOwner", + "ClientConn", + } + + fset := token.NewFileSet() + err := filepath.WalkDir(".", func(path string, d os.DirEntry, + err error) error { + + if err != nil { + return err + } + + if d.IsDir() || !strings.HasSuffix(path, ".go") || + strings.HasSuffix(path, "_test.go") { + + return nil + } + + file, err := parser.ParseFile(fset, path, nil, 0) + if err != nil { + return err + } + + checkFileOwnershipGuard( + t, fset, path, file, allowedCloseReceivers, + forbiddenReceiverComponents, + ) + + return nil + }) + require.NoError(t, err) +} + +// checkFileOwnershipGuard inspects a single parsed file for violations of +// the lnd connection ownership invariant. +func checkFileOwnershipGuard(t *testing.T, fset *token.FileSet, path string, + file *ast.File, allowedCloseReceivers map[string]bool, + forbiddenReceiverComponents []string) { + + ast.Inspect(file, func(n ast.Node) bool { + switch node := n.(type) { + case *ast.FuncDecl: + // The subserver entry point must only accept the + // non-closable services view. + if node.Name.Name != "StartAsSubserver" { + return true + } + + for _, field := range node.Type.Params.List { + typeStr := renderNode(fset, field.Type) + if strings.Contains( + typeStr, "GrpcLndServices", + ) { + + t.Errorf( + "%v: StartAsSubserver must "+ + "not accept the closable "+ + "wrapper type %v", + fset.Position(node.Pos()), + typeStr, + ) + } + } + + case *ast.CallExpr: + sel, ok := node.Fun.(*ast.SelectorExpr) + if !ok || sel.Sel.Name != "Close" { + return true + } + + receiver := renderNode(fset, sel.X) + if allowedCloseReceivers[receiver] { + return true + } + + components := strings.FieldsFunc( + receiver, func(r rune) bool { + return r == '.' || r == '(' || + r == ')' || r == '&' || + r == '*' + }, + ) + for _, component := range components { + for _, forbidden := range forbiddenReceiverComponents { //nolint:lll + if component != forbidden { + continue + } + + t.Errorf( + "%v: %v: forbidden .Close() "+ + "call on lnd connection "+ + "receiver %q, only the "+ + "owner handle lndOwner "+ + "may be closed", + fset.Position(node.Pos()), + path, receiver, + ) + } + } + } + + return true + }) +} + +// renderNode renders an AST node back to its source string. +func renderNode(fset *token.FileSet, n ast.Node) string { + var buf bytes.Buffer + _ = printer.Fprint(&buf, fset, n) + + return buf.String() +} diff --git a/server_ownership_test.go b/server_ownership_test.go new file mode 100644 index 00000000..55066daf --- /dev/null +++ b/server_ownership_test.go @@ -0,0 +1,375 @@ +package pool + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "math/big" + "net" + "testing" + "time" + + "github.com/lightninglabs/lndclient" + "github.com/lightningnetwork/lnd/lnrpc" + "github.com/lightningnetwork/lnd/lnrpc/chainrpc" + "github.com/lightningnetwork/lnd/lnrpc/invoicesrpc" + "github.com/lightningnetwork/lnd/lnrpc/routerrpc" + "github.com/lightningnetwork/lnd/lnrpc/signrpc" + "github.com/lightningnetwork/lnd/lnrpc/verrpc" + "github.com/lightningnetwork/lnd/lnrpc/walletrpc" + "github.com/stretchr/testify/require" + "google.golang.org/grpc" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/test/bufconn" +) + +const ( + // testMockLndHeight is the block height the mock lnd node reports. + testMockLndHeight = 600 + + // testMockLndPubkey is the identity pubkey the mock lnd node + // reports. + testMockLndPubkey = "03f5374b16f0b1f1b49101de1b9d89e0b460bc57ce9c2f9" + + "132b73dfc76d3704daa" + + // testMacaroonHex is a pre-baked macaroon (root key + // "dummy-root-key", id "42", location "lnd") that is used as the + // macaroon for all lnd services. The mock lnd server does not + // validate macaroons, the hex only needs to parse. + testMacaroonHex = "0201036c6e6402023432000006205a6adf86f5fef1c3738c7" + + "c299da15c0bb5e2c3d3f84e89090bbad9e070ee6663" +) + +// The following mock servers implement the minimal subset of lnd's gRPC +// services that is required to create an lndclient.GrpcLndServices and to +// start an embedded pool trader server. They are used to verify that the +// injected lnd connection is not closed by the subserver on shutdown. Each +// service gets its own struct because the embedded Unimplemented types have +// overlapping method names. + +// mockLightningServer implements lnd's main Lightning gRPC service. +type mockLightningServer struct { + lnrpc.UnimplementedLightningServer +} + +// GetInfo returns static node information. +func (m *mockLightningServer) GetInfo(_ context.Context, + _ *lnrpc.GetInfoRequest) (*lnrpc.GetInfoResponse, error) { + + return &lnrpc.GetInfoResponse{ + IdentityPubkey: testMockLndPubkey, + Alias: "mock-lnd", + Color: "#3399ff", + Version: "0.21.0-beta", + BlockHeight: testMockLndHeight, + BlockHash: "00000000000000000000000000000000" + + "00000000000000000000000000000000", + SyncedToChain: true, + SyncedToGraph: true, + Chains: []*lnrpc.Chain{ + { + Chain: "bitcoin", + Network: "testnet", + }, + }, + }, nil +} + +// SubscribeChannelEvents blocks until the subscription is canceled. +func (m *mockLightningServer) SubscribeChannelEvents( + _ *lnrpc.ChannelEventSubscription, + stream lnrpc.Lightning_SubscribeChannelEventsServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// ChannelAcceptor blocks until the stream is canceled. +func (m *mockLightningServer) ChannelAcceptor( + stream lnrpc.Lightning_ChannelAcceptorServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// mockStateServer implements lnd's State gRPC service. +type mockStateServer struct { + lnrpc.UnimplementedStateServer +} + +// SubscribeState reports the wallet as unlocked and then blocks. +func (m *mockStateServer) SubscribeState(_ *lnrpc.SubscribeStateRequest, + stream lnrpc.State_SubscribeStateServer) error { + + err := stream.Send(&lnrpc.SubscribeStateResponse{ + State: lnrpc.WalletState_RPC_ACTIVE, + }) + if err != nil { + return err + } + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// mockVersionerServer implements lnd's verrpc gRPC service. +type mockVersionerServer struct { + verrpc.UnimplementedVersionerServer +} + +// GetVersion returns a version that satisfies the minimum required lnd +// version of the pool daemon. +func (m *mockVersionerServer) GetVersion(_ context.Context, + _ *verrpc.VersionRequest) (*verrpc.Version, error) { + + return &verrpc.Version{ + AppMajor: 0, + AppMinor: 21, + AppPatch: 0, + BuildTags: []string{ + "signrpc", "walletrpc", "chainrpc", + "invoicesrpc", + }, + }, nil +} + +// mockChainNotifierServer implements lnd's chainrpc gRPC service. +type mockChainNotifierServer struct { + chainrpc.UnimplementedChainNotifierServer +} + +// RegisterBlockEpochNtfn sends the current block height once (like lnd +// does on registration) and then blocks until the subscription is +// canceled. +func (m *mockChainNotifierServer) RegisterBlockEpochNtfn( + _ *chainrpc.BlockEpoch, + stream chainrpc.ChainNotifier_RegisterBlockEpochNtfnServer) error { + + err := stream.Send(&chainrpc.BlockEpoch{ + Height: testMockLndHeight, + }) + if err != nil { + return err + } + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// RegisterConfirmationsNtfn blocks until the subscription is canceled. +func (m *mockChainNotifierServer) RegisterConfirmationsNtfn( + _ *chainrpc.ConfRequest, + stream chainrpc.ChainNotifier_RegisterConfirmationsNtfnServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// RegisterSpendNtfn blocks until the subscription is canceled. +func (m *mockChainNotifierServer) RegisterSpendNtfn( + _ *chainrpc.SpendRequest, + stream chainrpc.ChainNotifier_RegisterSpendNtfnServer) error { + + <-stream.Context().Done() + + return stream.Context().Err() +} + +// mockWalletKitServer implements lnd's walletrpc gRPC service. +type mockWalletKitServer struct { + walletrpc.UnimplementedWalletKitServer +} + +// ListUnspent returns an empty UTXO list. +func (m *mockWalletKitServer) ListUnspent(_ context.Context, + _ *walletrpc.ListUnspentRequest) (*walletrpc.ListUnspentResponse, + error) { + + return &walletrpc.ListUnspentResponse{}, nil +} + +// EstimateFee returns a static fee estimate. +func (m *mockWalletKitServer) EstimateFee(_ context.Context, + _ *walletrpc.EstimateFeeRequest) (*walletrpc.EstimateFeeResponse, + error) { + + return &walletrpc.EstimateFeeResponse{ + SatPerKw: 12500, + }, nil +} + +// startMockLnd starts the mock lnd gRPC server on an in-memory listener and +// returns the listener to dial. +func startMockLnd(t *testing.T) *bufconn.Listener { + t.Helper() + + lis := bufconn.Listen(1024 * 1024) + server := grpc.NewServer(grpc.Creds( + credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{testTLSCert(t)}, + }), + )) + + lnrpc.RegisterLightningServer(server, &mockLightningServer{}) + lnrpc.RegisterStateServer(server, &mockStateServer{}) + verrpc.RegisterVersionerServer(server, &mockVersionerServer{}) + chainrpc.RegisterChainNotifierServer( + server, &mockChainNotifierServer{}, + ) + walletrpc.RegisterWalletKitServer(server, &mockWalletKitServer{}) + invoicesrpc.RegisterInvoicesServer( + server, &invoicesrpc.UnimplementedInvoicesServer{}, + ) + routerrpc.RegisterRouterServer( + server, &routerrpc.UnimplementedRouterServer{}, + ) + signrpc.RegisterSignerServer( + server, &signrpc.UnimplementedSignerServer{}, + ) + + go func() { + _ = server.Serve(lis) + }() + + t.Cleanup(func() { + server.Stop() + _ = lis.Close() + }) + + return lis +} + +// newInjectedLndServices creates a real lndclient.GrpcLndServices backed by +// a real gRPC connection to the mock lnd server. This mirrors exactly what +// LiT creates once and then injects into its subservers. +func newInjectedLndServices(t *testing.T, + lis *bufconn.Listener) *lndclient.GrpcLndServices { + + t.Helper() + + services, err := lndclient.NewLndServices(&lndclient.LndServicesConfig{ + LndAddress: "bufnet", + Network: lndclient.NetworkTestnet, + CustomMacaroonHex: testMacaroonHex, + Insecure: true, + Dialer: func(ctx context.Context, _ string) (net.Conn, error) { + return lis.DialContext(ctx) + }, + CheckVersion: minimalCompatibleVersion, + }) + require.NoError(t, err) + + return services +} + +// testTLSCert creates an ephemeral self-signed TLS certificate for the mock +// lnd server. The lndclient is configured with Insecure=true, which skips +// certificate verification but still requires the server to speak TLS. +func testTLSCert(t *testing.T) tls.Certificate { + t.Helper() + + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + require.NoError(t, err) + + template := &x509.Certificate{ + SerialNumber: big.NewInt(1), + Subject: pkix.Name{ + CommonName: "mock-lnd", + }, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature | + x509.KeyUsageKeyEncipherment, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + DNSNames: []string{"mock-lnd"}, + } + + der, err := x509.CreateCertificate( + rand.Reader, template, template, &key.PublicKey, key, + ) + require.NoError(t, err) + + return tls.Certificate{ + Certificate: [][]byte{der}, + PrivateKey: key, + } +} + +// TestSubserverDoesNotCloseSharedLndConn is a regression test for the +// connection ownership bug that caused an embedded pool trader server to +// close the lnd connection that LiT shares among all its subservers. +// Stopping the embedded server must not close the injected lnd connection. +func TestSubserverDoesNotCloseSharedLndConn(t *testing.T) { + // Start the mock lnd node and create the shared lnd connection, + // exactly like LiT does before starting its subservers. + lis := startMockLnd(t) + services := newInjectedLndServices(t, lis) + conn := services.ClientConn + + cfg := DefaultConfig() + cfg.Network = "testnet" + cfg.BaseDir = t.TempDir() + cfg.LogDir = cfg.BaseDir + cfg.AuctionServer = "127.0.0.1:1" + cfg.Insecure = true + cfg.FakeAuth = true + + // Start the trader as a subserver with the shared (borrowed) lnd + // services and a basic client on the same connection, exactly like + // LiT passes them. Note that the trader only receives the + // non-closable view of the connection. + server := NewServer(&cfg) + basicClient := lnrpc.NewLightningClient(conn) + err := server.StartAsSubserver(basicClient, &services.LndServices, + false) + require.NoError(t, err) + + // Stopping the trader server must not close the shared lnd + // connection, it is owned by the parent process. + require.NoError(t, server.Stop()) + require.NotEqual( + t, connectivity.Shutdown, conn.GetState(), + "subserver closed the shared lnd connection", + ) + + // The owner of the connection (the test, acting as the parent + // process) cleans up. + services.Close() + require.Equal(t, connectivity.Shutdown, conn.GetState()) +} + +// TestOwnedLndConnClosedOnStop verifies that the trader server still closes +// the lnd connection when it owns it (standalone mode), i.e. that the +// ownership guard does not leak connections that the server created itself. +func TestOwnedLndConnClosedOnStop(t *testing.T) { + lis := startMockLnd(t) + services := newInjectedLndServices(t, lis) + conn := services.ClientConn + + // Simulate a server that created its own lnd connection (standalone + // mode via Start): it keeps the closable wrapper in lndOwner while + // the rest of the server only sees the non-closable services view. + cfg := DefaultConfig() + cfg.Network = "testnet" + cfg.BaseDir = t.TempDir() + + server := NewServer(&cfg) + server.lndServices = &services.LndServices + server.lndOwner = services + + // Stopping the server must close the connection it owns. We call the + // relevant part of the shutdown logic directly as the rest of the + // server was never started. + server.stopLnd() + require.Equal(t, connectivity.Shutdown, conn.GetState()) +}