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 = "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. if len(split_status) > 1:
  148. if split_status[0].isdigit():
  149. # code and message
  150. return status, int(split_status[0])
  151. # multi-word message
  152. return f"0 {status}", 0
  153. if split_status[0].isdigit():
  154. # code only
  155. status_code = int(split_status[0])
  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. # one-word message
  162. return f"0 {status}", 0
  163. def set_cookie(
  164. self,
  165. key: str,
  166. value: str = "",
  167. max_age: t.Optional[t.Union[timedelta, int]] = None,
  168. expires: t.Optional[t.Union[str, datetime, int, float]] = None,
  169. path: t.Optional[str] = "/",
  170. domain: t.Optional[str] = None,
  171. secure: bool = False,
  172. httponly: bool = False,
  173. samesite: t.Optional[str] = None,
  174. ) -> None:
  175. """Sets a cookie.
  176. A warning is raised if the size of the cookie header exceeds
  177. :attr:`max_cookie_size`, but the header will still be set.
  178. :param key: the key (name) of the cookie to be set.
  179. :param value: the value of the cookie.
  180. :param max_age: should be a number of seconds, or `None` (default) if
  181. the cookie should last only as long as the client's
  182. browser session.
  183. :param expires: should be a `datetime` object or UNIX timestamp.
  184. :param path: limits the cookie to a given path, per default it will
  185. span the whole domain.
  186. :param domain: if you want to set a cross-domain cookie. For example,
  187. ``domain=".example.com"`` will set a cookie that is
  188. readable by the domain ``www.example.com``,
  189. ``foo.example.com`` etc. Otherwise, a cookie will only
  190. be readable by the domain that set it.
  191. :param secure: If ``True``, the cookie will only be available
  192. via HTTPS.
  193. :param httponly: Disallow JavaScript access to the cookie.
  194. :param samesite: Limit the scope of the cookie to only be
  195. attached to requests that are "same-site".
  196. """
  197. self.headers.add(
  198. "Set-Cookie",
  199. dump_cookie(
  200. key,
  201. value=value,
  202. max_age=max_age,
  203. expires=expires,
  204. path=path,
  205. domain=domain,
  206. secure=secure,
  207. httponly=httponly,
  208. charset=self.charset,
  209. max_size=self.max_cookie_size,
  210. samesite=samesite,
  211. ),
  212. )
  213. def delete_cookie(
  214. self,
  215. key: str,
  216. path: str = "/",
  217. domain: t.Optional[str] = None,
  218. secure: bool = False,
  219. httponly: bool = False,
  220. samesite: t.Optional[str] = None,
  221. ) -> None:
  222. """Delete a cookie. Fails silently if key doesn't exist.
  223. :param key: the key (name) of the cookie to be deleted.
  224. :param path: if the cookie that should be deleted was limited to a
  225. path, the path has to be defined here.
  226. :param domain: if the cookie that should be deleted was limited to a
  227. domain, that domain has to be defined here.
  228. :param secure: If ``True``, the cookie will only be available
  229. via HTTPS.
  230. :param httponly: Disallow JavaScript access to the cookie.
  231. :param samesite: Limit the scope of the cookie to only be
  232. attached to requests that are "same-site".
  233. """
  234. self.set_cookie(
  235. key,
  236. expires=0,
  237. max_age=0,
  238. path=path,
  239. domain=domain,
  240. secure=secure,
  241. httponly=httponly,
  242. samesite=samesite,
  243. )
  244. @property
  245. def is_json(self) -> bool:
  246. """Check if the mimetype indicates JSON data, either
  247. :mimetype:`application/json` or :mimetype:`application/*+json`.
  248. """
  249. mt = self.mimetype
  250. return mt is not None and (
  251. mt == "application/json"
  252. or mt.startswith("application/")
  253. and mt.endswith("+json")
  254. )
  255. # Common Descriptors
  256. @property
  257. def mimetype(self) -> t.Optional[str]:
  258. """The mimetype (content type without charset etc.)"""
  259. ct = self.headers.get("content-type")
  260. if ct:
  261. return ct.split(";")[0].strip()
  262. else:
  263. return None
  264. @mimetype.setter
  265. def mimetype(self, value: str) -> None:
  266. self.headers["Content-Type"] = get_content_type(value, self.charset)
  267. @property
  268. def mimetype_params(self) -> t.Dict[str, str]:
  269. """The mimetype parameters as dict. For example if the
  270. content type is ``text/html; charset=utf-8`` the params would be
  271. ``{'charset': 'utf-8'}``.
  272. .. versionadded:: 0.5
  273. """
  274. def on_update(d: CallbackDict) -> None:
  275. self.headers["Content-Type"] = dump_options_header(self.mimetype, d)
  276. d = parse_options_header(self.headers.get("content-type", ""))[1]
  277. return CallbackDict(d, on_update)
  278. location = header_property[str](
  279. "Location",
  280. doc="""The Location response-header field is used to redirect
  281. the recipient to a location other than the Request-URI for
  282. completion of the request or identification of a new
  283. resource.""",
  284. )
  285. age = header_property(
  286. "Age",
  287. None,
  288. parse_age,
  289. dump_age, # type: ignore
  290. doc="""The Age response-header field conveys the sender's
  291. estimate of the amount of time since the response (or its
  292. revalidation) was generated at the origin server.
  293. Age values are non-negative decimal integers, representing time
  294. in seconds.""",
  295. )
  296. content_type = header_property[str](
  297. "Content-Type",
  298. doc="""The Content-Type entity-header field indicates the media
  299. type of the entity-body sent to the recipient or, in the case of
  300. the HEAD method, the media type that would have been sent had
  301. the request been a GET.""",
  302. )
  303. content_length = header_property(
  304. "Content-Length",
  305. None,
  306. int,
  307. str,
  308. doc="""The Content-Length entity-header field indicates the size
  309. of the entity-body, in decimal number of OCTETs, sent to the
  310. recipient or, in the case of the HEAD method, the size of the
  311. entity-body that would have been sent had the request been a
  312. GET.""",
  313. )
  314. content_location = header_property[str](
  315. "Content-Location",
  316. doc="""The Content-Location entity-header field MAY be used to
  317. supply the resource location for the entity enclosed in the
  318. message when that entity is accessible from a location separate
  319. from the requested resource's URI.""",
  320. )
  321. content_encoding = header_property[str](
  322. "Content-Encoding",
  323. doc="""The Content-Encoding entity-header field is used as a
  324. modifier to the media-type. When present, its value indicates
  325. what additional content codings have been applied to the
  326. entity-body, and thus what decoding mechanisms must be applied
  327. in order to obtain the media-type referenced by the Content-Type
  328. header field.""",
  329. )
  330. content_md5 = header_property[str](
  331. "Content-MD5",
  332. doc="""The Content-MD5 entity-header field, as defined in
  333. RFC 1864, is an MD5 digest of the entity-body for the purpose of
  334. providing an end-to-end message integrity check (MIC) of the
  335. entity-body. (Note: a MIC is good for detecting accidental
  336. modification of the entity-body in transit, but is not proof
  337. against malicious attacks.)""",
  338. )
  339. date = header_property(
  340. "Date",
  341. None,
  342. parse_date,
  343. http_date,
  344. doc="""The Date general-header field represents the date and
  345. time at which the message was originated, having the same
  346. semantics as orig-date in RFC 822.
  347. .. versionchanged:: 2.0
  348. The datetime object is timezone-aware.
  349. """,
  350. )
  351. expires = header_property(
  352. "Expires",
  353. None,
  354. parse_date,
  355. http_date,
  356. doc="""The Expires entity-header field gives the date/time after
  357. which the response is considered stale. A stale cache entry may
  358. not normally be returned by a cache.
  359. .. versionchanged:: 2.0
  360. The datetime object is timezone-aware.
  361. """,
  362. )
  363. last_modified = header_property(
  364. "Last-Modified",
  365. None,
  366. parse_date,
  367. http_date,
  368. doc="""The Last-Modified entity-header field indicates the date
  369. and time at which the origin server believes the variant was
  370. last modified.
  371. .. versionchanged:: 2.0
  372. The datetime object is timezone-aware.
  373. """,
  374. )
  375. @property
  376. def retry_after(self) -> t.Optional[datetime]:
  377. """The Retry-After response-header field can be used with a
  378. 503 (Service Unavailable) response to indicate how long the
  379. service is expected to be unavailable to the requesting client.
  380. Time in seconds until expiration or date.
  381. .. versionchanged:: 2.0
  382. The datetime object is timezone-aware.
  383. """
  384. value = self.headers.get("retry-after")
  385. if value is None:
  386. return None
  387. elif value.isdigit():
  388. return datetime.now(timezone.utc) + timedelta(seconds=int(value))
  389. return parse_date(value)
  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. )