response.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. import typing as t
  2. from datetime import datetime
  3. from datetime import timedelta
  4. from datetime import timezone
  5. from http import HTTPStatus
  6. from .._internal import _to_str
  7. from ..datastructures import Headers
  8. from ..datastructures import HeaderSet
  9. from ..http import dump_cookie
  10. from ..http import HTTP_STATUS_CODES
  11. from ..utils import get_content_type
  12. from werkzeug.datastructures import CallbackDict
  13. from werkzeug.datastructures import ContentRange
  14. from werkzeug.datastructures import ContentSecurityPolicy
  15. from werkzeug.datastructures import ResponseCacheControl
  16. from werkzeug.datastructures import WWWAuthenticate
  17. from werkzeug.http import COEP
  18. from werkzeug.http import COOP
  19. from werkzeug.http import dump_age
  20. from werkzeug.http import dump_header
  21. from werkzeug.http import dump_options_header
  22. from werkzeug.http import http_date
  23. from werkzeug.http import parse_age
  24. from werkzeug.http import parse_cache_control_header
  25. from werkzeug.http import parse_content_range_header
  26. from werkzeug.http import parse_csp_header
  27. from werkzeug.http import parse_date
  28. from werkzeug.http import parse_options_header
  29. from werkzeug.http import parse_set_header
  30. from werkzeug.http import parse_www_authenticate_header
  31. from werkzeug.http import quote_etag
  32. from werkzeug.http import unquote_etag
  33. from werkzeug.utils import header_property
  34. def _set_property(name: str, doc: t.Optional[str] = None) -> property:
  35. def fget(self: "Response") -> HeaderSet:
  36. def on_update(header_set: HeaderSet) -> None:
  37. if not header_set and name in self.headers:
  38. del self.headers[name]
  39. elif header_set:
  40. self.headers[name] = header_set.to_header()
  41. return parse_set_header(self.headers.get(name), on_update)
  42. def fset(
  43. self: "Response",
  44. value: t.Optional[
  45. t.Union[str, t.Dict[str, t.Union[str, int]], t.Iterable[str]]
  46. ],
  47. ) -> None:
  48. if not value:
  49. del self.headers[name]
  50. elif isinstance(value, str):
  51. self.headers[name] = value
  52. else:
  53. self.headers[name] = dump_header(value)
  54. return property(fget, fset, doc=doc)
  55. class Response:
  56. """Represents the non-IO parts of an HTTP response, specifically the
  57. status and headers but not the body.
  58. This class is not meant for general use. It should only be used when
  59. implementing WSGI, ASGI, or another HTTP application spec. Werkzeug
  60. provides a WSGI implementation at :cls:`werkzeug.wrappers.Response`.
  61. :param status: The status code for the response. Either an int, in
  62. which case the default status message is added, or a string in
  63. the form ``{code} {message}``, like ``404 Not Found``. Defaults
  64. to 200.
  65. :param headers: A :class:`~werkzeug.datastructures.Headers` object,
  66. or a list of ``(key, value)`` tuples that will be converted to a
  67. ``Headers`` object.
  68. :param mimetype: The mime type (content type without charset or
  69. other parameters) of the response. If the value starts with
  70. ``text/`` (or matches some other special cases), the charset
  71. will be added to create the ``content_type``.
  72. :param content_type: The full content type of the response.
  73. Overrides building the value from ``mimetype``.
  74. .. versionadded:: 2.0
  75. """
  76. #: the charset of the response.
  77. charset = "utf-8"
  78. #: the default status if none is provided.
  79. default_status = 200
  80. #: the default mimetype if none is provided.
  81. default_mimetype: t.Optional[str] = "text/plain"
  82. #: Warn if a cookie header exceeds this size. The default, 4093, should be
  83. #: safely `supported by most browsers <cookie_>`_. A cookie larger than
  84. #: this size will still be sent, but it may be ignored or handled
  85. #: incorrectly by some browsers. Set to 0 to disable this check.
  86. #:
  87. #: .. versionadded:: 0.13
  88. #:
  89. #: .. _`cookie`: http://browsercookielimits.squawky.net/
  90. max_cookie_size = 4093
  91. # A :class:`Headers` object representing the response headers.
  92. headers: Headers
  93. def __init__(
  94. self,
  95. status: t.Optional[t.Union[int, str, HTTPStatus]] = None,
  96. headers: t.Optional[
  97. t.Union[
  98. t.Mapping[str, t.Union[str, int, t.Iterable[t.Union[str, int]]]],
  99. t.Iterable[t.Tuple[str, t.Union[str, int]]],
  100. ]
  101. ] = None,
  102. mimetype: t.Optional[str] = None,
  103. content_type: t.Optional[str] = None,
  104. ) -> None:
  105. if isinstance(headers, Headers):
  106. self.headers = headers
  107. elif not headers:
  108. self.headers = Headers()
  109. else:
  110. self.headers = Headers(headers)
  111. if content_type is None:
  112. if mimetype is None and "content-type" not in self.headers:
  113. mimetype = self.default_mimetype
  114. if mimetype is not None:
  115. mimetype = get_content_type(mimetype, self.charset)
  116. content_type = mimetype
  117. if content_type is not None:
  118. self.headers["Content-Type"] = content_type
  119. if status is None:
  120. status = self.default_status
  121. self.status = status # type: ignore
  122. def __repr__(self) -> str:
  123. return f"<{type(self).__name__} [{self.status}]>"
  124. @property
  125. def status_code(self) -> int:
  126. """The HTTP status code as a number."""
  127. return self._status_code
  128. @status_code.setter
  129. def status_code(self, code: int) -> None:
  130. self.status = code # type: ignore
  131. @property
  132. def status(self) -> str:
  133. """The HTTP status code as a string."""
  134. return self._status
  135. @status.setter
  136. def status(self, value: t.Union[str, int, HTTPStatus]) -> None:
  137. if not isinstance(value, (str, bytes, int, HTTPStatus)):
  138. raise TypeError("Invalid status argument")
  139. self._status, self._status_code = self._clean_status(value)
  140. def _clean_status(self, value: t.Union[str, int, HTTPStatus]) -> t.Tuple[str, int]:
  141. if isinstance(value, HTTPStatus):
  142. value = int(value)
  143. status = _to_str(value, self.charset)
  144. split_status = status.split(None, 1)
  145. if len(split_status) == 0:
  146. raise ValueError("Empty status argument")
  147. try:
  148. status_code = int(split_status[0])
  149. except ValueError:
  150. # only message
  151. return f"0 {status}", 0
  152. if len(split_status) > 1:
  153. # code and message
  154. return status, status_code
  155. # only code, look up message
  156. try:
  157. status = f"{status_code} {HTTP_STATUS_CODES[status_code].upper()}"
  158. except KeyError:
  159. status = f"{status_code} UNKNOWN"
  160. return status, status_code
  161. def set_cookie(
  162. self,
  163. key: str,
  164. value: str = "",
  165. max_age: t.Optional[t.Union[timedelta, int]] = None,
  166. expires: t.Optional[t.Union[str, datetime, int, float]] = None,
  167. path: t.Optional[str] = "/",
  168. domain: t.Optional[str] = None,
  169. secure: bool = False,
  170. httponly: bool = False,
  171. samesite: t.Optional[str] = None,
  172. ) -> None:
  173. """Sets a cookie.
  174. A warning is raised if the size of the cookie header exceeds
  175. :attr:`max_cookie_size`, but the header will still be set.
  176. :param key: the key (name) of the cookie to be set.
  177. :param value: the value of the cookie.
  178. :param max_age: should be a number of seconds, or `None` (default) if
  179. the cookie should last only as long as the client's
  180. browser session.
  181. :param expires: should be a `datetime` object or UNIX timestamp.
  182. :param path: limits the cookie to a given path, per default it will
  183. span the whole domain.
  184. :param domain: if you want to set a cross-domain cookie. For example,
  185. ``domain=".example.com"`` will set a cookie that is
  186. readable by the domain ``www.example.com``,
  187. ``foo.example.com`` etc. Otherwise, a cookie will only
  188. be readable by the domain that set it.
  189. :param secure: If ``True``, the cookie will only be available
  190. via HTTPS.
  191. :param httponly: Disallow JavaScript access to the cookie.
  192. :param samesite: Limit the scope of the cookie to only be
  193. attached to requests that are "same-site".
  194. """
  195. self.headers.add(
  196. "Set-Cookie",
  197. dump_cookie(
  198. key,
  199. value=value,
  200. max_age=max_age,
  201. expires=expires,
  202. path=path,
  203. domain=domain,
  204. secure=secure,
  205. httponly=httponly,
  206. charset=self.charset,
  207. max_size=self.max_cookie_size,
  208. samesite=samesite,
  209. ),
  210. )
  211. def delete_cookie(
  212. self,
  213. key: str,
  214. path: str = "/",
  215. domain: t.Optional[str] = None,
  216. secure: bool = False,
  217. httponly: bool = False,
  218. samesite: t.Optional[str] = None,
  219. ) -> None:
  220. """Delete a cookie. Fails silently if key doesn't exist.
  221. :param key: the key (name) of the cookie to be deleted.
  222. :param path: if the cookie that should be deleted was limited to a
  223. path, the path has to be defined here.
  224. :param domain: if the cookie that should be deleted was limited to a
  225. domain, that domain has to be defined here.
  226. :param secure: If ``True``, the cookie will only be available
  227. via HTTPS.
  228. :param httponly: Disallow JavaScript access to the cookie.
  229. :param samesite: Limit the scope of the cookie to only be
  230. attached to requests that are "same-site".
  231. """
  232. self.set_cookie(
  233. key,
  234. expires=0,
  235. max_age=0,
  236. path=path,
  237. domain=domain,
  238. secure=secure,
  239. httponly=httponly,
  240. samesite=samesite,
  241. )
  242. @property
  243. def is_json(self) -> bool:
  244. """Check if the mimetype indicates JSON data, either
  245. :mimetype:`application/json` or :mimetype:`application/*+json`.
  246. """
  247. mt = self.mimetype
  248. return mt is not None and (
  249. mt == "application/json"
  250. or mt.startswith("application/")
  251. and mt.endswith("+json")
  252. )
  253. # Common Descriptors
  254. @property
  255. def mimetype(self) -> t.Optional[str]:
  256. """The mimetype (content type without charset etc.)"""
  257. ct = self.headers.get("content-type")
  258. if ct:
  259. return ct.split(";")[0].strip()
  260. else:
  261. return None
  262. @mimetype.setter
  263. def mimetype(self, value: str) -> None:
  264. self.headers["Content-Type"] = get_content_type(value, self.charset)
  265. @property
  266. def mimetype_params(self) -> t.Dict[str, str]:
  267. """The mimetype parameters as dict. For example if the
  268. content type is ``text/html; charset=utf-8`` the params would be
  269. ``{'charset': 'utf-8'}``.
  270. .. versionadded:: 0.5
  271. """
  272. def on_update(d: CallbackDict) -> None:
  273. self.headers["Content-Type"] = dump_options_header(self.mimetype, d)
  274. d = parse_options_header(self.headers.get("content-type", ""))[1]
  275. return CallbackDict(d, on_update)
  276. location = header_property[str](
  277. "Location",
  278. doc="""The Location response-header field is used to redirect
  279. the recipient to a location other than the Request-URI for
  280. completion of the request or identification of a new
  281. resource.""",
  282. )
  283. age = header_property(
  284. "Age",
  285. None,
  286. parse_age,
  287. dump_age, # type: ignore
  288. doc="""The Age response-header field conveys the sender's
  289. estimate of the amount of time since the response (or its
  290. revalidation) was generated at the origin server.
  291. Age values are non-negative decimal integers, representing time
  292. in seconds.""",
  293. )
  294. content_type = header_property[str](
  295. "Content-Type",
  296. doc="""The Content-Type entity-header field indicates the media
  297. type of the entity-body sent to the recipient or, in the case of
  298. the HEAD method, the media type that would have been sent had
  299. the request been a GET.""",
  300. )
  301. content_length = header_property(
  302. "Content-Length",
  303. None,
  304. int,
  305. str,
  306. doc="""The Content-Length entity-header field indicates the size
  307. of the entity-body, in decimal number of OCTETs, sent to the
  308. recipient or, in the case of the HEAD method, the size of the
  309. entity-body that would have been sent had the request been a
  310. GET.""",
  311. )
  312. content_location = header_property[str](
  313. "Content-Location",
  314. doc="""The Content-Location entity-header field MAY be used to
  315. supply the resource location for the entity enclosed in the
  316. message when that entity is accessible from a location separate
  317. from the requested resource's URI.""",
  318. )
  319. content_encoding = header_property[str](
  320. "Content-Encoding",
  321. doc="""The Content-Encoding entity-header field is used as a
  322. modifier to the media-type. When present, its value indicates
  323. what additional content codings have been applied to the
  324. entity-body, and thus what decoding mechanisms must be applied
  325. in order to obtain the media-type referenced by the Content-Type
  326. header field.""",
  327. )
  328. content_md5 = header_property[str](
  329. "Content-MD5",
  330. doc="""The Content-MD5 entity-header field, as defined in
  331. RFC 1864, is an MD5 digest of the entity-body for the purpose of
  332. providing an end-to-end message integrity check (MIC) of the
  333. entity-body. (Note: a MIC is good for detecting accidental
  334. modification of the entity-body in transit, but is not proof
  335. against malicious attacks.)""",
  336. )
  337. date = header_property(
  338. "Date",
  339. None,
  340. parse_date,
  341. http_date,
  342. doc="""The Date general-header field represents the date and
  343. time at which the message was originated, having the same
  344. semantics as orig-date in RFC 822.
  345. .. versionchanged:: 2.0
  346. The datetime object is timezone-aware.
  347. """,
  348. )
  349. expires = header_property(
  350. "Expires",
  351. None,
  352. parse_date,
  353. http_date,
  354. doc="""The Expires entity-header field gives the date/time after
  355. which the response is considered stale. A stale cache entry may
  356. not normally be returned by a cache.
  357. .. versionchanged:: 2.0
  358. The datetime object is timezone-aware.
  359. """,
  360. )
  361. last_modified = header_property(
  362. "Last-Modified",
  363. None,
  364. parse_date,
  365. http_date,
  366. doc="""The Last-Modified entity-header field indicates the date
  367. and time at which the origin server believes the variant was
  368. last modified.
  369. .. versionchanged:: 2.0
  370. The datetime object is timezone-aware.
  371. """,
  372. )
  373. @property
  374. def retry_after(self) -> t.Optional[datetime]:
  375. """The Retry-After response-header field can be used with a
  376. 503 (Service Unavailable) response to indicate how long the
  377. service is expected to be unavailable to the requesting client.
  378. Time in seconds until expiration or date.
  379. .. versionchanged:: 2.0
  380. The datetime object is timezone-aware.
  381. """
  382. value = self.headers.get("retry-after")
  383. if value is None:
  384. return None
  385. try:
  386. seconds = int(value)
  387. except ValueError:
  388. return parse_date(value)
  389. return datetime.now(timezone.utc) + timedelta(seconds=seconds)
  390. @retry_after.setter
  391. def retry_after(self, value: t.Optional[t.Union[datetime, int, str]]) -> None:
  392. if value is None:
  393. if "retry-after" in self.headers:
  394. del self.headers["retry-after"]
  395. return
  396. elif isinstance(value, datetime):
  397. value = http_date(value)
  398. else:
  399. value = str(value)
  400. self.headers["Retry-After"] = value
  401. vary = _set_property(
  402. "Vary",
  403. doc="""The Vary field value indicates the set of request-header
  404. fields that fully determines, while the response is fresh,
  405. whether a cache is permitted to use the response to reply to a
  406. subsequent request without revalidation.""",
  407. )
  408. content_language = _set_property(
  409. "Content-Language",
  410. doc="""The Content-Language entity-header field describes the
  411. natural language(s) of the intended audience for the enclosed
  412. entity. Note that this might not be equivalent to all the
  413. languages used within the entity-body.""",
  414. )
  415. allow = _set_property(
  416. "Allow",
  417. doc="""The Allow entity-header field lists the set of methods
  418. supported by the resource identified by the Request-URI. The
  419. purpose of this field is strictly to inform the recipient of
  420. valid methods associated with the resource. An Allow header
  421. field MUST be present in a 405 (Method Not Allowed)
  422. response.""",
  423. )
  424. # ETag
  425. @property
  426. def cache_control(self) -> ResponseCacheControl:
  427. """The Cache-Control general-header field is used to specify
  428. directives that MUST be obeyed by all caching mechanisms along the
  429. request/response chain.
  430. """
  431. def on_update(cache_control: ResponseCacheControl) -> None:
  432. if not cache_control and "cache-control" in self.headers:
  433. del self.headers["cache-control"]
  434. elif cache_control:
  435. self.headers["Cache-Control"] = cache_control.to_header()
  436. return parse_cache_control_header(
  437. self.headers.get("cache-control"), on_update, ResponseCacheControl
  438. )
  439. def set_etag(self, etag: str, weak: bool = False) -> None:
  440. """Set the etag, and override the old one if there was one."""
  441. self.headers["ETag"] = quote_etag(etag, weak)
  442. def get_etag(self) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]:
  443. """Return a tuple in the form ``(etag, is_weak)``. If there is no
  444. ETag the return value is ``(None, None)``.
  445. """
  446. return unquote_etag(self.headers.get("ETag"))
  447. accept_ranges = header_property[str](
  448. "Accept-Ranges",
  449. doc="""The `Accept-Ranges` header. Even though the name would
  450. indicate that multiple values are supported, it must be one
  451. string token only.
  452. The values ``'bytes'`` and ``'none'`` are common.
  453. .. versionadded:: 0.7""",
  454. )
  455. @property
  456. def content_range(self) -> ContentRange:
  457. """The ``Content-Range`` header as a
  458. :class:`~werkzeug.datastructures.ContentRange` object. Available
  459. even if the header is not set.
  460. .. versionadded:: 0.7
  461. """
  462. def on_update(rng: ContentRange) -> None:
  463. if not rng:
  464. del self.headers["content-range"]
  465. else:
  466. self.headers["Content-Range"] = rng.to_header()
  467. rv = parse_content_range_header(self.headers.get("content-range"), on_update)
  468. # always provide a content range object to make the descriptor
  469. # more user friendly. It provides an unset() method that can be
  470. # used to remove the header quickly.
  471. if rv is None:
  472. rv = ContentRange(None, None, None, on_update=on_update)
  473. return rv
  474. @content_range.setter
  475. def content_range(self, value: t.Optional[t.Union[ContentRange, str]]) -> None:
  476. if not value:
  477. del self.headers["content-range"]
  478. elif isinstance(value, str):
  479. self.headers["Content-Range"] = value
  480. else:
  481. self.headers["Content-Range"] = value.to_header()
  482. # Authorization
  483. @property
  484. def www_authenticate(self) -> WWWAuthenticate:
  485. """The ``WWW-Authenticate`` header in a parsed form."""
  486. def on_update(www_auth: WWWAuthenticate) -> None:
  487. if not www_auth and "www-authenticate" in self.headers:
  488. del self.headers["www-authenticate"]
  489. elif www_auth:
  490. self.headers["WWW-Authenticate"] = www_auth.to_header()
  491. header = self.headers.get("www-authenticate")
  492. return parse_www_authenticate_header(header, on_update)
  493. # CSP
  494. @property
  495. def content_security_policy(self) -> ContentSecurityPolicy:
  496. """The ``Content-Security-Policy`` header as a
  497. :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
  498. even if the header is not set.
  499. The Content-Security-Policy header adds an additional layer of
  500. security to help detect and mitigate certain types of attacks.
  501. """
  502. def on_update(csp: ContentSecurityPolicy) -> None:
  503. if not csp:
  504. del self.headers["content-security-policy"]
  505. else:
  506. self.headers["Content-Security-Policy"] = csp.to_header()
  507. rv = parse_csp_header(self.headers.get("content-security-policy"), on_update)
  508. if rv is None:
  509. rv = ContentSecurityPolicy(None, on_update=on_update)
  510. return rv
  511. @content_security_policy.setter
  512. def content_security_policy(
  513. self, value: t.Optional[t.Union[ContentSecurityPolicy, str]]
  514. ) -> None:
  515. if not value:
  516. del self.headers["content-security-policy"]
  517. elif isinstance(value, str):
  518. self.headers["Content-Security-Policy"] = value
  519. else:
  520. self.headers["Content-Security-Policy"] = value.to_header()
  521. @property
  522. def content_security_policy_report_only(self) -> ContentSecurityPolicy:
  523. """The ``Content-Security-policy-report-only`` header as a
  524. :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available
  525. even if the header is not set.
  526. The Content-Security-Policy-Report-Only header adds a csp policy
  527. that is not enforced but is reported thereby helping detect
  528. certain types of attacks.
  529. """
  530. def on_update(csp: ContentSecurityPolicy) -> None:
  531. if not csp:
  532. del self.headers["content-security-policy-report-only"]
  533. else:
  534. self.headers["Content-Security-policy-report-only"] = csp.to_header()
  535. rv = parse_csp_header(
  536. self.headers.get("content-security-policy-report-only"), on_update
  537. )
  538. if rv is None:
  539. rv = ContentSecurityPolicy(None, on_update=on_update)
  540. return rv
  541. @content_security_policy_report_only.setter
  542. def content_security_policy_report_only(
  543. self, value: t.Optional[t.Union[ContentSecurityPolicy, str]]
  544. ) -> None:
  545. if not value:
  546. del self.headers["content-security-policy-report-only"]
  547. elif isinstance(value, str):
  548. self.headers["Content-Security-policy-report-only"] = value
  549. else:
  550. self.headers["Content-Security-policy-report-only"] = value.to_header()
  551. # CORS
  552. @property
  553. def access_control_allow_credentials(self) -> bool:
  554. """Whether credentials can be shared by the browser to
  555. JavaScript code. As part of the preflight request it indicates
  556. whether credentials can be used on the cross origin request.
  557. """
  558. return "Access-Control-Allow-Credentials" in self.headers
  559. @access_control_allow_credentials.setter
  560. def access_control_allow_credentials(self, value: t.Optional[bool]) -> None:
  561. if value is True:
  562. self.headers["Access-Control-Allow-Credentials"] = "true"
  563. else:
  564. self.headers.pop("Access-Control-Allow-Credentials", None)
  565. access_control_allow_headers = header_property(
  566. "Access-Control-Allow-Headers",
  567. load_func=parse_set_header,
  568. dump_func=dump_header,
  569. doc="Which headers can be sent with the cross origin request.",
  570. )
  571. access_control_allow_methods = header_property(
  572. "Access-Control-Allow-Methods",
  573. load_func=parse_set_header,
  574. dump_func=dump_header,
  575. doc="Which methods can be used for the cross origin request.",
  576. )
  577. access_control_allow_origin = header_property[str](
  578. "Access-Control-Allow-Origin",
  579. doc="The origin or '*' for any origin that may make cross origin requests.",
  580. )
  581. access_control_expose_headers = header_property(
  582. "Access-Control-Expose-Headers",
  583. load_func=parse_set_header,
  584. dump_func=dump_header,
  585. doc="Which headers can be shared by the browser to JavaScript code.",
  586. )
  587. access_control_max_age = header_property(
  588. "Access-Control-Max-Age",
  589. load_func=int,
  590. dump_func=str,
  591. doc="The maximum age in seconds the access control settings can be cached for.",
  592. )
  593. cross_origin_opener_policy = header_property[COOP](
  594. "Cross-Origin-Opener-Policy",
  595. load_func=lambda value: COOP(value),
  596. dump_func=lambda value: value.value,
  597. default=COOP.UNSAFE_NONE,
  598. doc="""Allows control over sharing of browsing context group with cross-origin
  599. documents. Values must be a member of the :class:`werkzeug.http.COOP` enum.""",
  600. )
  601. cross_origin_embedder_policy = header_property[COEP](
  602. "Cross-Origin-Embedder-Policy",
  603. load_func=lambda value: COEP(value),
  604. dump_func=lambda value: value.value,
  605. default=COEP.UNSAFE_NONE,
  606. doc="""Prevents a document from loading any cross-origin resources that do not
  607. explicitly grant the document permission. Values must be a member of the
  608. :class:`werkzeug.http.COEP` enum.""",
  609. )