Skip to content
Snippets Groups Projects

server: Protect against cross-origin websocket requests

Merged Clément Pit-Claudel requested to merge cpc/websocket-origin into main
Files
4
package cs214.webapp.server.decorators
import cask.model.Response
import cask.router.{Decorator}
import cask.router.Result
/** Decorator to validate the origin of the request.
* Cask Decorators enforce strict matching type signatures
* with the core function they are decorating.
* So for each new Return type T, a new Decorator class
* extending originValidation must be created.
* The only method to override is constructForbiddenResponse
* which might be different for each Return type T.
*
*/
private class originValidation[T] extends Decorator[Any, T, Any] {
def wrapFunction(ctx: cask.Request, delegate: Delegate): Result[T] = {
// Check if the Origin header is valid
val isSourceValid = ctx.headers.get("host").flatMap(_.headOption).exists: host =>
ctx.headers.get("origin").flatMap(_.headOption).exists: origin =>
origin == s"http://$host" || origin == s"https://$host"
if (isSourceValid) {
// Call the core logic
delegate(Map.empty)
} else {
// Return a 403 Forbidden response
constructForbiddenResponse.asInstanceOf[Result[T]]
}
}
def constructForbiddenResponse: Result[T] = ???
}
/* WebSocket origin validation */
class originValidationWebSocket extends originValidation[cask.endpoints.WebsocketResult] {
override def constructForbiddenResponse: Result[cask.endpoints.WebsocketResult] = {
Result.Success(new cask.endpoints.WebsocketResult.Response(cask.Response("Forbidden", 403)))
}
}
\ No newline at end of file
Loading