Debian Codegraph @

src/Network/Wai/Middleware/Cors.hs

raw
1 {-# LANGUAGE GADTs #-}
2 {-# LANGUAGE LambdaCase #-}
3 {-# LANGUAGE OverloadedStrings #-}
4 {-# LANGUAGE PatternGuards #-}
5 {-# LANGUAGE ScopedTypeVariables #-}
6 {-# LANGUAGE UnicodeSyntax #-}
7
8 -- |
9 -- Module: Network.Wai.Middleware.Cors
10 -- Description: Cross-Origin resource sharing (CORS) for WAI
11 -- Copyright:
12 -- © 2015-2019 Lars Kuhtz <[email protected],
13 -- © 2014 AlephCloud Systems, Inc.
14 -- License: MIT
15 -- Maintainer: Lars Kuhtz <[email protected]>
16 -- Stability: stable
17 --
18 -- An implemenation of Cross-Origin resource sharing (CORS) for WAI that
19 -- aims to be compliant with <http://www.w3.org/TR/cors>.
20 --
21 -- The function 'simpleCors' enables support of simple cross-origin requests. More
22 -- advanced CORS policies can be enabled by passing a 'CorsResourcePolicy' to the
23 -- 'cors' middleware.
24 --
25 -- = Note On Security
26 --
27 -- This implementation doens't include any server side enforcement. By
28 -- complying with the CORS standard it enables the client (i.e. the web
29 -- browser) to enforce the CORS policy. For application authors it is strongly
30 -- recommended to take into account the security considerations in section 6.3
31 -- of <http://www.w3.org/TR/cors>. In particular the application should check
32 -- that the value of the @Origin@ header matches it's expectations.
33 --
34 -- = Websockets
35 --
36 -- Websocket connections don't support CORS and are ignored by this CORS
37 -- implementation. However Websocket requests usually (at least for some
38 -- browsers) include the @Origin@ header. Applications are expected to check
39 -- the value of this header and respond with an error in case that its content
40 -- doesn't match the expectations.
41 --
42 -- = Example
43 --
44 -- The following is an example how to enable support for simple cross-origin requests
45 -- for a <http://hackage.haskell.org/package/scotty scotty> application.
46 --
47 -- > {-# LANGUAGE UnicodeSyntax #-}
48 -- > {-# LANGUAGE OverloadedStrings #-}
49 -- >
50 -- > module Main
51 -- > ( main
52 -- > ) where
53 -- >
54 -- > import Network.Wai.Middleware.Cors
55 -- > import Web.Scotty
56 -- >
57 -- > main ∷ IO ()
58 -- > main = scotty 8080 $ do
59 -- > middleware simpleCors
60 -- > matchAny "/" $ text "Success"
61 --
62 -- The result of following curl command will include the HTTP response header
63 -- @Access-Control-Allow-Origin: *@.
64 --
65 -- > curl -i http://127.0.0.1:8888 -H 'Origin: 127.0.0.1' -v
66 --
67 module Network.Wai.Middleware.Cors
68 ( Origin
69 , CorsResourcePolicy(..)
70 , simpleCorsResourcePolicy
71 , cors
72 , simpleCors
73
74 -- * Utils
75 , isSimple
76 , simpleResponseHeaders
77 , simpleHeaders
78 , simpleContentTypes
79 , simpleMethods
80 ) where
81
82 import Control.Monad.Error.Class
83 import Control.Monad.Trans.Except
84
85 import qualified Data.Attoparsec.ByteString.Char8 as P
86 import qualified Data.ByteString.Char8 as B8
87 import qualified Data.ByteString.Lazy.Char8 as LB8
88 import qualified Data.CaseInsensitive as CI
89 import Data.List (intersect, (\\), union)
90 import Data.Maybe (catMaybes)
91 import Data.Monoid.Unicode
92 import Data.String
93
94 import qualified Network.HTTP.Types as HTTP
95 import qualified Network.Wai as WAI
96
97 import Prelude.Unicode
98
99 -- | Origins are expected to be formated as described in
100 -- <https://www.ietf.org/rfc/rfc6454.txt RFC6454> (section 6.2).
101 -- In particular the string @*@ is not a valid origin (but the string
102 -- @null@ is).
103 --
104 type Origin = B8.ByteString
105
106 data CorsResourcePolicy = CorsResourcePolicy
107 {
108
109 -- | HTTP origins that are allowed in CORS requests.
110 --
111 -- A value of 'Nothing' indicates unrestricted cross-origin sharing and
112 -- results in @*@ as value for the @Access-Control-Allow-Origin@ HTTP
113 -- response header. Note if you send @*@, credentials cannot be sent with the request.
114 --
115 -- A value other than 'Nothing' is a tuple that consists of a list of
116 -- origins and a Boolean flag that indicates if credentials are used
117 -- to access the resource via CORS.
118 --
119 -- Origins must be formated as described in
120 -- <https://www.ietf.org/rfc/rfc6454.txt RFC6454> (section 6.2). In
121 -- particular the string @*@ is not a valid origin (but the string @null@
122 -- is).
123 --
124 -- Credentials include cookies, authorization headers and TLS client certificates.
125 -- For credentials to be sent with requests, the @withCredentials@ setting of
126 -- @XmlHttpRequest@ in the browser must be set to @true@.
127 --
128 corsOrigins ∷ !(Maybe ([Origin], Bool))
129
130 -- | HTTP methods that are allowed in CORS requests.
131 --
132 , corsMethods ∷ ![HTTP.Method]
133
134 -- | Field names of HTTP request headers that are allowed in CORS requests.
135 -- Header names that are included in 'simpleHeaders', except for
136 -- @content-type@, are implicitly included and thus optional in this list.
137 --
138 , corsRequestHeaders ∷ ![HTTP.HeaderName]
139
140 -- | Field names of HTTP headers that are exposed to the client in the response.
141 --
142 , corsExposedHeaders ∷ !(Maybe [HTTP.HeaderName])
143
144 -- | Number of seconds that the OPTIONS preflight response may be cached by the client.
145 --
146 -- Tip: Set this to 'Nothing' while testing your CORS implementation, then increase
147 -- it once you deploy to production.
148 --
149 , corsMaxAge ∷ !(Maybe Int)
150
151 -- | If the resource is shared by multiple origins but
152 -- @Access-Control-Allow-Origin@ is not set to @*@ this may be set to
153 -- 'True' to cause the server to include a @Vary: Origin@ header in the
154 -- response, thus indicating that the value of the
155 -- @Access-Control-Allow-Origin@ header may vary between different requests
156 -- for the same resource. This prevents caching of the responses which may
157 -- not apply accross different origins.
158 --
159 , corsVaryOrigin ∷ !Bool
160
161 -- | If this is 'True' and the request does not include an @Origin@ header
162 -- the response has HTTP status 400 (bad request) and the body contains
163 -- a short error message.
164 --
165 -- If this is 'False' and the request does not include an @Origin@ header
166 -- the request is passed on unchanged to the application.
167 --
168 -- @since 0.2
169 , corsRequireOrigin ∷ !Bool
170
171 -- | In the case that
172 --
173 -- * the request contains an @Origin@ header and
174 --
175 -- * the client does not conform with the CORS protocol
176 -- (/request is out of scope/)
177 --
178 -- then
179 --
180 -- * the request is passed on unchanged to the application if this field is
181 -- 'True' or
182 --
183 -- * an response with HTTP status 400 (bad request) and short
184 -- error message is returned if this field is 'False'.
185 --
186 -- Note: Your application needs to will receive preflight OPTIONS requests if set to 'True'.
187 --
188 -- @since 0.2
189 --
190 , corsIgnoreFailures ∷ !Bool
191 }
192 deriving (Show,Read,Eq,Ord)
193
194 -- | A 'CorsResourcePolicy' that supports /simple cross-origin requests/ as defined
195 -- in <http://www.w3.org/TR/cors/>.
196 --
197 -- * The HTTP header @Access-Control-Allow-Origin@ is set to @*@.
198 --
199 -- * Request methods are constraint to /simple methods/ (@GET@, @HEAD@, @POST@).
200 --
201 -- * Request headers are constraint to /simple request headers/
202 -- (@Accept@, @Accept-Language@, @Content-Language@, @Content-Type@).
203 --
204 -- * If the request is a @POST@ request the content type is constraint to
205 -- /simple content types/
206 -- (@application/x-www-form-urlencoded@, @multipart/form-data@, @text/plain@),
207 --
208 -- * Only /simple response headers/ may be exposed on the client
209 -- (@Cache-Control@, @Content-Language@, @Content-Type@, @Expires@, @Last-Modified@, @Pragma@)
210 --
211 -- * The @Vary-Origin@ header is left unchanged (possibly unset).
212 --
213 -- * If the request doesn't include an @Origin@ header the request is passed unchanged to
214 -- the application.
215 --
216 -- * If the request includes an @Origin@ header but does not conform to the CORS
217 -- protocol (/request is out of scope/) an response with HTTP status 400 (bad request)
218 -- and a short error message is returned.
219 --
220 -- For /simple cross-origin requests/ a preflight request is not required. However, if
221 -- the client chooses to make a preflight request it is answered in accordance with
222 -- the policy for /simple cross-origin requests/.
223 --
224 simpleCorsResourcePolicy ∷ CorsResourcePolicy
225 simpleCorsResourcePolicy = CorsResourcePolicy
226 { corsOrigins = Nothing
227 , corsMethods = simpleMethods
228 , corsRequestHeaders = []
229 , corsExposedHeaders = Nothing
230 , corsMaxAge = Nothing
231 , corsVaryOrigin = False
232 , corsRequireOrigin = False
233 , corsIgnoreFailures = False
234 }
235
236 -- | A Cross-Origin resource sharing (CORS) middleware.
237 --
238 -- The middleware is given a function that serves as a pattern to decide
239 -- whether a requested resource is available for CORS. If the match fails with
240 -- 'Nothing' the request is passed unmodified to the inner application.
241 --
242 -- The current version of this module does only aim at compliance with the CORS
243 -- protocol as specified in <http://www.w3.org/TR/cors/>. In accordance with
244 -- that standard the role of the server side is to support the client to
245 -- enforce CORS restrictions. This module does not implement any enforcement of
246 -- authorization policies that are possibly implied by the
247 -- 'CorsResourcePolicy'. It is up to the inner WAI application to enforce such
248 -- policy and make sure that it is in accordance with the configuration of the
249 -- 'cors' middleware.
250 --
251 -- Matches are done as follows: @*@ matches every origin. For all other cases a
252 -- match succeeds if and only if the ASCII serializations (as described in
253 -- RCF6454 section 6.2) are equal.
254 --
255 -- The OPTIONS method may return options for resources that are not actually
256 -- available. In particular for preflight requests the implementation returns
257 -- for the HTTP response headers @Access-Control-Allow-Headers@ and
258 -- @Access-Control-Allow-Methods@ all values specified in the
259 -- 'CorsResourcePolicy' together with the respective values for simple requests
260 -- (except @content-type@). This does not imply that the application actually
261 -- supports the respective values are for the requested resource. Thus,
262 -- depending on the application, an actual request may still fail with 404 even
263 -- if the preflight request /supported/ the usage of the HTTP method with CORS.
264 --
265 -- The implementation does not distinguish between simple requests and requests
266 -- that require preflight. The client is free to omit a preflight request or do
267 -- a preflight request in cases when it wouldn't be required.
268 --
269 -- For application authors it is strongly recommended to take into account the
270 -- security considerations in section 6.3 of <http://www.w3.org/TR/cors>.
271 --
272 -- /TODO/
273 --
274 -- * We may consider adding optional enforcment aspects to this module: we may
275 -- check if a request respects our origin restrictions and we may check that a
276 -- CORS request respects the restrictions that we publish in the preflight
277 -- responses.
278 --
279 -- * Even though slightly out of scope we may (optionally) check if
280 -- host header matches the actual host of the resource, since clients
281 -- using CORS may expect this, since this check is recommended in
282 -- <http://www.w3.org/TR/cors>.
283 --
284 -- * We may consider integrating CORS policy handling more closely with the
285 -- handling of the source, for instance by integrating with 'ActionM' from
286 -- scotty.
287 --
288 cors
289 ∷ (WAI.Request → Maybe CorsResourcePolicy) -- ^ A value of 'Nothing' indicates that the resource is not available for CORS
290 → WAI.Middleware
291 cors policyPattern app r respond
292 -- We don't handle websockets, even if they include an @Origin@ header
293 | isWebSocketsReq r = runApp
294
295 | Just policy ← policyPattern r = case hdrOrigin of
296
297 -- No origin header: reject request
298 Nothing → if corsRequireOrigin policy
299 then res $ corsFailure "Origin header is missing"
300 else runApp
301
302 -- Origin header: apply CORS policy to request
303 Just origin → applyCorsPolicy policy origin
304
305 | otherwise = runApp
306 where
307 res = respond
308 runApp = app r respond
309
310 -- Lookup the HTTP origin request header
311 --
312 hdrOrigin = lookup "origin" (WAI.requestHeaders r)
313
314 -- Process a CORS request
315 --
316 applyCorsPolicy policy origin = do
317
318 -- The error continuation
319 let err e = if corsIgnoreFailures policy
320 then runApp
321 else res $ corsFailure (B8.pack e)
322
323 -- Match request origin with corsOrigins from policy
324 let respOriginOrErr = case corsOrigins policy of
325 Nothing → return Nothing
326 Just (originList, withCreds) → if origin `elem` originList
327 then Right $ Just (origin, withCreds)
328 else Left $ "Unsupported origin: " ⊕ B8.unpack origin
329
330 case respOriginOrErr of
331 Left e → err e
332 Right respOrigin → do
333
334 -- Determine headers that are common to actuall responses and preflight responses
335 let ch = commonCorsHeaders respOrigin (corsVaryOrigin policy)
336
337 case WAI.requestMethod r of
338
339 -- Preflight CORS request
340 "OPTIONS" → runExceptT (preflightHeaders policy) >>= \case
341 Left e → err e
342 Right headers → res $ WAI.responseLBS HTTP.ok200 (ch ⊕ headers) ""
343
344 -- Actual CORS request
345 _ → addHeaders (ch ⊕ respCorsHeaders policy) app r respond
346
347 -- Compute HTTP response headers for a preflight request
348 --
349 preflightHeaders ∷ (Functor μ, Monad μ) ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
350 preflightHeaders policy = concat <$> sequence
351 [ hdrReqMethod policy
352 , hdrRequestHeader policy
353 , hdrMaxAge policy
354 ]
355
356 hdrMaxAge ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
357 hdrMaxAge policy = case corsMaxAge policy of
358 Nothing → return []
359 Just secs → return [("Access-Control-Max-Age", sshow secs)]
360
361 hdrReqMethod ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
362 hdrReqMethod policy = case lookup "Access-Control-Request-Method" (WAI.requestHeaders r) of
363 Nothing → throwError "Access-Control-Request-Method header is missing in CORS preflight request"
364 Just x → if x `elem` supportedMethods
365 then return [("Access-Control-Allow-Methods", hdrL supportedMethods)]
366 else throwError
367 $ "Method requested in Access-Control-Request-Method of CORS request is not supported; requested: "
368 ⊕ B8.unpack x
369 ⊕ "; supported are "
370 ⊕ B8.unpack (hdrL supportedMethods)
371 ⊕ "."
372 where
373 supportedMethods = corsMethods policy `union` simpleMethods
374
375 hdrRequestHeader ∷ Monad μ ⇒ CorsResourcePolicy → ExceptT String μ HTTP.ResponseHeaders
376 hdrRequestHeader policy = case lookup "Access-Control-Request-Headers" (WAI.requestHeaders r) of
377 Nothing → return []
378 Just hdrsBytes → do
379 hdrs ← either throwError return $ P.parseOnly httpHeaderNameListParser hdrsBytes
380 if hdrs `isSubsetOf` supportedHeaders
381 then return [("Access-Control-Allow-Headers", hdrLI supportedHeaders)]
382 else throwError
383 $ "HTTP header requested in Access-Control-Request-Headers of CORS request is not supported; requested: "
384 ⊕ B8.unpack (hdrLI hdrs)
385 ⊕ "; supported are "
386 ⊕ B8.unpack (hdrLI supportedHeaders)
387 ⊕ "."
388 where
389 supportedHeaders = corsRequestHeaders policy `union` simpleHeadersWithoutContentType
390
391 simpleHeadersWithoutContentType = simpleHeaders \\ ["content-type"]
392
393 -- HTTP response headers that are common to normal and preflight CORS responses
394 --
395 commonCorsHeaders ∷ Maybe (Origin, Bool) → Bool → HTTP.ResponseHeaders
396 commonCorsHeaders Nothing _ = [("Access-Control-Allow-Origin", "*")]
397 commonCorsHeaders (Just (o, creds)) vary = []
398 ⊕ (True ?? ("Access-Control-Allow-Origin", o))
399 ⊕ (creds ?? ("Access-Control-Allow-Credentials", "true"))
400 ⊕ (vary ?? ("Vary", "Origin"))
401 where
402 (??) a b = if a then pure b else mempty
403
404 -- HTTP response headers that are only used with normal CORS responses
405 --
406 respCorsHeaders ∷ CorsResourcePolicy → HTTP.ResponseHeaders
407 respCorsHeaders policy = catMaybes
408 [ fmap (\x → ("Access-Control-Expose-Headers", hdrLI x)) (corsExposedHeaders policy)
409 ]
410
411 -- | A CORS middleware that supports simple cross-origin requests for all
412 -- resources.
413 --
414 -- This middleware does not check if the resource corresponds to the
415 -- restrictions for simple requests. This is in accordance with
416 -- <http://www.w3.org/TR/cors/>. It is the responsibility of the
417 -- client (user-agent) to enforce CORS policy. The role of the server
418 -- is to provide the client with the respective policy constraints.
419 --
420 -- It is out of the scope of the this module if the server chooses to
421 -- enforce rules on its resources in relation to CORS policy itself.
422 --
423 simpleCors ∷ WAI.Middleware
424 simpleCors = cors (const $ Just simpleCorsResourcePolicy)
425
426 -- -------------------------------------------------------------------------- --
427 -- Definition from Standards
428
429 -- | Simple HTTP response headers as defined in <https://www.w3.org/TR/cors/#simple-response-header>
430 --
431 simpleResponseHeaders ∷ [HTTP.HeaderName]
432 simpleResponseHeaders =
433 [ "Cache-Control"
434 , "Content-Language"
435 , "Content-Type"
436 , "Expires"
437 , "Last-Modified"
438 , "Pragma"
439 ]
440
441 -- | Simple HTTP headers are defined in <https://www.w3.org/TR/cors/#simple-header>
442 simpleHeaders ∷ [HTTP.HeaderName]
443 simpleHeaders =
444 [ "Accept"
445 , "Accept-Language"
446 , "Content-Language"
447 , "Content-Type"
448 ]
449
450 -- | Simple content types are defined in <https://www.w3.org/TR/cors/#simple-header>
451 simpleContentTypes ∷ [CI.CI B8.ByteString]
452 simpleContentTypes =
453 [ "application/x-www-form-urlencoded"
454 , "multipart/form-data"
455 , "text/plain"
456 ]
457
458
459 -- | Simple HTTP methods as defined in <https://www.w3.org/TR/cors/#simple-method>
460 --
461 simpleMethods ∷ [HTTP.Method]
462 simpleMethods =
463 [ "GET"
464 , "HEAD"
465 , "POST"
466 ]
467
468 -- | Whether the given method and headers constitute a simple request,
469 -- i.e. the method is simple, all headers are simple, and, if a POST request,
470 -- the content-type is simple.
471 isSimple ∷ HTTP.Method → HTTP.RequestHeaders → Bool
472 isSimple method headers
473 = method `elem` simpleMethods
474 ∧ map fst headers `isSubsetOf` simpleHeaders
475 ∧ case (method, lookup "content-type" headers) of
476 ("POST", Just x) → CI.mk x `elem` simpleContentTypes
477 _ → True
478
479 -- | Valid characters for HTTP header names according to RFC2616 (section 4.2)
480 --
481 isHttpHeaderNameChar ∷ Char → Bool
482 isHttpHeaderNameChar c = (c ≥ toEnum 33) && (c ≤ toEnum 126) && P.notInClass "()<>@,;:\\\"/[]?={}" c
483
484 httpHeaderNameParser ∷ P.Parser HTTP.HeaderName
485 httpHeaderNameParser = fromString <$> P.many1 (P.satisfy isHttpHeaderNameChar) P.<?> "HTTP Header Name"
486
487 -- -------------------------------------------------------------------------- --
488 -- Generic Tools
489
490 -- | A comma separated list of whitespace surounded HTTP header names.
491 --
492 -- Note that 'P.space' includes @SP@ (32), @HT@ (9), @LF@ (10), @VT@ (11),
493 -- @NP@ (12), and @CR@ (13). RFC 2616 (2.2) only defines @SP@ (32) and
494 -- @LWS = [CRLF] 1*(SP | HT)@ as whitespace. That's fine here since neither
495 -- of these characters is allowed in header names.
496 --
497 httpHeaderNameListParser ∷ P.Parser [HTTP.HeaderName]
498 httpHeaderNameListParser = spaces *> P.sepBy (httpHeaderNameParser <* spaces) (P.char ',') <* spaces
499 where
500 spaces = P.many' P.space
501
502 sshow ∷ (IsString α, Show β) ⇒ β → α
503 sshow = fromString ∘ show
504
505 isSubsetOf ∷ Eq α ⇒ [α] → [α] → Bool
506 isSubsetOf l1 l2 = intersect l1 l2 ≡ l1
507
508 -- | Add HTTP headers to a WAI response
509 --
510 addHeaders ∷ HTTP.ResponseHeaders → WAI.Middleware
511 addHeaders hdrs app req respond = app req $ \response → do
512 let (st, headers, streamHandle) = WAI.responseToStream response
513 streamHandle $ \streamBody →
514 respond $ WAI.responseStream st (headers ⊕ hdrs) streamBody
515
516 -- | Format a list of 'HTTP.HeaderName's such that it can be used as
517 -- an HTTP header value
518 --
519 hdrLI ∷ [HTTP.HeaderName] → B8.ByteString
520 hdrLI l = B8.intercalate ", " (map CI.original l)
521
522 -- | Format a list of 'B8.ByteString's such that it can be used as
523 -- an HTTP header value
524 --
525 hdrL ∷ [B8.ByteString] → B8.ByteString
526 hdrL = B8.intercalate ", "
527
528 corsFailure
529 ∷ B8.ByteString -- ^ body
530 → WAI.Response
531 corsFailure msg = WAI.responseLBS HTTP.status400 [("Content-Type", "text/html; charset-utf-8")] (LB8.fromStrict msg)
532
533 -- Copied from the [wai-websocket package](https://github.com/yesodweb/wai/blob/master/wai-websockets/Network/Wai/Handler/WebSockets.hs#L21)
534 --
535 isWebSocketsReq
536 ∷ WAI.Request
537 → Bool
538 isWebSocketsReq req =
539 fmap CI.mk (lookup "upgrade" $ WAI.requestHeaders req) == Just "websocket"
540