Skip to content

Commit

Permalink
use loopback instead of hardcoding IPs
Browse files Browse the repository at this point in the history
  • Loading branch information
deniseli committed Jun 6, 2024
1 parent ba3c58c commit fd79335
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
12 changes: 11 additions & 1 deletion backend/controller/admin/cmd_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package admin
import (
"context"
"errors"
"net"
"net/url"

"connectrpc.com/connect"
Expand Down Expand Up @@ -62,5 +63,14 @@ func isConnectUnavailableError(err error) bool {

func isEndpointLocal(endpoint *url.URL) bool {
h := endpoint.Hostname()
return h == "localhost" || h == "127.0.0.1"
ips, err := net.LookupIP(h)
if err != nil {
panic(err.Error())
}
for _, netip := range ips {
if netip.IsLoopback() {
return true
}
}
return false
}
45 changes: 45 additions & 0 deletions backend/controller/admin/cmd_client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package admin

import (
"net/url"
"testing"

"github.com/alecthomas/assert/v2"
)

func TestIsEndpointLocal(t *testing.T) {
tests := []struct {
Name string
Endpoint string
Want bool
}{
{
Name: "DefaultLocalhost",
Endpoint: "http://localhost:8892",
Want: true,
},
{
Name: "NumericLocalhost",
Endpoint: "http://127.0.0.1:8892",
Want: true,
},
{
Name: "TooLow",
Endpoint: "http://126.255.255.255:8892",
Want: false,
},
{
Name: "TooHigh",
Endpoint: "http://128.0.0.1:8892",
Want: false,
},
}

for _, test := range tests {
t.Run(test.Name, func(t *testing.T) {
u, err := url.Parse(test.Endpoint)
assert.NoError(t, err)
assert.Equal(t, isEndpointLocal(u), test.Want)
})
}
}

0 comments on commit fd79335

Please sign in to comment.