Skip to content

Control automatic port forwarding with a devcontainer.json file #49

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 27, 2025
Prev Previous commit
Next Next commit
Add validation that onAutoForward is a string
  • Loading branch information
aaronlehmann committed Feb 26, 2025
commit cf25cbe9a9c3c8a6ca56d2f571851ccc9c69a8cf
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ class CoderPortForwardService(
poller?.cancel()
}

class InvalidJsonTypeException(message: String) : Exception(message)

private fun start() {
val devcontainerFile = CoderBackendSettings.getDevcontainerFile()
if (devcontainerFile.exists()) {
Expand All @@ -66,19 +68,27 @@ class CoderPortForwardService(
val portsAttributes = obj.optJSONObject("portsAttributes") ?: JSONObject()
portsAttributes.keys().forEach { spec ->
portsAttributes.optJSONObject(spec)?.let { attrs ->
val onAutoForward = attrs.optString("onAutoForward")
if (onAutoForward == "ignore") {
val onAutoForward = attrs.opt("onAutoForward")
if (!isValidString(onAutoForward)) {
throw InvalidJsonTypeException("onAutoForward for port $spec is not a string value")
}
val onAutoForwardStr = onAutoForward as String
if (onAutoForwardStr == "ignore") {
logger.info("found ignored port specification $spec in devcontainer.json")
rules.add(0, PortRule(PortMatcher(spec), false))
} else if (onAutoForward != "") {
} else if (onAutoForwardStr != "") {
logger.info("found auto-forward port specification $spec in devcontainer.json")
rules.add(0, PortRule(PortMatcher(spec), true))
}
}
}

val otherPortsAttributes = obj.optJSONObject("otherPortsAttributes") ?: JSONObject()
if (otherPortsAttributes.optString("onAutoForward") == "ignore") {
val otherPortsAutoForward = otherPortsAttributes.opt("onAutoForward")
if (!isValidString(otherPortsAutoForward)) {
throw InvalidJsonTypeException("otherPortsAttributes.onAutoForward is not a string value")
}
if ((otherPortsAutoForward as String) == "ignore") {
logger.info("found ignored setting for otherPortsAttributes in devcontainer.json")
defaultForward = false
}
Expand Down Expand Up @@ -141,4 +151,8 @@ class CoderPortForwardService(
}
}
}

private fun isValidString(value: Any?): Boolean {
return value != null && value is String
}
}