Skip to content

Commit ae1df2f

Browse files
committed
Validate single port or range endpoint is between 0 and 65535
1 parent 12f38a1 commit ae1df2f

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/main/kotlin/com/coder/jetbrains/matcher/PortMatcher.kt

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,16 @@ class PortMatcher(private val rule: String) {
2828
return when {
2929
// Try parsing as single port
3030
portPart.all { it.isDigit() } -> {
31-
MatchRule.SinglePort(portPart.toInt())
31+
val port = portPart.toInt()
32+
validatePort(port)
33+
MatchRule.SinglePort(port)
3234
}
3335
// Try parsing as port range (e.g., "40000-55000")
3436
portPart.matches("^\\d+-\\d+$".toRegex()) -> {
3537
val (start, end) = portPart.split('-')
3638
.map { it.trim().toInt() }
39+
validatePort(start)
40+
validatePort(end)
3741
require(start <= end) { "Invalid port range: start must be less than or equal to end" }
3842
MatchRule.PortRange(start, end)
3943
}
@@ -47,4 +51,12 @@ class PortMatcher(private val rule: String) {
4751
}
4852
}
4953
}
54+
55+
private fun validatePort(port: Int) {
56+
require(port in 0..65535) { "Port number must be between 0 and 65535, got: $port" }
57+
}
58+
59+
companion object {
60+
const val MAX_PORT = 65535
61+
}
5062
}

src/test/kotlin/com/coder/jetbrains/matcher/PortMatcherTest.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package com.coder.jetbrains.matcher
33
import org.junit.Test
44
import org.junit.Assert.assertFalse
55
import org.junit.Assert.assertTrue
6+
import org.junit.Assert.assertThrows
67

78
class PortMatcherTest {
89

@@ -40,4 +41,24 @@ class PortMatcherTest {
4041
assertTrue(matcher.matches(8009))
4142
assertFalse(matcher.matches(8010))
4243
}
44+
45+
@Test
46+
fun `test invalid port numbers`() {
47+
assertThrows(IllegalArgumentException::class.java) { PortMatcher("65536") }
48+
assertThrows(IllegalArgumentException::class.java) { PortMatcher("0-65536") }
49+
assertThrows(IllegalArgumentException::class.java) { PortMatcher("70000") }
50+
}
51+
52+
@Test
53+
fun `test edge case port numbers`() {
54+
// These should work
55+
PortMatcher("0")
56+
PortMatcher("65535")
57+
PortMatcher("0-65535")
58+
59+
// These combinations should work
60+
val matcher = PortMatcher("0-65535")
61+
assertTrue(matcher.matches(0))
62+
assertTrue(matcher.matches(65535))
63+
}
4364
}

0 commit comments

Comments
 (0)