MCPcopy
hub / github.com/plotly/dash / csp_hashes

Method csp_hashes

dash/dash.py:1761–1798  ·  view source on GitHub ↗

Calculates CSP hashes (sha + base64) of all inline scripts, such that one of the biggest benefits of CSP (disallowing general inline scripts) can be utilized together with Dash clientside callbacks (inline scripts). Calculate these hashes after all inline callbacks are defin

(self, hash_algorithm="sha256")

Source from the content-addressed store, hash-verified

1759 return err.args[0], 404
1760
1761 def csp_hashes(self, hash_algorithm="sha256") -> Sequence[str]:
1762 """Calculates CSP hashes (sha + base64) of all inline scripts, such that
1763 one of the biggest benefits of CSP (disallowing general inline scripts)
1764 can be utilized together with Dash clientside callbacks (inline scripts).
1765
1766 Calculate these hashes after all inline callbacks are defined,
1767 and add them to your CSP headers before starting the server, for example
1768 with the flask-talisman package from PyPI:
1769
1770 flask_talisman.Talisman(app.server, content_security_policy={
1771 "default-src": "'self'",
1772 "script-src": ["'self'"] + app.csp_hashes()
1773 })
1774
1775 :param hash_algorithm: One of the recognized CSP hash algorithms ('sha256', 'sha384', 'sha512').
1776 :return: List of CSP hash strings of all inline scripts.
1777 """
1778
1779 HASH_ALGORITHMS = ["sha256", "sha384", "sha512"]
1780 if hash_algorithm not in HASH_ALGORITHMS:
1781 raise ValueError(
1782 "Possible CSP hash algorithms: " + ", ".join(HASH_ALGORITHMS)
1783 )
1784
1785 method = getattr(hashlib, hash_algorithm)
1786
1787 def _hash(script):
1788 return base64.b64encode(method(script.encode("utf-8")).digest()).decode(
1789 "utf-8"
1790 )
1791
1792 self._inline_scripts.extend(_callback.GLOBAL_INLINE_SCRIPTS)
1793 _callback.GLOBAL_INLINE_SCRIPTS.clear()
1794
1795 return [
1796 f"'{hash_algorithm}-{_hash(script)}'"
1797 for script in (self._inline_scripts + [self.renderer])
1798 ]
1799
1800 def get_asset_url(self, path: str) -> str:
1801 """

Calls 2

extendMethod · 0.45
clearMethod · 0.45

Tested by 1