Skip to content

Commit

Permalink
Don't connect to private or loopback addresses
Browse files Browse the repository at this point in the history
This probably doesn't matter but it is pointless to try to connect to
those.
  • Loading branch information
boreq committed Nov 21, 2023
1 parent 547ab93 commit b64be66
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions service/app/downloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,11 @@ func (m *DatabaseRelaySource) GetRelays(ctx context.Context) ([]domain.RelayAddr
Message("address is invalid")
continue
}

if address.IsLoopbackOrPrivate() {
continue
}

result = append(result, address)
}

Expand Down
11 changes: 11 additions & 0 deletions service/domain/relay_address.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package domain

import (
"net"
"net/url"
"strings"

"github.com/boreq/errors"
Expand Down Expand Up @@ -32,6 +34,15 @@ func NewRelayAddressFromMaybeAddress(maybe MaybeRelayAddress) (RelayAddress, err
return NewRelayAddress(maybe.String())
}

func (r RelayAddress) IsLoopbackOrPrivate() bool {
u, err := url.Parse(r.s)
if err != nil {
return false
}
ip := net.ParseIP(u.Host)
return ip.IsLoopback() || ip.IsPrivate()
}

func (r RelayAddress) String() string {
return r.s
}
31 changes: 31 additions & 0 deletions service/domain/relay_address_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,34 @@ func TestRelayAddress(t *testing.T) {
})
}
}

func TestRelayAddress_IsLocal(t *testing.T) {
testCases := []struct {
Input string
Result bool
}{
{
Input: "ws://127.0.0.1",
Result: true,
},
{
Input: "ws://192.168.0.10",
Result: true,
},
{
Input: "ws://1.2.3.4",
Result: false,
},
{
Input: "ws://example.com",
Result: false,
},
}

for _, testCase := range testCases {
t.Run(testCase.Input, func(t *testing.T) {
address := MustNewRelayAddress(testCase.Input)
require.Equal(t, testCase.Result, address.IsLoopbackOrPrivate())
})
}
}

0 comments on commit b64be66

Please sign in to comment.