| 1 | import pytest |
| 2 | from flask import json |
| 3 | from markupsafe import Markup |
| 4 | |
| 5 | from flask_wtf import FlaskForm |
| 6 | from flask_wtf.recaptcha import RecaptchaField |
| 7 | from flask_wtf.recaptcha.validators import http |
| 8 | from flask_wtf.recaptcha.validators import Recaptcha |
| 9 | |
| 10 | |
| 11 | class RecaptchaForm(FlaskForm): |
| 12 | class Meta: |
| 13 | csrf = False |
| 14 | |
| 15 | recaptcha = RecaptchaField() |
| 16 | |
| 17 | |
| 18 | class RecaptchaNonceForm(FlaskForm): |
| 19 | class Meta: |
| 20 | csrf = False |
| 21 | |
| 22 | recaptcha = RecaptchaField(nonce="foobar") |
| 23 | |
| 24 | |
| 25 | class RecaptchaNonceCallableForm(FlaskForm): |
| 26 | """Form using a callable nonce, for per-request resolution tests.""" |
| 27 | |
| 28 | class Meta: |
| 29 | csrf = False |
| 30 | |
| 31 | recaptcha = RecaptchaField(nonce=lambda: "dynamic-nonce") |
| 32 | |
| 33 | |
| 34 | class RecaptchaNonceUnsafeForm(FlaskForm): |
| 35 | """Form with an HTML-unsafe nonce, to assert escaping.""" |
| 36 | |
| 37 | class Meta: |
| 38 | csrf = False |
| 39 | |
| 40 | recaptcha = RecaptchaField(nonce='"><script>alert(1)</script>') |
| 41 | |
| 42 | |
| 43 | @pytest.fixture |
| 44 | def app(app): |
| 45 | app.testing = False |
| 46 | app.config["PROPAGATE_EXCEPTIONS"] = True |
| 47 | app.config["RECAPTCHA_PUBLIC_KEY"] = "public" |
| 48 | app.config["RECAPTCHA_PRIVATE_KEY"] = "private" |
| 49 | return app |
| 50 | |
| 51 | |
| 52 | @pytest.fixture(autouse=True) |
| 53 | def req_ctx(app): |
| 54 | with app.test_request_context(data={"g-recaptcha-response": "pass"}) as ctx: |
| 55 | yield ctx |
| 56 | |
| 57 | |
| 58 | def test_config(app, monkeypatch): |
| 59 | f = RecaptchaForm() |
| 60 | monkeypatch.setattr(app, "testing", True) |
| 61 | f.validate() |
| 62 | assert not f.recaptcha.errors |
| 63 | monkeypatch.undo() |
| 64 | |
| 65 | monkeypatch.delitem(app.config, "RECAPTCHA_PUBLIC_KEY") |
| 66 | pytest.raises(RuntimeError, f.recaptcha) |
| 67 | monkeypatch.undo() |
| 68 | |
| 69 | monkeypatch.delitem(app.config, "RECAPTCHA_PRIVATE_KEY") |
| 70 | pytest.raises(RuntimeError, f.validate) |
| 71 | |
| 72 | |
| 73 | def test_render_has_js(): |
| 74 | f = RecaptchaForm() |
| 75 | render = f.recaptcha() |
| 76 | assert "https://www.google.com/recaptcha/api.js" in render |
| 77 | |
| 78 | |
| 79 | def test_render_has_custom_js(app): |
| 80 | captcha_script = "https://hcaptcha.com/1/api.js" |
| 81 | app.config["RECAPTCHA_SCRIPT"] = captcha_script |
| 82 | f = RecaptchaForm() |
| 83 | render = f.recaptcha() |
| 84 | assert captcha_script in render |
| 85 | |
| 86 | |
| 87 | def test_render_has_nonce(): |
| 88 | f = RecaptchaNonceForm() |
| 89 | render = f.recaptcha() |
| 90 | assert 'nonce="foobar"' in render |
| 91 | |
| 92 | |
| 93 | def test_render_without_nonce(): |
| 94 | """Render must not include a nonce attribute when none is set.""" |
| 95 | f = RecaptchaForm() |
| 96 | render = f.recaptcha() |
| 97 | assert "nonce=" not in render |
| 98 | |
| 99 | |
| 100 | def test_render_nonce_callable(): |
| 101 | """A callable nonce is resolved at render time.""" |
| 102 | f = RecaptchaNonceCallableForm() |
| 103 | render = f.recaptcha() |
| 104 | assert 'nonce="dynamic-nonce"' in render |
| 105 | |
| 106 | |
| 107 | def test_render_nonce_is_escaped(): |
| 108 | """Nonce values are HTML-escaped to avoid attribute injection.""" |
| 109 | f = RecaptchaNonceUnsafeForm() |
| 110 | render = f.recaptcha() |
| 111 | assert "<script>alert(1)</script>" not in render |
| 112 | assert "<script>" in render |
| 113 | |
| 114 | |
| 115 | def test_render_custom_html(app): |
| 116 | app.config["RECAPTCHA_HTML"] = "custom" |
| 117 | f = RecaptchaForm() |
| 118 | render = f.recaptcha() |
| 119 | assert render == "custom" |
| 120 | assert isinstance(render, Markup) |
| 121 | |
| 122 | |
| 123 | def test_render_custom_div_class(app): |
| 124 | div_class = "h-captcha" |
| 125 | app.config["RECAPTCHA_DIV_CLASS"] = div_class |
| 126 | f = RecaptchaForm() |
| 127 | render = f.recaptcha() |
| 128 | assert div_class in render |
| 129 | |
| 130 | |
| 131 | def test_render_custom_args(app): |
| 132 | app.config["RECAPTCHA_PARAMETERS"] = {"key": "(value)"} |
| 133 | app.config["RECAPTCHA_DATA_ATTRS"] = {"red": "blue"} |
| 134 | f = RecaptchaForm() |
| 135 | render = f.recaptcha() |
| 136 | assert "?key=(value)" in render or "?key=%28value%29" in render |
| 137 | assert 'data-red="blue"' in render |
| 138 | |
| 139 | |
| 140 | def test_render_default_id_from_field(): |
| 141 | """The div ``id`` defaults to the field id.""" |
| 142 | f = RecaptchaForm() |
| 143 | render = f.recaptcha() |
| 144 | assert f'id="{f.recaptcha.id}"' in render |
| 145 | |
| 146 | |
| 147 | def test_render_custom_html_attrs(): |
| 148 | """Arbitrary HTML attributes can be passed as kwargs to the widget.""" |
| 149 | f = RecaptchaForm() |
| 150 | render = f.recaptcha(style="margin: 1em;", aria_label="captcha") |
| 151 | assert 'style="margin: 1em;"' in render |
| 152 | assert 'aria-label="captcha"' in render |
| 153 | |
| 154 | |
| 155 | def test_render_kwargs_override_class(app): |
| 156 | """``class_`` kwarg takes precedence over ``RECAPTCHA_DIV_CLASS`` config.""" |
| 157 | app.config["RECAPTCHA_DIV_CLASS"] = "from-config" |
| 158 | f = RecaptchaForm() |
| 159 | render = f.recaptcha(class_="from-kwargs") |
| 160 | assert 'class="from-kwargs"' in render |
| 161 | assert "from-config" not in render |
| 162 | |
| 163 | |
| 164 | def test_render_kwargs_override_data_attr(app): |
| 165 | """``data-*`` kwargs take precedence over ``RECAPTCHA_DATA_ATTRS`` config.""" |
| 166 | app.config["RECAPTCHA_DATA_ATTRS"] = {"theme": "light"} |
| 167 | f = RecaptchaForm() |
| 168 | render = f.recaptcha(data_theme="dark") |
| 169 | assert 'data-theme="dark"' in render |
| 170 | assert "light" not in render |
| 171 | |
| 172 | |
| 173 | def test_render_kwargs_override_id(): |
| 174 | """``id`` kwarg overrides the default field id.""" |
| 175 | f = RecaptchaForm() |
| 176 | render = f.recaptcha(id="custom-id") |
| 177 | assert 'id="custom-id"' in render |
| 178 | |
| 179 | |
| 180 | def test_render_kwargs_are_escaped(): |
| 181 | """HTML attribute values from kwargs are escaped.""" |
| 182 | f = RecaptchaForm() |
| 183 | render = f.recaptcha(title='"><script>alert(1)</script>') |
| 184 | assert "<script>alert(1)</script>" not in render |
| 185 | assert "<script>" in render |
| 186 | |
| 187 | |
| 188 | def test_recaptcha_enabled_false_skips_render(app): |
| 189 | app.config["RECAPTCHA_ENABLED"] = False |
| 190 | f = RecaptchaForm() |
| 191 | render = f.recaptcha() |
| 192 | assert render == Markup("<!-- recaptcha disabled -->") |
| 193 | |
| 194 | |
| 195 | def test_recaptcha_enabled_false_skips_validation(app): |
| 196 | app.config["RECAPTCHA_ENABLED"] = False |
| 197 | with app.test_request_context(): |
| 198 | f = RecaptchaForm() |
| 199 | f.validate() |
| 200 | assert not f.recaptcha.errors |
| 201 | |
| 202 | |
| 203 | def test_recaptcha_enabled_defaults_to_true(app): |
| 204 | f = RecaptchaForm() |
| 205 | render = f.recaptcha() |
| 206 | assert "g-recaptcha" in render |
| 207 | |
| 208 | |
| 209 | def test_missing_response(app): |
| 210 | with app.test_request_context(): |
| 211 | f = RecaptchaForm() |
| 212 | f.validate() |
| 213 | assert f.recaptcha.errors[0] == "The response parameter is missing." |
| 214 | |
| 215 | |
| 216 | class MockResponse: |
| 217 | def __init__(self, code, error="invalid-input-response", read_bytes=False): |
| 218 | self.code = code |
| 219 | self.data = json.dumps( |
| 220 | {"success": not error, "error-codes": [error] if error else []} |
| 221 | ) |
| 222 | self.read_bytes = read_bytes |
| 223 | |
| 224 | def read(self): |
| 225 | if self.read_bytes: |
| 226 | return self.data.encode("utf-8") |
| 227 | |
| 228 | return self.data |
| 229 | |
| 230 | |
| 231 | def test_send_invalid_request(monkeypatch): |
| 232 | def mock_urlopen(url, data): |
| 233 | return MockResponse(200) |
| 234 | |
| 235 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 236 | f = RecaptchaForm() |
| 237 | f.validate() |
| 238 | assert f.recaptcha.errors[0] == ("The response parameter is invalid or malformed.") |
| 239 | |
| 240 | |
| 241 | def test_response_from_json(app, monkeypatch): |
| 242 | def mock_urlopen(url, data): |
| 243 | return MockResponse(200) |
| 244 | |
| 245 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 246 | |
| 247 | with app.test_request_context( |
| 248 | data=json.dumps({"g-recaptcha-response": "pass"}), |
| 249 | content_type="application/json", |
| 250 | ): |
| 251 | f = RecaptchaForm() |
| 252 | f.validate() |
| 253 | assert f.recaptcha.errors[0] != "The response parameter is missing." |
| 254 | |
| 255 | |
| 256 | def test_request_fail(monkeypatch): |
| 257 | def mock_urlopen(url, data): |
| 258 | return MockResponse(400) |
| 259 | |
| 260 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 261 | f = RecaptchaForm() |
| 262 | f.validate() |
| 263 | assert f.recaptcha.errors |
| 264 | |
| 265 | |
| 266 | def test_request_success(monkeypatch): |
| 267 | def mock_urlopen(url, data): |
| 268 | return MockResponse(200, "") |
| 269 | |
| 270 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 271 | f = RecaptchaForm() |
| 272 | f.validate() |
| 273 | assert not f.recaptcha.errors |
| 274 | |
| 275 | |
| 276 | def test_request_custom_verify_server(app, monkeypatch): |
| 277 | verify_server = "https://hcaptcha.com/siteverify" |
| 278 | |
| 279 | def mock_urlopen(url, data): |
| 280 | assert url == verify_server |
| 281 | return MockResponse(200, "") |
| 282 | |
| 283 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 284 | app.config["RECAPTCHA_VERIFY_SERVER"] = verify_server |
| 285 | f = RecaptchaForm() |
| 286 | f.validate() |
| 287 | assert not f.recaptcha.errors |
| 288 | |
| 289 | |
| 290 | def test_request_unmatched_error(monkeypatch): |
| 291 | def mock_urlopen(url, data): |
| 292 | return MockResponse(200, "not-an-error", True) |
| 293 | |
| 294 | monkeypatch.setattr(http, "urlopen", mock_urlopen) |
| 295 | f = RecaptchaForm() |
| 296 | f.recaptcha.validators = [Recaptcha("custom")] |
| 297 | f.validate() |
| 298 | assert f.recaptcha.errors[0] == "custom" |