Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

captcha: Only consume a solved challenge when the form is valid.

Alex Vandiverafa544693a4b
diff --git a/zerver/lib/captcha.py b/zerver/lib/captcha.py
index f3c19841e7e..28b16305d91 100644
--- a/zerver/lib/captcha.py
+++ b/zerver/lib/captcha.py
@@ -58,10 +58,19 @@ class CaptchaFormMixin(forms.Form):
if not settings.USING_CAPTCHA or not settings.ALTCHA_HMAC_KEY:
del self.fields["captcha"]
- def clean_captcha(self) -> str:
- payload = self.data.get("captcha", "")
- validate_captcha_payload(self.request, payload)
- return payload
+ @override
+ def clean(self) -> None:
+ super().clean()
+ # Validating the payload consumes the solved challenge, to
+ # prevent replay; defer it until the rest of the form is
+ # valid, so that a failure in some other field does not
+ # invalidate a successful solve. The captcha field does not
+ # exist when the captcha is not enabled.
+ if "captcha" in self.fields and not self.errors:
+ try:
+ validate_captcha_payload(self.request, self.cleaned_data["captcha"])
+ except forms.ValidationError as error:
+ self.add_error("captcha", error)
def validate_captcha_payload(request: HttpRequest, captcha_payload: str) -> None:
diff --git a/zerver/tests/test_realm_creation.py b/zerver/tests/test_realm_creation.py
index bfc490eb652..1421f29866d 100644
--- a/zerver/tests/test_realm_creation.py
+++ b/zerver/tests/test_realm_creation.py
@@ -1209,6 +1209,18 @@ class RealmCreationTest(ZulipTestCase):
# Update the payload so the challenge matches what is in the
# session. The real payload would have other keys.
payload = base64.b64encode(orjson.dumps({"challenge": data["challenge"]})).decode()
+
+ # A failure in some other field does not consume the solved
+ # challenge; it is not even validated.
+ with patch("zerver.lib.captcha.verify_solution", return_value=(True, None)) as verify:
+ result = self.submit_realm_creation_form(
+ "invalid", realm_subdomain=string_id, realm_name=realm_name, captcha=payload
+ )
+ self.assert_in_success_response(["Enter a valid email address."], result)
+ verify.assert_not_called()
+ self.assert_length(self.client.session["altcha_challenges"], 1)
+
+ # The same solved challenge is accepted once the form is valid.
with patch("zerver.lib.captcha.verify_solution", return_value=(True, None)) as verify:
result = self.submit_realm_creation_form(
email, realm_subdomain=string_id, realm_name=realm_name, captcha=payload