A continuation of HomeBox the inventory and organization system built for the Home User
fix: #1656 introduced by underlying library
Matthew Kilgore1e81e65ccd94
diff --git a/backend/app/api/listener_test.go b/backend/app/api/listener_test.gonew file mode 100644index 00000000..26a48e19--- /dev/null+++ b/backend/app/api/listener_test.go@@ -0,0 +1,89 @@+package main++import (+ "net"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++// freePort reserves a port, then releases it so the code under test can bind it.+func freePort(t *testing.T) string {+ t.Helper()++ ln, err := net.Listen("tcp", "127.0.0.1:0")+ require.NoError(t, err)+ addr := ln.Addr().String()+ require.NoError(t, ln.Close())+ return addr+}++// isActivationAddress is the gate that keeps anyhttp — and therefore its+// implicit bind of ":http" (port 80) for an empty address — off the plain TCP+// path entirely. These cases mirror anyhttp's own parseAddress, so a drift in+// either direction shows up here. See issue #1656.+func TestIsActivationAddress(t *testing.T) {+ t.Parallel()++ activation := []string{+ "unix?path=/tmp/homebox.sock",+ "unix?path=/tmp/homebox.sock&mode=660",+ "sysd",+ "sysd?name=homebox",+ }+ for _, addr := range activation {+ assert.True(t, isActivationAddress(addr), "%q should be an activation address", addr)+ }++ plain := []string{+ "", // the default: anyhttp would map this to ":http" and bind port 80+ "0.0.0.0",+ "127.0.0.1",+ "localhost",+ "0.0.0.0:7745",+ "127.0.0.1:7745",+ }+ for _, addr := range plain {+ assert.False(t, isActivationAddress(addr), "%q should be handled as plain TCP", addr)+ }+}++// anyhttp opens a TCP socket for any address that isn't a unix socket or a+// systemd FD, including the ":http" (port 80) default it substitutes for an+// empty Web.Host. We never serve that socket, so it must not end up bound.+// See issue #1656.+func TestActivationListenerReleasesPlainTCPSocket(t *testing.T) {+ addr := freePort(t)++ listener, err := activationListener(addr)+ require.NoError(t, err)+ assert.Nil(t, listener, "a plain TCP address must not yield a listener to Serve")++ // The real assertion: the port anyhttp bound has to be free again.+ reclaimed, err := net.Listen("tcp", addr)+ require.NoError(t, err, "anyhttp's unused TCP listener was left bound (issue #1656)")+ require.NoError(t, reclaimed.Close())+}++// The default configuration leaves Web.Host empty, which is the case that+// reached out and bound port 80.+func TestActivationListenerEmptyHostYieldsNoListener(t *testing.T) {+ listener, err := activationListener("")+ require.NoError(t, err)+ assert.Nil(t, listener,+ "an empty Web.Host must fall through to ListenAndServe, not serve anyhttp's :80 socket")+}++// A unix socket address is a genuine activation mode and must still produce a+// listener for the server to Serve.+func TestActivationListenerReturnsUnixSocket(t *testing.T) {+ sock := t.TempDir() + "/homebox.sock"++ listener, err := activationListener("unix?path=" + sock + "&remove_existing=true")+ require.NoError(t, err)+ require.NotNil(t, listener, "a unix socket address must yield a listener to Serve")+ t.Cleanup(func() { _ = listener.Close() })++ assert.Equal(t, "unix", listener.Addr().Network())+}diff --git a/backend/app/api/main.go b/backend/app/api/main.goindex 0576816b..cc9afab8 100644--- a/backend/app/api/main.go+++ b/backend/app/api/main.go@@ -4,7 +4,9 @@ import ("context""errors""fmt"+ "net""net/http"+ "net/url""os""runtime""strings"@@ -267,27 +269,18 @@ func run(cfg *config.Config) error {_ = httpserver.Shutdown(context.Background())}()- listener, addrType, addrCfg, err := anyhttp.GetListener(cfg.Web.Host)- if err == nil {+ listener, err := activationListener(cfg.Web.Host)+ if err != nil {+ return err+ }+ if listener != nil {defer func() {if err := listener.Close(); err != nil {log.Error().Err(err).Msg("failed to close listener")}}()- switch addrType {- case anyhttp.SystemdFD:- sysdCfg := addrCfg.(*anyhttp.SysdConfig)- if sysdCfg.IdleTimeout != nil {- log.Error().Msg("idle timeout not yet supported. Please remove and try again")- return errors.New("idle timeout not yet supported. Please remove and try again")- }- fallthrough- case anyhttp.UnixSocket:- log.Info().Msgf("Server is running on %s", cfg.Web.Host)- return httpserver.Serve(listener)- }- } else {- log.Debug().Msgf("anyhttp error: %v", err)+ log.Info().Msgf("Server is running on %s", cfg.Web.Host)+ return httpserver.Serve(listener)}log.Info().Msgf("Server is running on %s:%s", cfg.Web.Host, cfg.Web.Port)return httpserver.ListenAndServe()@@ -322,6 +315,72 @@ func run(cfg *config.Config) error {return runner.Start(context.Background())}+// isActivationAddress reports whether host selects one of anyhttp's socket+// activation modes. It mirrors anyhttp's own parsing — an address whose URL+// path is "unix" or "sysd" — so the gate can never disagree with what+// GetListener would have decided. Everything else, including the empty+// default, is a plain TCP address we bind ourselves.+func isActivationAddress(host string) bool {+ u, err := url.Parse(host)+ if err != nil {+ // anyhttp treats an unparseable address as TCP; so do we.+ return false+ }+ return u.Path == "unix" || u.Path == "sysd"+}++// activationListener returns a listener to Serve when Web.Host selects systemd+// socket activation or a unix socket, and nil when the caller should bind+// Web.Host:Web.Port itself.+//+// The gate runs *before* anyhttp is called, and that ordering is the whole+// point. anyhttp.GetListener binds a TCP socket for any non-activation address+// before it returns, and when Web.Host is empty (the default) that socket is+// port 80, because anyhttp maps "" to ":http". Homebox never serves it, so the+// process would sit on :80 for its entire lifetime without accepting anything:+// under host networking that denies :80 to every other service, and clients+// that do connect reach a socket nobody answers, so they hang rather than being+// refused. Opening it and closing it again would still lose a startup race+// against another service, so the only safe thing is never to ask for it.+// See issue #1656.+func activationListener(host string) (net.Listener, error) {+ if !isActivationAddress(host) {+ return nil, nil+ }++ listener, addrType, addrCfg, err := anyhttp.GetListener(host)+ if err != nil {+ // A malformed unix/sysd address falls back to binding Web.Host:Web.Port,+ // matching how this behaved before.+ log.Debug().Msgf("anyhttp error: %v", err)+ return nil, nil+ }++ switch addrType {+ case anyhttp.SystemdFD:+ sysdCfg := addrCfg.(*anyhttp.SysdConfig)+ if sysdCfg.IdleTimeout != nil {+ closeUnusedListener(listener)+ log.Error().Msg("idle timeout not yet supported. Please remove and try again")+ return nil, errors.New("idle timeout not yet supported. Please remove and try again")+ }+ return listener, nil+ case anyhttp.UnixSocket:+ return listener, nil+ default:+ // Unreachable given the gate above, but if anyhttp ever hands back a+ // TCP listener for a unix/sysd address, don't hold the socket.+ closeUnusedListener(listener)+ return nil, nil+ }+}++func closeUnusedListener(listener net.Listener) {+ if err := listener.Close(); err != nil {+ log.Error().Err(err).Msg("failed to close unused listener")+ }+}+// ensureAssetIDs assigns asset IDs to any entities that don't have one,// covering locations that were migrated from the old schema.func ensureAssetIDs(app *app) {