All posts

How to Fix Xss Vulnerability in Scala

Struggling with Xss Vulnerability in Scala? This guide explains why it happens and how to resolve it quickly.

XSS Vulnerabilities in Scala

Scala web frameworks like Play and http4s can be vulnerable to XSS when templates or responses include unescaped user input.

How XSS Occurs

  • Play's @Html() directive with user content
  • String interpolation in HTML responses
  • JSON responses rendered as HTML by browsers

The Fix

Use framework escaping and sanitize carefully:

import play.twirl.api.HtmlFormat
import org.owasp.encoder.Encode

class CommentController @Inject()(cc: ControllerComponents)
  extends AbstractController(cc) {

  def addComment(): Action[AnyContent] = Action { request =>
    val content = request.body.asFormUrlEncoded
      .flatMap(_.get("content"))
      .flatMap(_.headOption)
      .getOrElse("")

    // HtmlFormat.escape handles HTML encoding
    val safeContent = HtmlFormat.escape(content)

    // For API responses, encode for the output context
    val apiSafe = Encode.forHtml(content)

    Ok(views.html.comment(safeContent))
      .withHeaders(
        "Content-Security-Policy" -> "default-src 'self'",
        "X-Content-Type-Options" -> "nosniff"
      )
  }
}

Never use Html() or @Html() with user input in Twirl templates. Use HtmlFormat.escape() when building HTML programmatically.

Production Hardening

Beyond the immediate fix, consider adding circuit breakers and graceful degradation for this failure mode. Log structured error data so your observability stack can correlate this error with upstream causes. Set up dashboards to track error rates over time and catch regressions early.

Bugsly for Scala

Bugsly detects potential XSS attempts by flagging requests containing script tags or event handlers in parameters, giving your security team early warning of attack patterns.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free