From f4555cb8eded6dbeea5f73839f0a1582c3f38af7 Mon Sep 17 00:00:00 2001 From: James Elliott Date: Tue, 22 Aug 2023 19:49:27 +1000 Subject: [PATCH] fix: isloopback returns true incorrectly (#765) Closes #750 --- authorize_helper.go | 7 +++- authorize_helper_whitebox_test.go | 69 +++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 authorize_helper_whitebox_test.go diff --git a/authorize_helper.go b/authorize_helper.go index 10422155a..3293175fc 100644 --- a/authorize_helper.go +++ b/authorize_helper.go @@ -141,11 +141,14 @@ func isMatchingAsLoopback(requested *url.URL, registeredURI string) bool { return false } +var ( + regexLoopbackAddress = regexp.MustCompile(`^(127\.0\.0\.1|\[::1])(:\d+)?$`) +) + // Check if address is either an IPv4 loopback or an IPv6 loopback- // An optional port is ignored func isLoopbackAddress(address string) bool { - match, _ := regexp.MatchString("^(127.0.0.1|\\[::1\\])(:?)(\\d*)$", address) - return match + return regexLoopbackAddress.MatchString(address) } // IsValidRedirectURI validates a redirect_uri as specified in: diff --git a/authorize_helper_whitebox_test.go b/authorize_helper_whitebox_test.go new file mode 100644 index 000000000..13a54aa31 --- /dev/null +++ b/authorize_helper_whitebox_test.go @@ -0,0 +1,69 @@ +// Copyright © 2023 Ory Corp +// SPDX-License-Identifier: Apache-2.0 + +package fosite + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsLookbackAddress(t *testing.T) { + testCases := []struct { + name string + have string + expected bool + }{ + { + "ShouldReturnTrueIPv4Loopback", + "127.0.0.1", + true, + }, + { + "ShouldReturnTrueIPv4LoopbackWithPort", + "127.0.0.1:1230", + true, + }, + { + "ShouldReturnTrueIPv6Loopback", + "[::1]", + true, + }, + { + "ShouldReturnTrueIPv6LoopbackWithPort", + "[::1]:1230", + true, + }, { + "ShouldReturnFalse12700255", + "127.0.0.255", + false, + }, + { + "ShouldReturnFalse12700255WithPort", + "127.0.0.255:1230", + false, + }, + { + "ShouldReturnFalseInvalidFourthOctet", + "127.0.0.11230", + false, + }, + { + "ShouldReturnFalseInvalidIPv4", + "127x0x0x11230", + false, + }, + { + "ShouldReturnFalseInvalidIPv6", + "[::1]1230", + false, + }, + } + + for _, tc := range testCases { + t.Run(tc.name, func(t *testing.T) { + assert.Equal(t, tc.expected, isLoopbackAddress(tc.have)) + }) + } +}