Skip to content

Commit

Permalink
simplify csrf handler
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed Sep 20, 2017
1 parent a401f17 commit 255e4d4
Show file tree
Hide file tree
Showing 3 changed files with 6 additions and 15 deletions.
1 change: 0 additions & 1 deletion conf/base.conf
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,6 @@ security {
mailgun = ${mailgun}
net.domain = ${net.domain}
net.base_url = ${net.base_url}
csrf.enabled = true
}
recaptcha {
endpoint = "https://www.google.com/recaptcha/api/siteverify"
Expand Down
17 changes: 5 additions & 12 deletions modules/security/src/main/CSRFRequestHandler.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,14 @@ import play.api.mvc.RequestHeader

import lila.common.HTTPRequest._

final class CSRFRequestHandler(domain: String, enabled: Boolean) {
final class CSRFRequestHandler(domain: String) {

private def logger = lila.log("csrf")

def check(req: RequestHeader): Boolean = {
if (isXhr(req) || (isSafe(req) && !isSocket(req))) true
else origin(req).orElse(referer(req) flatMap refererToOrigin) match {
if (isXhr(req)) true // cross origin xhr not allowed by browsers
else if (isSafe(req) && !isSocket(req)) true
else origin(req) match {
case None =>
lila.mon.http.csrf.missingOrigin()
logger.debug(print(req))
Expand All @@ -27,7 +28,7 @@ final class CSRFRequestHandler(domain: String, enabled: Boolean) {
lila.mon.http.csrf.forbidden()
logger.info(print(req))
}
!enabled // ignore if disabled
false
}
}

Expand All @@ -38,12 +39,4 @@ final class CSRFRequestHandler(domain: String, enabled: Boolean) {
// domain = "lichess.org"
private def isSubdomain(origin: String) =
origin.endsWith(subDomain) || origin.endsWith(topDomain)

// input = "https://lichess.org/some/path?a=b&c=d"
// output = "https://lichess.org"
private val RefererToOriginRegex = """^([^:]+:https://[^/]+).*""".r // a.k.a. pokemon face regex
private def refererToOrigin(r: String): Option[String] = r match {
case RefererToOriginRegex(origin) => origin.some
case _ => none
}
}
3 changes: 1 addition & 2 deletions modules/security/src/main/Env.scala
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@ final class Env(
val RecaptchaEndpoint = config getString "recaptcha.endpoint"
val RecaptchaEnabled = config getBoolean "recaptcha.enabled"
val NetDomain = config getString "net.domain"
val CsrfEnabled = config getBoolean "csrf.enabled"
}
import settings._

Expand Down Expand Up @@ -132,7 +131,7 @@ final class Env(

lazy val api = new SecurityApi(storeColl, firewall, geoIP, emailAddressValidator)

lazy val csrfRequestHandler = new CSRFRequestHandler(NetDomain, enabled = CsrfEnabled)
lazy val csrfRequestHandler = new CSRFRequestHandler(NetDomain)

def cli = new Cli

Expand Down

0 comments on commit 255e4d4

Please sign in to comment.