packages feed

yesod-csp-0.3.0.0: src/Yesod/Csp/TH.hs

{-# LANGUAGE OverloadedStrings #-}

module Yesod.Csp.TH (
    source
    , withSourceList
    , reportUri
    , reportTo
    , pluginTypes
    , sandbox
    , sandboxOptions
    , upgradeInsecureRequests
    , requireTrustedTypesFor
    , trustedTypes
    , directive
    , csp
  ) where

import           Codec.MIME.Parse          (parseMIMEType)
import           Control.Applicative
import           Data.Attoparsec.Text
import           Data.Generics
import           Data.List.NonEmpty        (NonEmpty (..))
import qualified Data.Text                 as T
import qualified Language.Haskell.TH       as TH
import           Language.Haskell.TH.Quote
import           Yesod.Csp

csp :: QuasiQuoter
csp = QuasiQuoter {
      quoteExp = \str -> do
        let c = parseOnly directive (T.pack str)
        case c of
          Left err -> error $ "csp parsing error: " ++ err -- compile time error
          Right x -> dataToExpQ (const Nothing `extQ` antiCsp) x
    , quotePat  = undefined
    , quoteType = undefined
    , quoteDec  = undefined
    }

antiCsp :: Source -> Maybe (TH.Q TH.Exp)
antiCsp (MetaSource x) = if T.isPrefixOf noncePrefix x
  then Just . return $ TH.AppE (TH.VarE (TH.mkName "nonce")) (TH.VarE (TH.mkName (T.unpack (nonceVar x))))
  else Just . return $ TH.AppE (TH.ConE (TH.mkName "Host")) (TH.VarE (TH.mkName (T.unpack x)))
  where noncePrefix = "nonce-"
        nonceVar = T.drop (T.length noncePrefix)
antiCsp _ = Nothing

metaSource :: Parser Source
metaSource = do
  _ <- char '$'
  x <- many (digit <|> letter <|> char '-')
  return $ MetaSource (T.pack x)

source :: Parser Source
source = wildcard
         <|> none
         <|> self
         <|> dataScheme
         <|> https
         <|> unsafeHashes
         <|> wasmUnsafeEval
         <|> hash
         <|> host
         <|> unsafeInline
         <|> unsafeEval
         <|> strictDynamic
         <|> parseNonce
         <|> metaSource
  where wildcard = string "*" *> pure Wildcard
        none = string "'none'" *> pure None
        self = string "'self'" *> pure Self
        dataScheme = string "data:" *> pure DataScheme
        parseNonce :: Parser Source
        parseNonce = do
          _ <- char '\''
          _ <- string "nonce"
          _ <- char '-'
          n <- takeTill (== '\'')
          _ <- char '\''
          return $ nonce n
        unsafeHashes = string "'unsafe-hashes'" *> pure UnsafeHashes
        wasmUnsafeEval = string "'wasm-unsafe-eval'" *> pure WasmUnsafeEval
        hash = do
          _ <- char '\''
          a <- (string "sha256" *> pure Sha256) <|> (string "sha384" *> pure Sha384) <|> (string "sha512" *> pure Sha512)
          _ <- char '-'
          h <- takeTill (== '\'')
          _ <- char '\''
          return $ Hash a h
        host :: Parser Source
        host = do
          u <- takeTill separated
          case escapeAndParseURI u of
            Nothing -> fail "host"
            Just uri -> return $ Host uri
        https = do
          _ <- string "https:"
          c <- peekChar
          case c of
            (Just ' ') -> return Https
            (Just ';') -> return Https
            Nothing -> return Https
            _ -> fail "https"
        -- quoted is the standard CSP form; unquoted is kept for compatibility
        keyword k = string ("'" <> k <> "'") <|> string k
        unsafeInline = keyword "unsafe-inline" *> pure UnsafeInline
        unsafeEval = keyword "unsafe-eval" *> pure UnsafeEval
        strictDynamic = keyword "strict-dynamic" *> pure StrictDynamic

separated :: Char -> Bool
separated x = x == ';' || x == ' '

-- Safe to head and tail these sources as they come from the `sepBy1` combinator
mkWithSource :: (NonEmpty Source -> Directive) -> [Source] -> Parser Directive
mkWithSource f x = pure $ f (head x :| tail x)

withSourceList :: Parser Directive
withSourceList = defaultSrc
                 <|> scriptSrc
                 <|> scriptSrc
                 <|> styleSrc
                 <|> imgSrc
                 <|> connectSrc
                 <|> fontSrc
                 <|> objectSrc
                 <|> mediaSrc
                 <|> frameSrc
                 <|> frameAncestors
                 <|> childSrc
                 <|> formAction
                 <|> workerSrc
                 <|> manifestSrc
                 <|> prefetchSrc
                 <|> baseUri
  where defaultSrc = d "default-src" DefaultSrc
        scriptSrc = d "script-src" ScriptSrc
        styleSrc = d "style-src" StyleSrc
        imgSrc = d "img-src" ImgSrc
        connectSrc = d "connect-src" ConnectSrc
        fontSrc = d "font-src" FontSrc
        objectSrc = d "object-src" ObjectSrc
        mediaSrc = d "media-src" MediaSrc
        frameSrc = d "frame-src" FrameSrc
        frameAncestors = d "frame-ancestors" FrameAncestors
        childSrc = d "child-src" ChildSrc
        formAction = d "form-action" FormAction
        workerSrc = d "worker-src" WorkerSrc
        manifestSrc = d "manifest-src" ManifestSrc
        prefetchSrc = d "prefetch-src" PrefetchSrc
        baseUri = d "base-uri" BaseUri
        d x y = string x >> s >> slist >>= mkWithSource y
        slist = sepBy1 source (char ' ')
        s = spaces

spaces :: Parser ()
spaces = many space *> pure ()

reportUri :: Parser Directive
reportUri = do
  _ <- string "report-uri"
  _ <- spaces
  u <- takeTill separated
  case escapeAndParseURI u of
    Nothing -> fail "reportUri" -- n.b. compile time error
    Just uri -> return $ ReportUri uri

reportTo :: Parser Directive
reportTo = do
  _ <- string "report-to"
  _ <- spaces
  g <- takeTill separated
  if T.null g
    then fail "reportTo" -- n.b. compile time error
    else return $ ReportTo g

pluginTypes :: Parser Directive
pluginTypes = do
  _ <- string "plugin-types"
  _ <- spaces
  u <- takeTill separated
  case parseMIMEType u of
    Nothing -> fail "plugin-types" -- n.b. compile time error
    Just mimeType -> return $ PluginTypes $ pure mimeType

sandbox :: Parser Directive
sandbox = do
  _ <- string "sandbox"
  _ <- spaces
  x <- sepBy sandboxOptions spaces
  return $ Sandbox x

sandboxOptions :: Parser SandboxOptions
-- longer names first, where one is a prefix of another
sandboxOptions = choice $ fmap (\(n, o) -> string n *> pure o)
  [ ("allow-forms", AllowForms)
  , ("allow-scripts", AllowScripts)
  , ("allow-same-origin", AllowSameOrigin)
  , ("allow-top-navigation-by-user-activation", AllowTopNavigationByUserActivation)
  , ("allow-top-navigation-to-custom-protocols", AllowTopNavigationToCustomProtocols)
  , ("allow-top-navigation", AllowTopNavigation)
  , ("allow-downloads", AllowDownloads)
  , ("allow-modals", AllowModals)
  , ("allow-orientation-lock", AllowOrientationLock)
  , ("allow-pointer-lock", AllowPointerLock)
  , ("allow-popups-to-escape-sandbox", AllowPopupsToEscapeSandbox)
  , ("allow-popups", AllowPopups)
  , ("allow-presentation", AllowPresentation)
  , ("allow-storage-access-by-user-activation", AllowStorageAccessByUserActivation)
  ]

upgradeInsecureRequests :: Parser Directive
upgradeInsecureRequests = string "upgrade-insecure-requests" *> pure UpgradeInsecureRequests

requireTrustedTypesFor :: Parser Directive
requireTrustedTypesFor = string "require-trusted-types-for" *> spaces *> string "'script'" *> pure RequireTrustedTypesForScript

trustedTypes :: Parser Directive
trustedTypes = do
  _ <- string "trusted-types"
  _ <- spaces
  ns <- sepBy (takeWhile1 (not . separated)) (char ' ')
  return $ TrustedTypes ns

separator :: Parser ()
separator = comma *> (spaces *> pure ())
  where comma = string ";"

directive :: Parser DirectiveList
directive = sepBy (spaces *> d) separator <* (spaces *> endOfInput)
  where d = withSourceList <|> reportUri <|> reportTo <|> pluginTypes <|> sandbox
            <|> upgradeInsecureRequests <|> requireTrustedTypesFor <|> trustedTypes