mirror of
https://github.com/coder/coder.git
synced 2025-07-03 16:13:58 +00:00
fix: ensure websocket close messages are truncated to 123 bytes (#779)
It's possible for websocket close messages to be too long, which cause them to silently fail without a proper close message. See error below: ``` 2022-03-31 17:08:34.862 [INFO] (stdlib) <close_notjs.go:72> "2022/03/31 17:08:34 websocket: failed to marshal close frame: reason string max is 123 but got \"insert provisioner daemon:Cannot encode []database.ProvisionerType into oid 19098 - []database.ProvisionerType must implement Encoder or be converted to a string\" with length 161" ```
This commit is contained in:
@ -115,3 +115,21 @@ func Read(rw http.ResponseWriter, r *http.Request, value interface{}) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
const websocketCloseMaxLen = 123
|
||||
|
||||
// WebsocketCloseSprintf formats a websocket close message and ensures it is
|
||||
// truncated to the maximum allowed length.
|
||||
func WebsocketCloseSprintf(format string, vars ...any) string {
|
||||
msg := fmt.Sprintf(format, vars...)
|
||||
|
||||
// Cap msg length at 123 bytes. nhooyr/websocket only allows close messages
|
||||
// of this length.
|
||||
if len(msg) > websocketCloseMaxLen {
|
||||
// Trim the string to 123 bytes. If we accidentally cut in the middle of
|
||||
// a UTF-8 character, remove it from the string.
|
||||
return strings.ToValidUTF8(string(msg[123]), "")
|
||||
}
|
||||
|
||||
return msg
|
||||
}
|
||||
|
Reference in New Issue
Block a user