{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE UnicodeSyntax #-}

-- |
-- Module: Network.Wai.Middleware.Cors
-- Description: Cross-Origin resource sharing (CORS) for WAI
-- Copyright:
--     © 2015-2019 Lars Kuhtz <lakuhtz@gmail.com,
--     © 2014 AlephCloud Systems, Inc.
-- License: MIT
-- Maintainer: Lars Kuhtz <lakuhtz@gmail.com>
-- Stability: stable
--
-- An implemenation of Cross-Origin resource sharing (CORS) for WAI that
-- aims to be compliant with <http://www.w3.org/TR/cors>.
--
-- The function 'simpleCors' enables support of simple cross-origin requests. More
-- advanced CORS policies can be enabled by passing a 'CorsResourcePolicy' to the
-- 'cors' middleware.
--
-- = Note On Security
--
-- This implementation doens't include any server side enforcement. By
-- complying with the CORS standard it enables the client (i.e. the web
-- browser) to enforce the CORS policy. For application authors it is strongly
-- recommended to take into account the security considerations in section 6.3
-- of <http://www.w3.org/TR/cors>. In particular the application should check
-- that the value of the @Origin@ header matches it's expectations.
--
-- = Websockets
--
-- Websocket connections don't support CORS and are ignored by this CORS
-- implementation. However Websocket requests usually (at least for some
-- browsers) include the @Origin@ header. Applications are expected to check
-- the value of this header and respond with an error in case that its content
-- doesn't match the expectations.
--
-- = Example
--
-- The following is an example how to enable support for simple cross-origin requests
-- for a <http://hackage.haskell.org/package/scotty scotty> application.
--
-- > {-# LANGUAGE UnicodeSyntax #-}
-- > {-# LANGUAGE OverloadedStrings #-}
-- >
-- > module Main
-- > ( main
-- > ) where
-- >
-- > import Network.Wai.Middleware.Cors
-- > import Web.Scotty
-- >
-- > main ∷ IO ()
-- > main = scotty 8080 $ do
-- >     middleware simpleCors
-- >     matchAny  "/" $ text "Success"
--
-- The result of following curl command will include the HTTP response header
-- @Access-Control-Allow-Origin: *@.
--
-- > curl -i http://127.0.0.1:8888 -H 'Origin: 127.0.0.1' -v
--
module Network.Wai.Middleware.Cors
( Origin
, CorsResourcePolicy(..)
, simpleCorsResourcePolicy
, cors
, simpleCors

-- * Utils
, isSimple
, simpleResponseHeaders
, simpleHeaders
, simpleContentTypes
, simpleMethods
) where

import Control.Monad.Error.Class
import Control.Monad.Trans.Except

import qualified Data.Attoparsec.ByteString.Char8 as P
import qualified Data.ByteString.Char8 as B8
import qualified Data.ByteString.Lazy.Char8 as LB8
import qualified Data.CaseInsensitive as CI
import Data.List (intersect, (\\), union)
import Data.Maybe (catMaybes)
import Data.Monoid.Unicode
import Data.String

import qualified Network.HTTP.Types as HTTP
import qualified Network.Wai as WAI

import Prelude.Unicode

-- | Origins are expected to be formated as described in
-- <https://www.ietf.org/rfc/rfc6454.txt RFC6454> (section 6.2).
-- In particular the string @*@ is not a valid origin (but the string
-- @null@ is).
--
type Origin = B8.ByteString

data CorsResourcePolicy = CorsResourcePolicy
    {

    -- | HTTP origins that are allowed in CORS requests.
    --
    -- A value of 'Nothing' indicates unrestricted cross-origin sharing and
    -- results in @*@ as value for the @Access-Control-Allow-Origin@ HTTP
    -- response header. Note if you send @*@, credentials cannot be sent with the request.
    --
    -- A value other than 'Nothing' is a tuple that consists of a list of
    -- origins and a Boolean flag that indicates if credentials are used
    -- to access the resource via CORS.
    --
    -- Origins must be formated as described in
    -- <https://www.ietf.org/rfc/rfc6454.txt RFC6454> (section 6.2). In
    -- particular the string @*@ is not a valid origin (but the string @null@
    -- is).
    --
    -- Credentials include cookies, authorization headers and TLS client certificates.
    -- For credentials to be sent with requests, the @withCredentials@ setting of
    -- @XmlHttpRequest@ in the browser must be set to @true@.
    --
       CorsResourcePolicy -> Maybe ([Origin], Bool)
corsOrigins  !(Maybe ([Origin], Bool))

    -- | HTTP methods that are allowed in CORS requests.
    --
    , CorsResourcePolicy -> [Origin]
corsMethods  ![HTTP.Method]

    -- | Field names of HTTP request headers that are allowed in CORS requests.
    -- Header names that are included in 'simpleHeaders', except for
    -- @content-type@, are implicitly included and thus optional in this list.
    --
    , CorsResourcePolicy -> [HeaderName]
corsRequestHeaders  ![HTTP.HeaderName]

    -- | Field names of HTTP headers that are exposed to the client in the response.
    --
    , CorsResourcePolicy -> Maybe [HeaderName]
corsExposedHeaders  !(Maybe [HTTP.HeaderName])

    -- | Number of seconds that the OPTIONS preflight response may be cached by the client.
    --
    -- Tip: Set this to 'Nothing' while testing your CORS implementation, then increase
    -- it once you deploy to production.
    --
    , CorsResourcePolicy -> Maybe Int
corsMaxAge  !(Maybe Int)

    -- | If the resource is shared by multiple origins but
    -- @Access-Control-Allow-Origin@ is not set to @*@ this may be set to
    -- 'True' to cause the server to include a @Vary: Origin@ header in the
    -- response, thus indicating that the value of the
    -- @Access-Control-Allow-Origin@ header may vary between different requests
    -- for the same resource. This prevents caching of the responses which may
    -- not apply accross different origins.
    --
    , CorsResourcePolicy -> Bool
corsVaryOrigin  !Bool

    -- | If this is 'True' and the request does not include an @Origin@ header
    -- the response has HTTP status 400 (bad request) and the body contains
    -- a short error message.
    --
    -- If this is 'False' and the request does not include an @Origin@ header
    -- the request is passed on unchanged to the application.
    --
    -- @since 0.2
    , CorsResourcePolicy -> Bool
corsRequireOrigin  !Bool

    -- | In the case that
    --
    -- * the request contains an @Origin@ header and
    --
    -- * the client does not conform with the CORS protocol
    --   (/request is out of scope/)
    --
    -- then
    --
    -- * the request is passed on unchanged to the application if this field is
    --   'True' or
    --
    -- * an response with HTTP status 400 (bad request) and short
    --   error message is returned if this field is 'False'.
    --
    -- Note: Your application needs to will receive preflight OPTIONS requests if set to 'True'.
    --
    -- @since 0.2
    --
    , CorsResourcePolicy -> Bool
corsIgnoreFailures  !Bool
    }
    deriving (Int -> CorsResourcePolicy -> ShowS
[CorsResourcePolicy] -> ShowS
CorsResourcePolicy -> String
(Int -> CorsResourcePolicy -> ShowS)
-> (CorsResourcePolicy -> String)
-> ([CorsResourcePolicy] -> ShowS)
-> Show CorsResourcePolicy
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [CorsResourcePolicy] -> ShowS
$cshowList :: [CorsResourcePolicy] -> ShowS
show :: CorsResourcePolicy -> String
$cshow :: CorsResourcePolicy -> String
showsPrec :: Int -> CorsResourcePolicy -> ShowS
$cshowsPrec :: Int -> CorsResourcePolicy -> ShowS
Show,ReadPrec [CorsResourcePolicy]
ReadPrec CorsResourcePolicy
Int -> ReadS CorsResourcePolicy
ReadS [CorsResourcePolicy]
(Int -> ReadS CorsResourcePolicy)
-> ReadS [CorsResourcePolicy]
-> ReadPrec CorsResourcePolicy
-> ReadPrec [CorsResourcePolicy]
-> Read CorsResourcePolicy
forall a.
(Int -> ReadS a)
-> ReadS [a] -> ReadPrec a -> ReadPrec [a] -> Read a
readListPrec :: ReadPrec [CorsResourcePolicy]
$creadListPrec :: ReadPrec [CorsResourcePolicy]
readPrec :: ReadPrec CorsResourcePolicy
$creadPrec :: ReadPrec CorsResourcePolicy
readList :: ReadS [CorsResourcePolicy]
$creadList :: ReadS [CorsResourcePolicy]
readsPrec :: Int -> ReadS CorsResourcePolicy
$creadsPrec :: Int -> ReadS CorsResourcePolicy
Read,CorsResourcePolicy -> CorsResourcePolicy -> Bool
(CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> (CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> Eq CorsResourcePolicy
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c/= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
== :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c== :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
Eq,Eq CorsResourcePolicy
Eq CorsResourcePolicy
-> (CorsResourcePolicy -> CorsResourcePolicy -> Ordering)
-> (CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> (CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> (CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> (CorsResourcePolicy -> CorsResourcePolicy -> Bool)
-> (CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy)
-> (CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy)
-> Ord CorsResourcePolicy
CorsResourcePolicy -> CorsResourcePolicy -> Bool
CorsResourcePolicy -> CorsResourcePolicy -> Ordering
CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy
$cmin :: CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy
max :: CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy
$cmax :: CorsResourcePolicy -> CorsResourcePolicy -> CorsResourcePolicy
>= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c>= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
> :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c> :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
<= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c<= :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
< :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
$c< :: CorsResourcePolicy -> CorsResourcePolicy -> Bool
compare :: CorsResourcePolicy -> CorsResourcePolicy -> Ordering
$ccompare :: CorsResourcePolicy -> CorsResourcePolicy -> Ordering
$cp1Ord :: Eq CorsResourcePolicy
Ord)

-- | A 'CorsResourcePolicy' that supports /simple cross-origin requests/ as defined
-- in <http://www.w3.org/TR/cors/>.
--
-- * The HTTP header @Access-Control-Allow-Origin@ is set to @*@.
--
-- * Request methods are constraint to /simple methods/ (@GET@, @HEAD@, @POST@).
--
-- * Request headers are constraint to /simple request headers/
--   (@Accept@, @Accept-Language@, @Content-Language@, @Content-Type@).
--
-- * If the request is a @POST@ request the content type is constraint to
--    /simple content types/
--    (@application/x-www-form-urlencoded@, @multipart/form-data@, @text/plain@),
--
-- * Only /simple response headers/ may be exposed on the client
--   (@Cache-Control@, @Content-Language@, @Content-Type@, @Expires@, @Last-Modified@,  @Pragma@)
--
-- * The @Vary-Origin@ header is left unchanged (possibly unset).
--
-- * If the request doesn't include an @Origin@ header the request is passed unchanged to
--   the application.
--
-- * If the request includes an @Origin@ header but does not conform to the CORS
--   protocol (/request is out of scope/) an response with HTTP status 400 (bad request)
--   and a short error message is returned.
--
-- For /simple cross-origin requests/ a preflight request is not required. However, if
-- the client chooses to make a preflight request it is answered in accordance with
-- the policy for /simple cross-origin requests/.
--
simpleCorsResourcePolicy  CorsResourcePolicy
simpleCorsResourcePolicy :: CorsResourcePolicy
simpleCorsResourcePolicy = CorsResourcePolicy :: Maybe ([Origin], Bool)
-> [Origin]
-> [HeaderName]
-> Maybe [HeaderName]
-> Maybe Int
-> Bool
-> Bool
-> Bool
-> CorsResourcePolicy
CorsResourcePolicy
    { corsOrigins :: Maybe ([Origin], Bool)
corsOrigins = Maybe ([Origin], Bool)
forall a. Maybe a
Nothing
    , corsMethods :: [Origin]
corsMethods = [Origin]
simpleMethods
    , corsRequestHeaders :: [HeaderName]
corsRequestHeaders = []
    , corsExposedHeaders :: Maybe [HeaderName]
corsExposedHeaders = Maybe [HeaderName]
forall a. Maybe a
Nothing
    , corsMaxAge :: Maybe Int
corsMaxAge = Maybe Int
forall a. Maybe a
Nothing
    , corsVaryOrigin :: Bool
corsVaryOrigin = Bool
False
    , corsRequireOrigin :: Bool
corsRequireOrigin = Bool
False
    , corsIgnoreFailures :: Bool
corsIgnoreFailures = Bool
False
    }

-- | A Cross-Origin resource sharing (CORS) middleware.
--
-- The middleware is given a function that serves as a pattern to decide
-- whether a requested resource is available for CORS. If the match fails with
-- 'Nothing' the request is passed unmodified to the inner application.
--
-- The current version of this module does only aim at compliance with the CORS
-- protocol as specified in <http://www.w3.org/TR/cors/>. In accordance with
-- that standard the role of the server side is to support the client to
-- enforce CORS restrictions. This module does not implement any enforcement of
-- authorization policies that are possibly implied by the
-- 'CorsResourcePolicy'. It is up to the inner WAI application to enforce such
-- policy and make sure that it is in accordance with the configuration of the
-- 'cors' middleware.
--
-- Matches are done as follows: @*@ matches every origin. For all other cases a
-- match succeeds if and only if the ASCII serializations (as described in
-- RCF6454 section 6.2) are equal.
--
-- The OPTIONS method may return options for resources that are not actually
-- available. In particular for preflight requests the implementation returns
-- for the HTTP response headers @Access-Control-Allow-Headers@ and
-- @Access-Control-Allow-Methods@ all values specified in the
-- 'CorsResourcePolicy' together with the respective values for simple requests
-- (except @content-type@). This does not imply that the application actually
-- supports the respective values are for the requested resource. Thus,
-- depending on the application, an actual request may still fail with 404 even
-- if the preflight request /supported/ the usage of the HTTP method with CORS.
--
-- The implementation does not distinguish between simple requests and requests
-- that require preflight. The client is free to omit a preflight request or do
-- a preflight request in cases when it wouldn't be required.
--
-- For application authors it is strongly recommended to take into account the
-- security considerations in section 6.3 of <http://www.w3.org/TR/cors>.
--
-- /TODO/
--
-- * We may consider adding optional enforcment aspects to this module: we may
--   check if a request respects our origin restrictions and we may check that a
--   CORS request respects the restrictions that we publish in the preflight
--   responses.
--
-- * Even though slightly out of scope we may (optionally) check if
--   host header matches the actual host of the resource, since clients
--   using CORS may expect this, since this check is recommended in
--   <http://www.w3.org/TR/cors>.
--
-- * We may consider integrating CORS policy handling more closely with the
--   handling of the source, for instance by integrating with 'ActionM' from
--   scotty.
--
cors
     (WAI.Request  Maybe CorsResourcePolicy) -- ^ A value of 'Nothing' indicates that the resource is not available for CORS
     WAI.Middleware
cors :: (Request -> Maybe CorsResourcePolicy) -> Middleware
cors Request -> Maybe CorsResourcePolicy
policyPattern Application
app Request
r Response -> IO ResponseReceived
respond
    -- We don't handle websockets, even if they include an @Origin@ header
    | Request -> Bool
isWebSocketsReq Request
r = IO ResponseReceived
runApp

    | Just CorsResourcePolicy
policy  Request -> Maybe CorsResourcePolicy
policyPattern Request
r = case Maybe Origin
hdrOrigin of

        -- No origin header: reject request
        Maybe Origin
Nothing  if CorsResourcePolicy -> Bool
corsRequireOrigin CorsResourcePolicy
policy
            then Response -> IO ResponseReceived
res (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Origin -> Response
corsFailure Origin
"Origin header is missing"
            else IO ResponseReceived
runApp

        -- Origin header: apply CORS policy to request
        Just Origin
origin  CorsResourcePolicy -> Origin -> IO ResponseReceived
applyCorsPolicy CorsResourcePolicy
policy Origin
origin

    | Bool
otherwise = IO ResponseReceived
runApp
  where
    res :: Response -> IO ResponseReceived
res = Response -> IO ResponseReceived
respond
    runApp :: IO ResponseReceived
runApp = Application
app Request
r Response -> IO ResponseReceived
respond

    -- Lookup the HTTP origin request header
    --
    hdrOrigin :: Maybe Origin
hdrOrigin = HeaderName -> [(HeaderName, Origin)] -> Maybe Origin
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"origin" (Request -> [(HeaderName, Origin)]
WAI.requestHeaders Request
r)

    -- Process a CORS request
    --
    applyCorsPolicy :: CorsResourcePolicy -> Origin -> IO ResponseReceived
applyCorsPolicy CorsResourcePolicy
policy Origin
origin = do

        -- The error continuation
        let err :: String -> IO ResponseReceived
err String
e = if CorsResourcePolicy -> Bool
corsIgnoreFailures CorsResourcePolicy
policy
            then IO ResponseReceived
runApp
            else Response -> IO ResponseReceived
res (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Origin -> Response
corsFailure (String -> Origin
B8.pack String
e)

        -- Match request origin with corsOrigins from policy
        let respOriginOrErr :: Either String (Maybe (Origin, Bool))
respOriginOrErr = case CorsResourcePolicy -> Maybe ([Origin], Bool)
corsOrigins CorsResourcePolicy
policy of
                Maybe ([Origin], Bool)
Nothing  Maybe (Origin, Bool) -> Either String (Maybe (Origin, Bool))
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Origin, Bool)
forall a. Maybe a
Nothing
                Just ([Origin]
originList, Bool
withCreds)  if Origin
origin Origin -> [Origin] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Origin]
originList
                    then Maybe (Origin, Bool) -> Either String (Maybe (Origin, Bool))
forall a b. b -> Either a b
Right (Maybe (Origin, Bool) -> Either String (Maybe (Origin, Bool)))
-> Maybe (Origin, Bool) -> Either String (Maybe (Origin, Bool))
forall a b. (a -> b) -> a -> b
$ (Origin, Bool) -> Maybe (Origin, Bool)
forall a. a -> Maybe a
Just (Origin
origin, Bool
withCreds)
                    else String -> Either String (Maybe (Origin, Bool))
forall a b. a -> Either a b
Left (String -> Either String (Maybe (Origin, Bool)))
-> String -> Either String (Maybe (Origin, Bool))
forall a b. (a -> b) -> a -> b
$ String
"Unsupported origin: " String -> ShowS
forall α. Monoid α => α -> α -> α
 Origin -> String
B8.unpack Origin
origin

        case Either String (Maybe (Origin, Bool))
respOriginOrErr of
            Left String
e  String -> IO ResponseReceived
err String
e
            Right Maybe (Origin, Bool)
respOrigin  do

                -- Determine headers that are common to actuall responses and preflight responses
                let ch :: [(HeaderName, Origin)]
ch = Maybe (Origin, Bool) -> Bool -> [(HeaderName, Origin)]
commonCorsHeaders Maybe (Origin, Bool)
respOrigin (CorsResourcePolicy -> Bool
corsVaryOrigin CorsResourcePolicy
policy)

                case Request -> Origin
WAI.requestMethod Request
r of

                    -- Preflight CORS request
                    Origin
"OPTIONS"  ExceptT String IO [(HeaderName, Origin)]
-> IO (Either String [(HeaderName, Origin)])
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (CorsResourcePolicy -> ExceptT String IO [(HeaderName, Origin)]
forall (μ :: * -> *).
(Functor μ, Monad μ) =>
CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
preflightHeaders CorsResourcePolicy
policy) IO (Either String [(HeaderName, Origin)])
-> (Either String [(HeaderName, Origin)] -> IO ResponseReceived)
-> IO ResponseReceived
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                        Left String
e  String -> IO ResponseReceived
err String
e
                        Right [(HeaderName, Origin)]
headers  Response -> IO ResponseReceived
res (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Status -> [(HeaderName, Origin)] -> ByteString -> Response
WAI.responseLBS Status
HTTP.ok200 ([(HeaderName, Origin)]
ch [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 [(HeaderName, Origin)]
headers) ByteString
""

                    -- Actual CORS request
                    Origin
_  [(HeaderName, Origin)] -> Middleware
addHeaders ([(HeaderName, Origin)]
ch [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 CorsResourcePolicy -> [(HeaderName, Origin)]
respCorsHeaders CorsResourcePolicy
policy) Application
app Request
r Response -> IO ResponseReceived
respond

    -- Compute HTTP response headers for a preflight request
    --
    preflightHeaders  (Functor μ, Monad μ)  CorsResourcePolicy  ExceptT String μ HTTP.ResponseHeaders
    preflightHeaders :: CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
preflightHeaders CorsResourcePolicy
policy = [[(HeaderName, Origin)]] -> [(HeaderName, Origin)]
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat ([[(HeaderName, Origin)]] -> [(HeaderName, Origin)])
-> ExceptT String μ [[(HeaderName, Origin)]]
-> ExceptT String μ [(HeaderName, Origin)]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [ExceptT String μ [(HeaderName, Origin)]]
-> ExceptT String μ [[(HeaderName, Origin)]]
forall (t :: * -> *) (m :: * -> *) a.
(Traversable t, Monad m) =>
t (m a) -> m (t a)
sequence
        [ CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
forall (μ :: * -> *).
Monad μ =>
CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrReqMethod CorsResourcePolicy
policy
        , CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
forall (μ :: * -> *).
Monad μ =>
CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrRequestHeader CorsResourcePolicy
policy
        , CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
forall (μ :: * -> *).
Monad μ =>
CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrMaxAge CorsResourcePolicy
policy
        ]

    hdrMaxAge  Monad μ  CorsResourcePolicy  ExceptT String μ HTTP.ResponseHeaders
    hdrMaxAge :: CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrMaxAge CorsResourcePolicy
policy = case CorsResourcePolicy -> Maybe Int
corsMaxAge CorsResourcePolicy
policy of
        Maybe Int
Nothing  [(HeaderName, Origin)] -> ExceptT String μ [(HeaderName, Origin)]
forall (m :: * -> *) a. Monad m => a -> m a
return []
        Just Int
secs  [(HeaderName, Origin)] -> ExceptT String μ [(HeaderName, Origin)]
forall (m :: * -> *) a. Monad m => a -> m a
return [(HeaderName
"Access-Control-Max-Age", Int -> Origin
forall α β. (IsString α, Show β) => β -> α
sshow Int
secs)]

    hdrReqMethod  Monad μ  CorsResourcePolicy  ExceptT String μ HTTP.ResponseHeaders
    hdrReqMethod :: CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrReqMethod CorsResourcePolicy
policy = case HeaderName -> [(HeaderName, Origin)] -> Maybe Origin
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"Access-Control-Request-Method" (Request -> [(HeaderName, Origin)]
WAI.requestHeaders Request
r) of
        Maybe Origin
Nothing  String -> ExceptT String μ [(HeaderName, Origin)]
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError String
"Access-Control-Request-Method header is missing in CORS preflight request"
        Just Origin
x  if  Origin
x Origin -> [Origin] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Origin]
supportedMethods
            then [(HeaderName, Origin)] -> ExceptT String μ [(HeaderName, Origin)]
forall (m :: * -> *) a. Monad m => a -> m a
return [(HeaderName
"Access-Control-Allow-Methods", [Origin] -> Origin
hdrL [Origin]
supportedMethods)]
            else String -> ExceptT String μ [(HeaderName, Origin)]
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError
                (String -> ExceptT String μ [(HeaderName, Origin)])
-> String -> ExceptT String μ [(HeaderName, Origin)]
forall a b. (a -> b) -> a -> b
$ String
"Method requested in Access-Control-Request-Method of CORS request is not supported; requested: "
                String -> ShowS
forall α. Monoid α => α -> α -> α
 Origin -> String
B8.unpack Origin
x
                String -> ShowS
forall α. Monoid α => α -> α -> α
 String
"; supported are "
                String -> ShowS
forall α. Monoid α => α -> α -> α
 Origin -> String
B8.unpack ([Origin] -> Origin
hdrL [Origin]
supportedMethods)
                String -> ShowS
forall α. Monoid α => α -> α -> α
 String
"."
      where
         supportedMethods :: [Origin]
supportedMethods = CorsResourcePolicy -> [Origin]
corsMethods CorsResourcePolicy
policy [Origin] -> [Origin] -> [Origin]
forall a. Eq a => [a] -> [a] -> [a]
`union` [Origin]
simpleMethods

    hdrRequestHeader  Monad μ  CorsResourcePolicy  ExceptT String μ HTTP.ResponseHeaders
    hdrRequestHeader :: CorsResourcePolicy -> ExceptT String μ [(HeaderName, Origin)]
hdrRequestHeader CorsResourcePolicy
policy = case HeaderName -> [(HeaderName, Origin)] -> Maybe Origin
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"Access-Control-Request-Headers" (Request -> [(HeaderName, Origin)]
WAI.requestHeaders Request
r) of
        Maybe Origin
Nothing  [(HeaderName, Origin)] -> ExceptT String μ [(HeaderName, Origin)]
forall (m :: * -> *) a. Monad m => a -> m a
return []
        Just Origin
hdrsBytes  do
            [HeaderName]
hdrs  (String -> ExceptT String μ [HeaderName])
-> ([HeaderName] -> ExceptT String μ [HeaderName])
-> Either String [HeaderName]
-> ExceptT String μ [HeaderName]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either String -> ExceptT String μ [HeaderName]
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError [HeaderName] -> ExceptT String μ [HeaderName]
forall (m :: * -> *) a. Monad m => a -> m a
return (Either String [HeaderName] -> ExceptT String μ [HeaderName])
-> Either String [HeaderName] -> ExceptT String μ [HeaderName]
forall a b. (a -> b) -> a -> b
$ Parser [HeaderName] -> Origin -> Either String [HeaderName]
forall a. Parser a -> Origin -> Either String a
P.parseOnly Parser [HeaderName]
httpHeaderNameListParser Origin
hdrsBytes
            if [HeaderName]
hdrs [HeaderName] -> [HeaderName] -> Bool
forall α. Eq α => [α] -> [α] -> Bool
`isSubsetOf` [HeaderName]
supportedHeaders
                then [(HeaderName, Origin)] -> ExceptT String μ [(HeaderName, Origin)]
forall (m :: * -> *) a. Monad m => a -> m a
return [(HeaderName
"Access-Control-Allow-Headers", [HeaderName] -> Origin
hdrLI [HeaderName]
supportedHeaders)]
                else String -> ExceptT String μ [(HeaderName, Origin)]
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError
                    (String -> ExceptT String μ [(HeaderName, Origin)])
-> String -> ExceptT String μ [(HeaderName, Origin)]
forall a b. (a -> b) -> a -> b
$ String
"HTTP header requested in Access-Control-Request-Headers of CORS request is not supported; requested: "
                    String -> ShowS
forall α. Monoid α => α -> α -> α
 Origin -> String
B8.unpack ([HeaderName] -> Origin
hdrLI [HeaderName]
hdrs)
                    String -> ShowS
forall α. Monoid α => α -> α -> α
 String
"; supported are "
                    String -> ShowS
forall α. Monoid α => α -> α -> α
 Origin -> String
B8.unpack ([HeaderName] -> Origin
hdrLI [HeaderName]
supportedHeaders)
                    String -> ShowS
forall α. Monoid α => α -> α -> α
 String
"."
      where
        supportedHeaders :: [HeaderName]
supportedHeaders = CorsResourcePolicy -> [HeaderName]
corsRequestHeaders CorsResourcePolicy
policy [HeaderName] -> [HeaderName] -> [HeaderName]
forall a. Eq a => [a] -> [a] -> [a]
`union` [HeaderName]
simpleHeadersWithoutContentType

    simpleHeadersWithoutContentType :: [HeaderName]
simpleHeadersWithoutContentType = [HeaderName]
simpleHeaders [HeaderName] -> [HeaderName] -> [HeaderName]
forall a. Eq a => [a] -> [a] -> [a]
\\ [HeaderName
"content-type"]

    -- HTTP response headers that are common to normal and preflight CORS responses
    --
    commonCorsHeaders  Maybe (Origin, Bool)  Bool  HTTP.ResponseHeaders
    commonCorsHeaders :: Maybe (Origin, Bool) -> Bool -> [(HeaderName, Origin)]
commonCorsHeaders Maybe (Origin, Bool)
Nothing Bool
_ = [(HeaderName
"Access-Control-Allow-Origin", Origin
"*")]
    commonCorsHeaders (Just (Origin
o, Bool
creds)) Bool
vary = []
        [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 (Bool
True Bool -> (HeaderName, Origin) -> [(HeaderName, Origin)]
forall (f :: * -> *) a.
(Applicative f, Monoid (f a)) =>
Bool -> a -> f a
?? (HeaderName
"Access-Control-Allow-Origin", Origin
o))
        [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 (Bool
creds Bool -> (HeaderName, Origin) -> [(HeaderName, Origin)]
forall (f :: * -> *) a.
(Applicative f, Monoid (f a)) =>
Bool -> a -> f a
?? (HeaderName
"Access-Control-Allow-Credentials", Origin
"true"))
        [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 (Bool
vary Bool -> (HeaderName, Origin) -> [(HeaderName, Origin)]
forall (f :: * -> *) a.
(Applicative f, Monoid (f a)) =>
Bool -> a -> f a
?? (HeaderName
"Vary", Origin
"Origin"))
      where
        ?? :: Bool -> a -> f a
(??) Bool
a a
b = if Bool
a then a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure a
b else f a
forall a. Monoid a => a
mempty

    -- HTTP response headers that are only used with normal CORS responses
    --
    respCorsHeaders  CorsResourcePolicy  HTTP.ResponseHeaders
    respCorsHeaders :: CorsResourcePolicy -> [(HeaderName, Origin)]
respCorsHeaders CorsResourcePolicy
policy = [Maybe (HeaderName, Origin)] -> [(HeaderName, Origin)]
forall a. [Maybe a] -> [a]
catMaybes
        [ ([HeaderName] -> (HeaderName, Origin))
-> Maybe [HeaderName] -> Maybe (HeaderName, Origin)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (\[HeaderName]
x  (HeaderName
"Access-Control-Expose-Headers", [HeaderName] -> Origin
hdrLI [HeaderName]
x)) (CorsResourcePolicy -> Maybe [HeaderName]
corsExposedHeaders CorsResourcePolicy
policy)
        ]

-- | A CORS middleware that supports simple cross-origin requests for all
-- resources.
--
-- This middleware does not check if the resource corresponds to the
-- restrictions for simple requests. This is in accordance with
-- <http://www.w3.org/TR/cors/>. It is the responsibility of the
-- client (user-agent) to enforce CORS policy. The role of the server
-- is to provide the client with the respective policy constraints.
--
-- It is out of the scope of the this module if the server chooses to
-- enforce rules on its resources in relation to CORS policy itself.
--
simpleCors  WAI.Middleware
simpleCors :: Middleware
simpleCors = (Request -> Maybe CorsResourcePolicy) -> Middleware
cors (Maybe CorsResourcePolicy -> Request -> Maybe CorsResourcePolicy
forall a b. a -> b -> a
const (Maybe CorsResourcePolicy -> Request -> Maybe CorsResourcePolicy)
-> Maybe CorsResourcePolicy -> Request -> Maybe CorsResourcePolicy
forall a b. (a -> b) -> a -> b
$ CorsResourcePolicy -> Maybe CorsResourcePolicy
forall a. a -> Maybe a
Just CorsResourcePolicy
simpleCorsResourcePolicy)

-- -------------------------------------------------------------------------- --
-- Definition from Standards

-- | Simple HTTP response headers as defined in <https://www.w3.org/TR/cors/#simple-response-header>
--
simpleResponseHeaders  [HTTP.HeaderName]
simpleResponseHeaders :: [HeaderName]
simpleResponseHeaders =
    [ HeaderName
"Cache-Control"
    , HeaderName
"Content-Language"
    , HeaderName
"Content-Type"
    , HeaderName
"Expires"
    , HeaderName
"Last-Modified"
    , HeaderName
"Pragma"
    ]

-- | Simple HTTP headers are defined in <https://www.w3.org/TR/cors/#simple-header>
simpleHeaders  [HTTP.HeaderName]
simpleHeaders :: [HeaderName]
simpleHeaders =
    [ HeaderName
"Accept"
    , HeaderName
"Accept-Language"
    , HeaderName
"Content-Language"
    , HeaderName
"Content-Type"
    ]

-- | Simple content types are defined in <https://www.w3.org/TR/cors/#simple-header>
simpleContentTypes  [CI.CI B8.ByteString]
simpleContentTypes :: [HeaderName]
simpleContentTypes =
    [ HeaderName
"application/x-www-form-urlencoded"
    , HeaderName
"multipart/form-data"
    , HeaderName
"text/plain"
    ]


-- | Simple HTTP methods as defined in <https://www.w3.org/TR/cors/#simple-method>
--
simpleMethods  [HTTP.Method]
simpleMethods :: [Origin]
simpleMethods =
    [ Origin
"GET"
    , Origin
"HEAD"
    , Origin
"POST"
    ]

-- | Whether the given method and headers constitute a simple request,
-- i.e. the method is simple, all headers are simple, and, if a POST request,
-- the content-type is simple.
isSimple  HTTP.Method  HTTP.RequestHeaders  Bool
isSimple :: Origin -> [(HeaderName, Origin)] -> Bool
isSimple Origin
method [(HeaderName, Origin)]
headers
    = Origin
method Origin -> [Origin] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Origin]
simpleMethods
    Bool -> Bool -> Bool
 ((HeaderName, Origin) -> HeaderName)
-> [(HeaderName, Origin)] -> [HeaderName]
forall a b. (a -> b) -> [a] -> [b]
map (HeaderName, Origin) -> HeaderName
forall a b. (a, b) -> a
fst [(HeaderName, Origin)]
headers [HeaderName] -> [HeaderName] -> Bool
forall α. Eq α => [α] -> [α] -> Bool
`isSubsetOf` [HeaderName]
simpleHeaders
    Bool -> Bool -> Bool
 case (Origin
method, HeaderName -> [(HeaderName, Origin)] -> Maybe Origin
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"content-type" [(HeaderName, Origin)]
headers) of
        (Origin
"POST", Just Origin
x)  Origin -> HeaderName
forall s. FoldCase s => s -> CI s
CI.mk Origin
x HeaderName -> [HeaderName] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [HeaderName]
simpleContentTypes
        (Origin, Maybe Origin)
_  Bool
True

-- | Valid characters for HTTP header names according to RFC2616 (section 4.2)
--
isHttpHeaderNameChar  Char  Bool
isHttpHeaderNameChar :: Char -> Bool
isHttpHeaderNameChar Char
c = (Char
c Char -> Char -> Bool
forall α. Ord α => α -> α -> Bool
 Int -> Char
forall a. Enum a => Int -> a
toEnum Int
33) Bool -> Bool -> Bool
&& (Char
c Char -> Char -> Bool
forall α. Ord α => α -> α -> Bool
 Int -> Char
forall a. Enum a => Int -> a
toEnum Int
126) Bool -> Bool -> Bool
&& String -> Char -> Bool
P.notInClass String
"()<>@,;:\\\"/[]?={}" Char
c

httpHeaderNameParser  P.Parser HTTP.HeaderName
httpHeaderNameParser :: Parser HeaderName
httpHeaderNameParser = String -> HeaderName
forall a. IsString a => String -> a
fromString (String -> HeaderName) -> Parser Origin String -> Parser HeaderName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Parser Origin Char -> Parser Origin String
forall (f :: * -> *) a. Alternative f => f a -> f [a]
P.many1 ((Char -> Bool) -> Parser Origin Char
P.satisfy Char -> Bool
isHttpHeaderNameChar) Parser HeaderName -> String -> Parser HeaderName
forall i a. Parser i a -> String -> Parser i a
P.<?> String
"HTTP Header Name"

-- -------------------------------------------------------------------------- --
-- Generic Tools

-- | A comma separated list of whitespace surounded HTTP header names.
--
-- Note that 'P.space' includes @SP@ (32), @HT@ (9), @LF@ (10), @VT@ (11),
-- @NP@ (12), and @CR@ (13). RFC 2616 (2.2) only defines @SP@ (32) and
-- @LWS = [CRLF] 1*(SP | HT)@ as whitespace. That's fine here since neither
-- of these characters is allowed in header names.
--
httpHeaderNameListParser  P.Parser [HTTP.HeaderName]
httpHeaderNameListParser :: Parser [HeaderName]
httpHeaderNameListParser = Parser Origin String
spaces Parser Origin String -> Parser [HeaderName] -> Parser [HeaderName]
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f b
*> Parser HeaderName -> Parser Origin Char -> Parser [HeaderName]
forall (f :: * -> *) a s. Alternative f => f a -> f s -> f [a]
P.sepBy (Parser HeaderName
httpHeaderNameParser Parser HeaderName -> Parser Origin String -> Parser HeaderName
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser Origin String
spaces) (Char -> Parser Origin Char
P.char Char
',') Parser [HeaderName] -> Parser Origin String -> Parser [HeaderName]
forall (f :: * -> *) a b. Applicative f => f a -> f b -> f a
<* Parser Origin String
spaces
  where
    spaces :: Parser Origin String
spaces = Parser Origin Char -> Parser Origin String
forall (m :: * -> *) a. MonadPlus m => m a -> m [a]
P.many' Parser Origin Char
P.space

sshow  (IsString α, Show β)  β  α
sshow :: β -> α
sshow = String -> α
forall a. IsString a => String -> a
fromString (String -> α) -> (β -> String) -> β -> α
forall β γ α. (β -> γ) -> (α -> β) -> α -> γ
 β -> String
forall a. Show a => a -> String
show

isSubsetOf  Eq α  [α]  [α]  Bool
isSubsetOf :: [α] -> [α] -> Bool
isSubsetOf [α]
l1 [α]
l2 = [α] -> [α] -> [α]
forall a. Eq a => [a] -> [a] -> [a]
intersect [α]
l1 [α]
l2 [α] -> [α] -> Bool
forall α. Eq α => α -> α -> Bool
 [α]
l1

-- | Add HTTP headers to a WAI response
--
addHeaders  HTTP.ResponseHeaders  WAI.Middleware
addHeaders :: [(HeaderName, Origin)] -> Middleware
addHeaders [(HeaderName, Origin)]
hdrs Application
app Request
req Response -> IO ResponseReceived
respond = Application
app Request
req ((Response -> IO ResponseReceived) -> IO ResponseReceived)
-> (Response -> IO ResponseReceived) -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ \Response
response  do
    let (Status
st, [(HeaderName, Origin)]
headers, (StreamingBody -> IO ResponseReceived) -> IO ResponseReceived
streamHandle) = Response
-> (Status, [(HeaderName, Origin)],
    (StreamingBody -> IO ResponseReceived) -> IO ResponseReceived)
forall a.
Response
-> (Status, [(HeaderName, Origin)],
    (StreamingBody -> IO a) -> IO a)
WAI.responseToStream Response
response
    (StreamingBody -> IO ResponseReceived) -> IO ResponseReceived
streamHandle ((StreamingBody -> IO ResponseReceived) -> IO ResponseReceived)
-> (StreamingBody -> IO ResponseReceived) -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ \StreamingBody
streamBody 
        Response -> IO ResponseReceived
respond (Response -> IO ResponseReceived)
-> Response -> IO ResponseReceived
forall a b. (a -> b) -> a -> b
$ Status -> [(HeaderName, Origin)] -> StreamingBody -> Response
WAI.responseStream Status
st ([(HeaderName, Origin)]
headers [(HeaderName, Origin)]
-> [(HeaderName, Origin)] -> [(HeaderName, Origin)]
forall α. Monoid α => α -> α -> α
 [(HeaderName, Origin)]
hdrs) StreamingBody
streamBody

-- | Format a list of 'HTTP.HeaderName's such that it can be used as
-- an HTTP header value
--
hdrLI  [HTTP.HeaderName]  B8.ByteString
hdrLI :: [HeaderName] -> Origin
hdrLI [HeaderName]
l = Origin -> [Origin] -> Origin
B8.intercalate Origin
", " ((HeaderName -> Origin) -> [HeaderName] -> [Origin]
forall a b. (a -> b) -> [a] -> [b]
map HeaderName -> Origin
forall s. CI s -> s
CI.original [HeaderName]
l)

-- | Format a list of 'B8.ByteString's such that it can be used as
-- an HTTP header value
--
hdrL  [B8.ByteString]  B8.ByteString
hdrL :: [Origin] -> Origin
hdrL = Origin -> [Origin] -> Origin
B8.intercalate Origin
", "

corsFailure
     B8.ByteString -- ^ body
     WAI.Response
corsFailure :: Origin -> Response
corsFailure Origin
msg = Status -> [(HeaderName, Origin)] -> ByteString -> Response
WAI.responseLBS Status
HTTP.status400 [(HeaderName
"Content-Type", Origin
"text/html; charset-utf-8")] (Origin -> ByteString
LB8.fromStrict Origin
msg)

-- Copied from the [wai-websocket package](https://github.com/yesodweb/wai/blob/master/wai-websockets/Network/Wai/Handler/WebSockets.hs#L21)
--
isWebSocketsReq
     WAI.Request
     Bool
isWebSocketsReq :: Request -> Bool
isWebSocketsReq Request
req =
    (Origin -> HeaderName) -> Maybe Origin -> Maybe HeaderName
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Origin -> HeaderName
forall s. FoldCase s => s -> CI s
CI.mk (HeaderName -> [(HeaderName, Origin)] -> Maybe Origin
forall a b. Eq a => a -> [(a, b)] -> Maybe b
lookup HeaderName
"upgrade" ([(HeaderName, Origin)] -> Maybe Origin)
-> [(HeaderName, Origin)] -> Maybe Origin
forall a b. (a -> b) -> a -> b
$ Request -> [(HeaderName, Origin)]
WAI.requestHeaders Request
req) Maybe HeaderName -> Maybe HeaderName -> Bool
forall α. Eq α => α -> α -> Bool
== HeaderName -> Maybe HeaderName
forall a. a -> Maybe a
Just HeaderName
"websocket"