Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

fix: Meilisearch Docker/Local Network HTTP connectivity, #1795

Matthew Kilgore1fd28822634a
diff --git a/backend/internal/data/search/meilisearch.go b/backend/internal/data/search/meilisearch.go
index d58f3866..49905580 100644
--- a/backend/internal/data/search/meilisearch.go
+++ b/backend/internal/data/search/meilisearch.go
@@ -4,8 +4,12 @@ import (
"context"
"encoding/json"
"fmt"
+ "net"
+ "net/http"
+ "net/url"
"strings"
"sync"
+ "syscall"
"time"
"github.com/google/uuid"
@@ -99,12 +103,48 @@ type MeilisearchEngine struct {
timer *time.Timer
}
+// localNetworkOnlyOptions restricts a plaintext http client to loopback and
+// private (RFC 1918 / RFC 4193) peers. The check runs on the resolved address
+// of every connection, so hostnames such as Docker Compose service names work,
+// and a name that resolves (or later re-resolves) to a public address is
+// refused before the API key is sent. Proxies are bypassed so the guarded peer
+// is Meilisearch itself rather than an intermediary that would forward the
+// request onward.
+func localNetworkOnlyOptions() []meilisearch.Option {
+ dialer := &net.Dialer{
+ Timeout: 30 * time.Second,
+ KeepAlive: 30 * time.Second,
+ Control: rejectNonLocalNetwork,
+ }
+ return []meilisearch.Option{
+ meilisearch.WithCustomDialContext(dialer.DialContext),
+ meilisearch.WithCustomProxy(func(*http.Request) (*url.URL, error) { return nil, nil }),
+ }
+}
+
+// rejectNonLocalNetwork is a net.Dialer Control hook that fails the dial
+// unless the resolved peer address is loopback or private.
+func rejectNonLocalNetwork(_, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return err
+ }
+ if ip := net.ParseIP(host); ip == nil || !config.IsLocalNetworkIP(ip) {
+ return fmt.Errorf("refusing insecure http connection to non-local address %s: use https", host)
+ }
+ return nil
+}
+
// NewMeilisearchEngine connects to Meilisearch, ensures the index and its
// settings exist, subscribes to mutation events for incremental indexing, and
// kicks off a full reindex in the background. It fails fast when the instance
// is unreachable so a misconfiguration is caught at startup.
func NewMeilisearchEngine(cfg config.MeilisearchConf, db *ent.Client, bus *eventbus.EventBus) (*MeilisearchEngine, error) {
- client := meilisearch.New(cfg.Host, meilisearch.WithAPIKey(cfg.APIKey))
+ opts := []meilisearch.Option{meilisearch.WithAPIKey(cfg.APIKey)}
+ if u, err := url.Parse(cfg.Host); err == nil && u.Scheme == "http" {
+ opts = append(opts, localNetworkOnlyOptions()...)
+ }
+ client := meilisearch.New(cfg.Host, opts...)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
diff --git a/backend/internal/data/search/meilisearch_test.go b/backend/internal/data/search/meilisearch_test.go
index 7987cf1d..a727aa51 100644
--- a/backend/internal/data/search/meilisearch_test.go
+++ b/backend/internal/data/search/meilisearch_test.go
@@ -2,6 +2,9 @@ package search
import (
"context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
"os"
"testing"
"time"
@@ -270,3 +273,57 @@ func TestNewEngine_MeilisearchUnreachable(t *testing.T) {
require.Error(t, err)
assert.Contains(t, err.Error(), "not reachable")
}
+
+func TestRejectNonLocalNetwork(t *testing.T) {
+ tests := []struct {
+ address string
+ wantErr bool
+ }{
+ {"127.0.0.1:7700", false},
+ {"[::1]:7700", false},
+ {"10.1.2.3:7700", false},
+ {"172.18.0.4:7700", false},
+ {"192.168.1.20:7700", false},
+ {"172.32.0.1:7700", true},
+ {"8.8.8.8:7700", true},
+ {"[fd00::1]:7700", false},
+ {"[fdab:cdef::5]:7700", false},
+ {"[2001:db8::1]:7700", true},
+ }
+ for _, tt := range tests {
+ t.Run(tt.address, func(t *testing.T) {
+ err := rejectNonLocalNetwork("tcp", tt.address, nil)
+ if tt.wantErr {
+ require.Error(t, err)
+ } else {
+ require.NoError(t, err)
+ }
+ })
+ }
+}
+
+// TestLocalNetworkOnlyOptions_ResolvesHostnames verifies the guard runs on the
+// resolved address, so a hostname (as with Docker Compose service names) that
+// resolves to a local address is allowed while a public IP is refused.
+func TestLocalNetworkOnlyOptions_ResolvesHostnames(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"available"}`))
+ }))
+ t.Cleanup(srv.Close)
+
+ u, err := url.Parse(srv.URL)
+ require.NoError(t, err)
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ local := meilisearch.New("http://localhost:"+u.Port(), localNetworkOnlyOptions()...)
+ _, err = local.HealthWithContext(ctx)
+ require.NoError(t, err)
+
+ public := meilisearch.New("http://8.8.8.8:7700", localNetworkOnlyOptions()...)
+ _, err = public.HealthWithContext(ctx)
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "refusing insecure http connection")
+}
diff --git a/backend/internal/sys/config/conf.go b/backend/internal/sys/config/conf.go
index 92a0659c..6c55d895 100644
--- a/backend/internal/sys/config/conf.go
+++ b/backend/internal/sys/config/conf.go
@@ -5,9 +5,9 @@ import (
"encoding/json"
"errors"
"fmt"
+ "net"
"net/url"
"os"
- "strings"
"time"
"github.com/ardanlabs/conf/v3"
@@ -100,7 +100,9 @@ func (c MeilisearchConf) MarshalJSON() ([]byte, error) {
// Validate enforces secure transport for the Meilisearch connection. The API
// key is sent on every request, so a non-local endpoint reached over plaintext
// http would leak it on the wire. https is always allowed; http is permitted
-// only for loopback hosts.
+// only for loopback and private addresses (see IsLocalNetworkIP). A literal IP host is checked here; a hostname (e.g. a
+// Docker Compose service name) can only be checked once resolved, so the
+// Meilisearch client enforces the same rule on every connection it dials.
func (c MeilisearchConf) Validate() error {
if c.Host == "" {
return errors.New("search.meilisearch.host must not be empty")
@@ -113,17 +115,25 @@ func (c MeilisearchConf) Validate() error {
case "https":
return nil
case "http":
- switch strings.ToLower(u.Hostname()) {
- case "localhost", "127.0.0.1", "::1":
- return nil
- default:
+ if u.Hostname() == "" {
+ return errors.New("search.meilisearch.host must include a hostname")
+ }
+ if ip := net.ParseIP(u.Hostname()); ip != nil && !IsLocalNetworkIP(ip) {
return fmt.Errorf("search.meilisearch.host uses insecure http for non-local host %q: use https", u.Host)
}
+ return nil
default:
return fmt.Errorf("search.meilisearch.host has unsupported scheme %q: must be http or https", u.Scheme)
}
}
+// IsLocalNetworkIP reports whether ip is a loopback address or a private
+// address (RFC 1918 IPv4 or RFC 4193 IPv6 unique local), i.e. a destination
+// plaintext http may be used for.
+func IsLocalNetworkIP(ip net.IP) bool {
+ return ip.IsLoopback() || ip.IsPrivate()
+}
+
type Options struct {
CurrencyConfig string `yaml:"currencies"`
Hostname string `yaml:"hostname"`
diff --git a/backend/internal/sys/config/conf_search_test.go b/backend/internal/sys/config/conf_search_test.go
index c391a40e..6c1accf9 100644
--- a/backend/internal/sys/config/conf_search_test.go
+++ b/backend/internal/sys/config/conf_search_test.go
@@ -30,9 +30,20 @@ func Test_MeilisearchConf_Validate(t *testing.T) {
{"https remote with port", "https://search.example.com:7700", false},
{"http localhost", "http://localhost:7700", false},
{"http 127.0.0.1", "http://127.0.0.1:7700", false},
+ {"http 127/8 loopback", "http://127.0.0.2:7700", false},
{"http ipv6 loopback", "http://[::1]:7700", false},
- {"http remote rejected", "http://search.example.com:7700", true},
- {"http remote ip rejected", "http://10.0.0.5:7700", true},
+ {"http hostname deferred to dial", "http://meilisearch:7700", false},
+ {"http fqdn deferred to dial", "http://search.example.com:7700", false},
+ {"http missing hostname", "http://:7700", true},
+ {"http rfc1918 10/8", "http://10.0.0.5:7700", false},
+ {"http rfc1918 172.16/12", "http://172.16.0.1:7700", false},
+ {"http rfc1918 172.31 upper bound", "http://172.31.255.254:7700", false},
+ {"http rfc1918 192.168/16", "http://192.168.1.20:7700", false},
+ {"http just outside 172.16/12 rejected", "http://172.32.0.1:7700", true},
+ {"http public ip rejected", "http://8.8.8.8:7700", true},
+ {"http ipv6 ula fd00::/8", "http://[fd00::1]:7700", false},
+ {"http ipv6 ula fc00::/8", "http://[fc00::1]:7700", false},
+ {"http ipv6 public rejected", "http://[2001:4860:4860::8888]:7700", true},
{"empty host", "", true},
{"unsupported scheme", "ftp://localhost", true},
}