|
| 1 | +import contextlib |
| 2 | + |
| 3 | +import pytest |
| 4 | +import flask_talisman |
| 5 | +from selenium.common.exceptions import NoSuchElementException |
| 6 | + |
| 7 | +import dash |
| 8 | +import dash_core_components as dcc |
| 9 | +import dash_html_components as html |
| 10 | +from dash.dependencies import Input, Output |
| 11 | + |
| 12 | + |
| 13 | +@contextlib.contextmanager |
| 14 | +def does_not_raise(): |
| 15 | + yield |
| 16 | + |
| 17 | + |
| 18 | +@pytest.mark.parametrize( |
| 19 | + "add_hashes, hash_algorithm, expectation", |
| 20 | + [ |
| 21 | + (False, None, pytest.raises(NoSuchElementException)), |
| 22 | + (True, "sha256", does_not_raise()), |
| 23 | + (True, "sha384", does_not_raise()), |
| 24 | + (True, "sha512", does_not_raise()), |
| 25 | + (True, "sha999", pytest.raises(ValueError)), |
| 26 | + ], |
| 27 | +) |
| 28 | +def test_incs001_csp_hashes_inline_scripts( |
| 29 | + dash_duo, add_hashes, hash_algorithm, expectation |
| 30 | +): |
| 31 | + app = dash.Dash(__name__) |
| 32 | + |
| 33 | + app.layout = html.Div( |
| 34 | + [dcc.Input(id="input_element", type="text"), html.Div(id="output_element")] |
| 35 | + ) |
| 36 | + |
| 37 | + app.clientside_callback( |
| 38 | + """ |
| 39 | + function(input) { |
| 40 | + return input; |
| 41 | + } |
| 42 | + """, |
| 43 | + Output("output_element", "children"), |
| 44 | + [Input("input_element", "value")], |
| 45 | + ) |
| 46 | + |
| 47 | + with expectation: |
| 48 | + csp = { |
| 49 | + "default-src": "'self'", |
| 50 | + "script-src": ["'self'"] |
| 51 | + + (app.csp_hashes(hash_algorithm) if add_hashes else []), |
| 52 | + } |
| 53 | + |
| 54 | + flask_talisman.Talisman( |
| 55 | + app.server, content_security_policy=csp, force_https=False |
| 56 | + ) |
| 57 | + |
| 58 | + dash_duo.start_server(app) |
| 59 | + |
| 60 | + dash_duo.find_element("#input_element").send_keys("xyz") |
| 61 | + assert dash_duo.wait_for_element("#output_element").text == "xyz" |
0 commit comments