wai-cors-0.2.7/0000755000000000000000000000000007346545000011435 5ustar0000000000000000wai-cors-0.2.7/CHANGELOG.md0000644000000000000000000000542407346545000013253 0ustar00000000000000000.2.7 (2019-06-06) ================== * Remove support for `wai<3` and older versions of GHC from the code base. * Fix a documentation bug [#23](https://github.com/larskuhtz/wai-cors/issues/23). 0.2.6 (2017-12-01) ================== * Removed ghc-7.6.3 and versions of wai<3.0 from the CI test matrix. These versions are still supported in the code but cabal may need some manual help to resolve dependencies. * Fixes and improvements to the documentation. Thanks to Frederik Hanghøj Iversen, Alex Collins, and Maximilian Tagher. 0.2.5 ===== * Support GHC-8.0.1. * Removed dependencies on parsers package. 0.2.4 ===== * Fix [bug #1](https://github.com/larskuhtz/wai-cors/issues/1). Response header `Vary: Origin` is now included when `corsVaryOrigin` is `True` and `corsOrigins` does not equal `Nothing`. 0.2.3 ===== * Added a test-suite to the package that uses PhantomJS to simulate a browser client. * Pass on websocket requests unchanged to the application. Add documentation that reminds the application author to check the `Origin` header for websocket requests. * Move development source repository from https://github.com/alephcloud/wai-cors to https://github.com/larskuhtz/wai-cors. 0.2.2 ===== * Support GHC-7.10/base-4.8 without compiler warnings. * Drop dependency on errors package. 0.2.1 ===== * Fix [bug #8](https://github.com/alephcloud/wai-cors/issues/8). Accept empty list as value for `Access-Control-Request-Headers`. 0.2 === This version may break existing code by changing the type of `CorsResourcePolicy`. This version changes the behavior of `simpleCorsResourcePolicy`: Before it was a failure when the request didn't contain an @Origin@ header. With this version the request is passed unchanged to the application. If an failure occurs during CORS processing the response has HTTP status 400 (bad request) and contains a short error messages. This behavior can be changed with the new settings `corsRequireOrigin` and `corsIgnorefailure`. * Remove setting `corsVerboseResponse` from `CorsResourcePolicy`. * Add new settings `corsRequireOrigin` and `corsIgnoreFailure` to `CorsResourcePolicy`. 0.1.4 ===== * Support wai-3 0.1.3 ===== * Improved documentation 0.1.2 ===== * Export type synonym `Origin` * New easy-to-use middleware function `simpleCors` that supports just simple cross-origin requests * The new value `simpleCorseResourcePolicy` is a `CorseResourcePolicy` for simple cross-origin requests. * Documentation has been slightly improved * Some code for testing `simpleCors` from a browser 0.1.1 ===== * Drop redundant dependencies on *lens* and *ghc-prim* * Fix typo in HTTP header field name `Access-Control-Allow-Credentials` 0.1.0 ===== * Initial version wai-cors-0.2.7/LICENSE0000644000000000000000000000214307346545000012442 0ustar0000000000000000Copyright (c) 2015-2019 Lars Kuhtz Copyright (c) 2014 AlephCloud Systems, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. wai-cors-0.2.7/README.md0000644000000000000000000000602607346545000012720 0ustar0000000000000000[![Build Status](https://travis-ci.org/larskuhtz/wai-cors.svg?branch=master)](https://travis-ci.org/larskuhtz/wai-cors) Cross-Origin Resource Sharing (CORS) For Wai ============================================ This package provides a Haskell implementation of CORS for [WAI](http://hackage.haskell.org/package/wai) that aims to be compliant with [http://www.w3.org/TR/cors](http://www.w3.org/TR/cors). Note On Security ---------------- This implementation doesn'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 the [CORS standard](http://wwww.w3.org/TR/cors). In particular the application should check that the value of the `Origin` header matches the expectations. Websocket connections don't support CORS and are ignored by the CORS implementation in this package. 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. Installation ------------ Assuming the availability of recent versions of [GHC](https://www.haskell.org/ghc/) and [cabal](https://www.haskell.org/cabal/) this package is installed via ```.bash cabal update cabal install wai-cors ``` Usage ----- 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. The file `examples/Scotty.hs` shows how to support simple cross-origin requests (as defined in [http://www.w3.org/TR/cors](http://www.w3.org/TR/cors)) in a [scotty](http://hackage.haskell.org/package/scotty) application. ```.haskell {-# 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: *`. ```.bash curl -i http://127.0.0.1:8080 -H 'Origin: 127.0.0.1' -v ``` Documentation for more general usage can be found in the module [Network.Wai.Middleware.Cors](http://hackage.haskell.org/package/wai-cors/docs/Network-Wai-Middleware-Cors.html). Test ---- In order to run the automated test suite [PhantomJS](http://phantomjs.org/) (at least version 2.0) must be installed in the system. ```.bash cabal install --only-dependencies --enable-tests cabal test --show-details=streaming ``` If [PhantomJS](http://phantomjs.org/) is not available the tests can be exectued manually in a modern web-browser as follows. Start the server application: ```.bash cd test ghc -main-is Server Server.hs ./Server ``` Open the file `test/index.html` in a modern web-browser. On page load a Javascript script is exectued that runs the test suite and prints the result on the page. wai-cors-0.2.7/Setup.hs0000644000000000000000000000005607346545000013072 0ustar0000000000000000import Distribution.Simple main = defaultMain wai-cors-0.2.7/examples/0000755000000000000000000000000007346545000013253 5ustar0000000000000000wai-cors-0.2.7/examples/Scotty.hs0000644000000000000000000000072607346545000015101 0ustar0000000000000000{-# LANGUAGE UnicodeSyntax #-} {-# LANGUAGE OverloadedStrings #-} -- | -- Module: Main -- Description: Exampe for using wai-cors with scotty -- Copyright: © 2015 Lars Kuhtz -- License: MIT -- Maintainer: Lars Kuhtz -- Stability: experimental -- module Main ( main ) where import Network.Wai.Middleware.Cors import Web.Scotty main ∷ IO () main = scotty 8080 $ do middleware simpleCors matchAny "/" $ text "Success" wai-cors-0.2.7/examples/ServantWai.hs0000644000000000000000000000232607346545000015675 0ustar0000000000000000{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} import Data.Aeson import Data.Aeson.TH import Network.Wai import Network.Wai.Handler.Warp import Network.Wai.Middleware.Cors import Servant data User = User { userId :: Int , userFirstName :: String , userLastName :: String } deriving (Eq, Show) $(deriveJSON defaultOptions ''User) type API = "users" :> Get '[JSON] [User] -- | Configure an Application with a CORS policy app :: Application app = (cors (const policy)) $ serve api server where policy = Just CorsResourcePolicy { corsOrigins = Nothing , corsMethods = ["GET"] , corsRequestHeaders = ["authorization", "content-type"] , corsExposedHeaders = Nothing , corsMaxAge = Just $ 60*60*24 -- one day , corsVaryOrigin = False , corsRequireOrigin = True , corsIgnoreFailures = False } api :: Proxy API api = Proxy server :: Server API server = return users users :: [User] users = [ User 1 "Isaac" "Newton" , User 2 "Albert" "Einstein" ] main :: IO () main = run 8080 app wai-cors-0.2.7/examples/Wai.hs0000644000000000000000000000107307346545000014330 0ustar0000000000000000{-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Wai -- Description: Example for using wai-cors with a plain wai app -- Copyright: Copyright © 2017 Lars Kuhtz . -- License: MIT -- Maintainer: Lars Kuhtz -- Stability: experimental -- module Wai ( main ) where import Network.HTTP.Types.Status import Network.Wai import Network.Wai.Middleware.Cors import Network.Wai.Handler.Warp main ∷ IO () main = run 8080 $ simpleCors $ echo echo ∷ Application echo req respond = respond . responseLBS ok200 [] =<< lazyRequestBody req wai-cors-0.2.7/src/Network/Wai/Middleware/0000755000000000000000000000000007346545000016452 5ustar0000000000000000wai-cors-0.2.7/src/Network/Wai/Middleware/Cors.hs0000644000000000000000000005123007346545000017715 0ustar0000000000000000{-# 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 -- Stability: stable -- -- An implemenation of Cross-Origin resource sharing (CORS) for WAI that -- aims to be compliant with . -- -- 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 . 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 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 -- (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 -- (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@. -- corsOrigins ∷ !(Maybe ([Origin], Bool)) -- | HTTP methods that are allowed in CORS requests. -- , 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. -- , corsRequestHeaders ∷ ![HTTP.HeaderName] -- | Field names of HTTP headers that are exposed to the client in the response. -- , 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. -- , 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. -- , 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 , 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 -- , corsIgnoreFailures ∷ !Bool } deriving (Show,Read,Eq,Ord) -- | A 'CorsResourcePolicy' that supports /simple cross-origin requests/ as defined -- in . -- -- * 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 { corsOrigins = Nothing , corsMethods = simpleMethods , corsRequestHeaders = [] , corsExposedHeaders = Nothing , corsMaxAge = Nothing , corsVaryOrigin = False , corsRequireOrigin = False , corsIgnoreFailures = 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 . 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 . -- -- /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 -- . -- -- * 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 policyPattern app r respond -- We don't handle websockets, even if they include an @Origin@ header | isWebSocketsReq r = runApp | Just policy ← policyPattern r = case hdrOrigin of -- No origin header: reject request Nothing → if corsRequireOrigin policy then res $ corsFailure "Origin header is missing" else runApp -- Origin header: apply CORS policy to request Just origin → applyCorsPolicy policy origin | otherwise = runApp where res = respond runApp = app r respond -- Lookup the HTTP origin request header -- hdrOrigin = lookup "origin" (WAI.requestHeaders r) -- Process a CORS request -- applyCorsPolicy policy origin = do -- The error continuation let err e = if corsIgnoreFailures policy then runApp else res $ corsFailure (B8.pack e) -- Match request origin with corsOrigins from policy let respOriginOrErr = case corsOrigins policy of Nothing → return Nothing Just (originList, withCreds) → if origin `elem` originList then Right $ Just (origin, withCreds) else Left $ "Unsupported origin: " ⊕ B8.unpack origin case respOriginOrErr of Left e → err e Right respOrigin → do -- Determine headers that are common to actuall responses and preflight responses let ch = commonCorsHeaders respOrigin (corsVaryOrigin policy) case WAI.requestMethod r of -- Preflight CORS request "OPTIONS" → runExceptT (preflightHeaders policy) >>= \case Left e → err e Right headers → res $ WAI.responseLBS HTTP.ok200 (ch ⊕ headers) "" -- Actual CORS request _ → addHeaders (ch ⊕ respCorsHeaders policy) app r respond -- Compute HTTP response headers for a preflight request -- preflightHeaders ∷ (Functor μ, Monad μ) ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders preflightHeaders policy = concat <$> sequence [ hdrReqMethod policy , hdrRequestHeader policy , hdrMaxAge policy ] hdrMaxAge ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders hdrMaxAge policy = case corsMaxAge policy of Nothing → return [] Just secs → return [("Access-Control-Max-Age", sshow secs)] hdrReqMethod ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders hdrReqMethod policy = case lookup "Access-Control-Request-Method" (WAI.requestHeaders r) of Nothing → throwError "Access-Control-Request-Method header is missing in CORS preflight request" Just x → if x `elem` supportedMethods then return [("Access-Control-Allow-Methods", hdrL supportedMethods)] else throwError $ "Method requested in Access-Control-Request-Method of CORS request is not supported; requested: " ⊕ B8.unpack x ⊕ "; supported are " ⊕ B8.unpack (hdrL supportedMethods) ⊕ "." where supportedMethods = corsMethods policy `union` simpleMethods hdrRequestHeader ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders hdrRequestHeader policy = case lookup "Access-Control-Request-Headers" (WAI.requestHeaders r) of Nothing → return [] Just hdrsBytes → do hdrs ← either throwError return $ P.parseOnly httpHeaderNameListParser hdrsBytes if hdrs `isSubsetOf` supportedHeaders then return [("Access-Control-Allow-Headers", hdrLI supportedHeaders)] else throwError $ "HTTP header requested in Access-Control-Request-Headers of CORS request is not supported; requested: " ⊕ B8.unpack (hdrLI hdrs) ⊕ "; supported are " ⊕ B8.unpack (hdrLI supportedHeaders) ⊕ "." where supportedHeaders = corsRequestHeaders policy `union` simpleHeadersWithoutContentType simpleHeadersWithoutContentType = simpleHeaders \\ ["content-type"] -- HTTP response headers that are common to normal and preflight CORS responses -- commonCorsHeaders ∷ Maybe (Origin, Bool) → Bool → HTTP.ResponseHeaders commonCorsHeaders Nothing _ = [("Access-Control-Allow-Origin", "*")] commonCorsHeaders (Just (o, creds)) vary = [] ⊕ (True ?? ("Access-Control-Allow-Origin", o)) ⊕ (creds ?? ("Access-Control-Allow-Credentials", "true")) ⊕ (vary ?? ("Vary", "Origin")) where (??) a b = if a then pure b else mempty -- HTTP response headers that are only used with normal CORS responses -- respCorsHeaders ∷ CorsResourcePolicy → HTTP.ResponseHeaders respCorsHeaders policy = catMaybes [ fmap (\x → ("Access-Control-Expose-Headers", hdrLI x)) (corsExposedHeaders 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 -- . 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 = cors (const $ Just simpleCorsResourcePolicy) -- -------------------------------------------------------------------------- -- -- Definition from Standards -- | Simple HTTP response headers as defined in -- simpleResponseHeaders ∷ [HTTP.HeaderName] simpleResponseHeaders = [ "Cache-Control" , "Content-Language" , "Content-Type" , "Expires" , "Last-Modified" , "Pragma" ] -- | Simple HTTP headers are defined in simpleHeaders ∷ [HTTP.HeaderName] simpleHeaders = [ "Accept" , "Accept-Language" , "Content-Language" , "Content-Type" ] -- | Simple content types are defined in simpleContentTypes ∷ [CI.CI B8.ByteString] simpleContentTypes = [ "application/x-www-form-urlencoded" , "multipart/form-data" , "text/plain" ] -- | Simple HTTP methods as defined in -- simpleMethods ∷ [HTTP.Method] simpleMethods = [ "GET" , "HEAD" , "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 method headers = method `elem` simpleMethods ∧ map fst headers `isSubsetOf` simpleHeaders ∧ case (method, lookup "content-type" headers) of ("POST", Just x) → CI.mk x `elem` simpleContentTypes _ → True -- | Valid characters for HTTP header names according to RFC2616 (section 4.2) -- isHttpHeaderNameChar ∷ Char → Bool isHttpHeaderNameChar c = (c ≥ toEnum 33) && (c ≤ toEnum 126) && P.notInClass "()<>@,;:\\\"/[]?={}" c httpHeaderNameParser ∷ P.Parser HTTP.HeaderName httpHeaderNameParser = fromString <$> P.many1 (P.satisfy isHttpHeaderNameChar) P. "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 = spaces *> P.sepBy (httpHeaderNameParser <* spaces) (P.char ',') <* spaces where spaces = P.many' P.space sshow ∷ (IsString α, Show β) ⇒ β → α sshow = fromString ∘ show isSubsetOf ∷ Eq α ⇒ [α] → [α] → Bool isSubsetOf l1 l2 = intersect l1 l2 ≡ l1 -- | Add HTTP headers to a WAI response -- addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware addHeaders hdrs app req respond = app req $ \response → do let (st, headers, streamHandle) = WAI.responseToStream response streamHandle $ \streamBody → respond $ WAI.responseStream st (headers ⊕ hdrs) 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 l = B8.intercalate ", " (map CI.original 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 = B8.intercalate ", " corsFailure ∷ B8.ByteString -- ^ body → WAI.Response corsFailure msg = WAI.responseLBS HTTP.status400 [("Content-Type", "text/html; charset-utf-8")] (LB8.fromStrict 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 req = fmap CI.mk (lookup "upgrade" $ WAI.requestHeaders req) == Just "websocket" wai-cors-0.2.7/test/0000755000000000000000000000000007346545000012414 5ustar0000000000000000wai-cors-0.2.7/test/PhantomJS.hs0000644000000000000000000000350407346545000014615 0ustar0000000000000000{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Main -- Description: Test suite that uses PhantomJS to simulate a browser -- Copyright: © 2015 Lars Kuhtz -- License: MIT -- Maintainer: Lars Kuhtz -- Stability: experimental -- module Main ( main ) where import Control.Concurrent import Data.Monoid.Unicode import Data.String import System.Directory import System.FilePath import System.Exit import System.IO import System.Process -- internal modules import qualified Server as Server phantomJsBinaryPath ∷ FilePath phantomJsBinaryPath = "phantomjs" phantomJsArgs ∷ IsString a ⇒ [a] phantomJsArgs = ["--ignore-ssl-errors=true"] -- phantomJsArgs = ["--ignore-ssl-errors=true", "--debug=true"] phantomJsScriptPath ∷ FilePath phantomJsScriptPath = "test/phantomjs.js" indexFilePath ∷ FilePath indexFilePath = "test/index.html" runPhantomJs ∷ IO () runPhantomJs = do -- check that phantomJS binary is available -- FIXME check the version findExecutable phantomJsBinaryPath >>= \case Nothing → do hPutStrLn stderr $ "Missing PhantomJS exectuable: in order to run this test-suite PhantomJS must be availabe on the system" exitFailure Just _ → return () pwd ← getCurrentDirectory -- FIXME I consider it an API bug of the directory package that in order -- to get the exit code we have also capture stdout and stderr. (code, out, err) ← readProcessWithExitCode phantomJsBinaryPath (args pwd) "" hPutStrLn stdout out hPutStrLn stderr err exitWith code where args pwd = phantomJsArgs ⊕ [phantomJsScriptPath] ⊕ [pwd indexFilePath] main ∷ IO () main = do _ ← forkIO $ Server.main runPhantomJs wai-cors-0.2.7/test/Server.hs0000644000000000000000000000622507346545000014223 0ustar0000000000000000{-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: Server -- Description: Test HTTP server for wai-cors -- Copyright: © 2015-2018 Lars Kuhtz . -- License: MIT -- Maintainer: Lars Kuhtz -- Stability: experimental -- module Server ( main ) where import Control.Concurrent import Control.Exception import Control.Monad import Network.Socket (withSocketsDo) import Network.Wai.Middleware.Cors import qualified Network.HTTP.Types as HTTP import qualified Network.Wai as WAI import qualified Network.Wai.Handler.Warp as WARP import qualified Network.Wai.Handler.WebSockets as WS import qualified Network.WebSockets as WS import qualified Data.Text as T main ∷ IO () main = withSocketsDo . WARP.run 8080 $ server -- -------------------------------------------------------------------------- -- -- Server application server ∷ WAI.Application server = cors corsPolicy $ \request → case WAI.pathInfo request of "cors":_ → corsapp request _ → testapp where testapp respond = respond $ WAI.responseFile HTTP.status200 [] "index.html" Nothing corsapp = WS.websocketsOr WS.defaultConnectionOptions wsserver $ \_ respond → respond $ WAI.responseLBS HTTP.status200 [] "Success" -- -------------------------------------------------------------------------- -- -- CORS Policy corsPolicy ∷ WAI.Request → Maybe CorsResourcePolicy corsPolicy request = case WAI.pathInfo request of "cors" : "non-simple":_ → Just nonSimplePolicy "cors" : "simple":_ → Just simpleCorsResourcePolicy _ → Nothing -- -------------------------------------------------------------------------- -- -- Websockets Server wsserver ∷ WS.ServerApp wsserver pc = do c ← WS.acceptRequest pc forever (go c) `catch` \case WS.CloseRequest _code _msg → WS.sendClose c ("closed" ∷ T.Text) e → throwIO e where go c = do msg ← WS.receiveDataMessage c forkIO $ WS.sendDataMessage c msg -- -------------------------------------------------------------------------- -- -- Non Simple Policy -- | Perform the following tests the following with this policy: -- -- * @Variy: Origin@ header is set on responses -- * @X-cors-test@ header is accepted -- * @X-cors-test@ header is exposed on response -- * @Access-Control-Allow-Origin@ header is set on responses to the request host -- * @DELETE@ requests are not allowed -- * @PUT@ requests are allowed -- * Requests that don't include an @Origin@ header result in 400 responses -- (it's not clear how to test this with a browser client) -- -- Note that Chrome sends @Origin: null@ when loaded from a "file://..." URL, -- PhantomJS sends "file://". -- nonSimplePolicy ∷ CorsResourcePolicy nonSimplePolicy = CorsResourcePolicy { corsOrigins = Just (["http://localhost:8080", "null", "file://"], False) , corsMethods = ["PUT"] , corsRequestHeaders = ["X-cors-test"] , corsExposedHeaders = Just ["X-cors-test", "Vary"] , corsMaxAge = Nothing , corsVaryOrigin = True , corsRequireOrigin = True , corsIgnoreFailures = False } wai-cors-0.2.7/test/UnitTests.hs0000644000000000000000000000756407346545000014726 0ustar0000000000000000{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnicodeSyntax #-} -- | -- Module: UnitTests -- Description: Unit Tests for wai-cors -- Copyright: © 2015-2018 Lars Kuhtz . -- License: MIT -- Maintainer: Lars Kuhtz -- Stability: experimental -- module Main ( main , post , patch , delete , put , get , options , head ) where import Network.Wai.Middleware.Cors import qualified Network.HTTP.Types as HTTP import qualified Network.Wai as WAI import Network.Wai.Test import Prelude hiding (head) import Test.Tasty import Test.Tasty.HUnit -- -------------------------------------------------------------------------- -- -- Unit tests main ∷ IO () main = defaultMain tests tests ∷ TestTree tests = testGroup "unit tests" [ testCase "Origins any" test_originsAny , testCase "Origins null" test_originsNull , testCase "Any Origin" test_anyOrigin , testCase "Require Origin" test_requireOrigin , testCase "Missing Require Origin" test_missingRequireOrigin , testCase "Vary Origin Header" test_varyOriginHeader , testCase "Vary Origin No Header" test_varyOriginNoHeader ] test_originsAny ∷ Assertion test_originsAny = corsSession policy $ do resp ← request get assertHeader "Access-Control-Allow-Origin" "*" resp assertStatus 200 resp where policy = simpleCorsResourcePolicy { corsOrigins = Nothing } test_originsNull ∷ Assertion test_originsNull = corsSession policy $ do resp ← request get assertHeader "Access-Control-Allow-Origin" "null" resp assertStatus 200 resp where policy = simpleCorsResourcePolicy { corsOrigins = Just (["null"], False) } test_missingRequireOrigin ∷ Assertion test_missingRequireOrigin = corsSession policy $ do resp ← request $ defaultRequest { WAI.requestMethod = "GET" } assertStatus 400 resp where policy = simpleCorsResourcePolicy { corsRequireOrigin = True } test_requireOrigin ∷ Assertion test_requireOrigin = corsSession policy $ do resp ← request get assertStatus 200 resp where policy = simpleCorsResourcePolicy { corsRequireOrigin = True } test_anyOrigin ∷ Assertion test_anyOrigin = corsSession policy $ do resp ← request get assertStatus 200 resp where policy = simpleCorsResourcePolicy { corsOrigins = Nothing } test_varyOriginHeader ∷ Assertion test_varyOriginHeader = corsSession policy $ do resp ← request put assertStatus 200 resp assertHeader "Vary" "Origin" resp where policy = simpleCorsResourcePolicy { corsOrigins = Just (["null"], False) , corsVaryOrigin = True } test_varyOriginNoHeader ∷ Assertion test_varyOriginNoHeader = corsSession policy $ do resp ← request put assertStatus 200 resp assertNoHeader "Vary" resp where policy = simpleCorsResourcePolicy { corsOrigins = Nothing , corsVaryOrigin = True } -- -------------------------------------------------------------------------- -- -- Test Requests corsSession ∷ CorsResourcePolicy → Session () → Assertion corsSession policy session = runSession session . cors (const $ Just policy) $ app corsRequest ∷ WAI.Request corsRequest = WAI.defaultRequest { WAI.pathInfo = ["cors"] , WAI.requestHeaders = [("Origin", "null")] } get, post, put, patch, delete, head, options ∷ WAI.Request get = corsRequest { WAI.requestMethod = "GET" } post = corsRequest { WAI.requestMethod = "POST" } put = corsRequest { WAI.requestMethod = "PUT" } patch = corsRequest { WAI.requestMethod = "PATCH" } delete = corsRequest { WAI.requestMethod = "DELETE" } head = corsRequest { WAI.requestMethod = "HEAD" } options = corsRequest { WAI.requestMethod = "OPTIONS" } app ∷ WAI.Application app _ respond = respond $ WAI.responseLBS HTTP.status200 [] "Success" wai-cors-0.2.7/test/index.html0000644000000000000000000002726407346545000014424 0ustar0000000000000000

Results

Websocket Test Results

wai-cors-0.2.7/test/phantomjs.js0000644000000000000000000000212607346545000014756 0ustar0000000000000000/* * Copyright (c) 2015 Lars Kuhtz */ var page = require('webpage').create(); var system = require('system'); var index = null; if (system.args.length === 1) { index = 'https://rawgit.com/alephcloud/wai-cors/master/test/index.html' } else if (system.args.length === 2) { index = 'file://' + system.args[1]; } else { console.log('Usage:'); console.log(' phantomjs phanomjs.js '); console.log(' phantomjs phanomjs.js'); phantom.exit(3); } page.open(index, function(status) { console.log("Status: " + status); if(status === "success") { console.log("test page loaded successfully"); } else { console.log("failed to load test page"); phantom.exit(2); } }); page.onCallback = function(data) { if (data.failures > 0) { console.log("Some tests failed"); console.log( page.plainText ); phantom.exit(1); } else { console.log( page.plainText ); phantom.exit(0); } } page.onConsoleMessage = function(msg) { system.stderr.writeLine('[CONSOLE] ' + msg); }; wai-cors-0.2.7/wai-cors.cabal0000644000000000000000000000553107346545000014151 0ustar0000000000000000-- ------------------------------------------------------ -- -- Copyright © 2015-2019 Lars Kuhtz -- Copyright © 2014 AlephCloud Systems, Inc. -- ------------------------------------------------------ -- Name: wai-cors Version: 0.2.7 Synopsis: CORS for WAI Description: This package provides an implemenation of Cross-Origin resource sharing (CORS) for that aims to be compliant with . Homepage: https://github.com/larskuhtz/wai-cors Bug-reports: https://github.com/larskuhtz/wai-cors/issues License: MIT License-file: LICENSE Author: Lars Kuhtz Maintainer: Lars Kuhtz Copyright: (c) 2015-2019 Lars Kuhtz , (c) 2014 AlephCloud Systems, Inc. Category: HTTP, Network, Web, Wai Build-type: Simple Cabal-version: 1.22 tested-with: GHC == 7.10.3 GHC == 8.0.2 GHC == 8.2.2 GHC == 8.4.4 GHC == 8.6.5 data-files: README.md CHANGELOG.md test/index.html test/phantomjs.js examples/Scotty.hs examples/Wai.hs examples/ServantWai.hs source-repository head type: git location: https://github.com/larskuhtz/wai-cors branch: master source-repository this type: git location: https://github.com/larskuhtz/wai-cors tag: 0.2.7 Library default-language: Haskell2010 hs-source-dirs: src exposed-modules: Network.Wai.Middleware.Cors build-depends: attoparsec >= 0.10.4.0, base >= 4.8 && <5.0, base-unicode-symbols >= 0.2.2.3, bytestring >= 0.10.0.2, case-insensitive >= 1.0.0.1, http-types >= 0.8.0, mtl >= 2.2, transformers >= 0.4, wai >= 3.0 ghc-options: -Wall Test-Suite phantomjs type: exitcode-stdio-1.0 default-language: Haskell2010 main-is: PhantomJS.hs hs-source-dirs: test other-modules: Server build-depends: base >= 4.8 && <5.0, base-unicode-symbols >= 0.2, directory >= 1.2, filepath >= 1.4, http-types >= 0.8, network >= 2.6, process >= 1.2, text >= 1.2, wai >= 3.0, wai-cors, wai-websockets >= 3.0, warp >= 3.0, websockets >= 0.9 ghc-options: -threaded -Wall -with-rtsopts=-N Test-Suite unit-tests type: exitcode-stdio-1.0 default-language: Haskell2010 main-is: UnitTests.hs hs-source-dirs: test build-depends: base >= 4.8 && <5.0, base-unicode-symbols >= 0.2, base-unicode-symbols >= 0.2, http-types >= 0.8, tasty >= 0.11, tasty-hunit >= 0.9, wai >= 3.0, wai-cors, wai-extra >= 3.0, wai-websockets >= 3.0.1, warp >= 3.0, websockets >= 0.10 ghc-options: -threaded -Wall -with-rtsopts=-N