-
-
Notifications
You must be signed in to change notification settings - Fork 53
feat: create reCAPTCHA validation utility #1204
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
rboixaderg
wants to merge
6
commits into
master
Choose a base branch
from
recaptcha-utility
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
415dca0
feat: create reCAPTCHA validation utility
rboixaderg 8b56499
chore: isort
rboixaderg 6a9aa7b
fix: update recaptcha utility usage and add validation tests
rboixaderg 6992419
refactor: simplify ClientSession patching in reCAPTCHA validation tests
rboixaderg 524708d
refactor: enhance reCAPTCHA validation tests with context management …
rboixaderg 202cc88
Merge branch 'master' into recaptcha-utility
bloodbare File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| from guillotina import app_settings | ||
| from guillotina.auth.recaptcha import RECAPTCHA_VALIDATION_URL | ||
| from guillotina.auth.recaptcha import RecaptchaValidator | ||
| from guillotina.auth.recaptcha import VALIDATION_HEADER | ||
| from guillotina.component import query_utility | ||
| from guillotina.interfaces.async_util import IRecaptchaValidationUtility | ||
| from guillotina.tests import utils | ||
| from unittest.mock import AsyncMock | ||
| from unittest.mock import MagicMock | ||
| from unittest.mock import patch | ||
|
|
||
| import json | ||
| import pytest | ||
|
|
||
|
|
||
| pytestmark = pytest.mark.asyncio | ||
|
|
||
| FAKE_RECAPTCHA = "FAKE_RECAPTCHA" | ||
|
|
||
|
|
||
| class TestRecaptchaValidator: | ||
| """Test the RecaptchaValidator utility class directly.""" | ||
|
|
||
| async def test_initialize_and_finalize(self): | ||
| """Test that initialize and finalize methods exist and work.""" | ||
| validator = RecaptchaValidator() | ||
| await validator.initialize() | ||
| await validator.finalize() | ||
|
|
||
| async def test_validate_with_fake_recaptcha(self): | ||
| """Test validation with fake recaptcha token.""" | ||
| original_value = app_settings.get("_fake_recaptcha_") | ||
| try: | ||
| app_settings["_fake_recaptcha_"] = FAKE_RECAPTCHA | ||
| request = utils.get_mocked_request(headers={VALIDATION_HEADER: FAKE_RECAPTCHA}) | ||
| utils.task_vars.request.set(request) | ||
|
|
||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
| assert result is True | ||
| finally: | ||
| if original_value is not None: | ||
| app_settings["_fake_recaptcha_"] = original_value | ||
| else: | ||
| app_settings.pop("_fake_recaptcha_", None) | ||
|
|
||
| async def test_validate_without_configuration(self): | ||
| """Test validation when recaptcha is not configured (graceful degradation).""" | ||
| original_value = app_settings.get("recaptcha") | ||
| try: | ||
| app_settings.pop("recaptcha", None) | ||
| request = utils.get_mocked_request(headers={VALIDATION_HEADER: "some-token"}) | ||
| utils.task_vars.request.set(request) | ||
|
|
||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
| # Should return True when not configured (graceful degradation) | ||
| assert result is True | ||
| finally: | ||
| if original_value is not None: | ||
| app_settings["recaptcha"] = original_value | ||
| else: | ||
| app_settings.pop("recaptcha", None) | ||
|
|
||
| async def test_validate_success(self): | ||
| """Test successful validation with mocked HTTP response.""" | ||
| original_value = app_settings.get("recaptcha") | ||
| try: | ||
| app_settings["recaptcha"] = {"private": "test-secret-key"} | ||
| request = utils.get_mocked_request(headers={VALIDATION_HEADER: "valid-token"}) | ||
| utils.task_vars.request.set(request) | ||
|
|
||
| # Mock aiohttp response | ||
| mock_response = AsyncMock() | ||
| mock_response.json = AsyncMock(return_value={"success": True}) | ||
| mock_response.__aenter__ = AsyncMock(return_value=mock_response) | ||
| mock_response.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| mock_post = AsyncMock(return_value=mock_response) | ||
| mock_session = MagicMock() | ||
| mock_session.post = mock_post | ||
| mock_session.__aenter__ = AsyncMock(return_value=mock_session) | ||
| mock_session.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| with patch("aiohttp.ClientSession", return_value=mock_session): | ||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
|
|
||
| assert result is True | ||
| mock_post.assert_called_once() | ||
| call_args = mock_post.call_args | ||
| assert call_args[0][0] == RECAPTCHA_VALIDATION_URL | ||
| assert call_args[1]["data"]["secret"] == "test-secret-key" | ||
| assert call_args[1]["data"]["response"] == "valid-token" | ||
| finally: | ||
| if original_value is not None: | ||
| app_settings["recaptcha"] = original_value | ||
| else: | ||
| app_settings.pop("recaptcha", None) | ||
|
|
||
| async def test_validate_failure(self): | ||
| """Test failed validation with mocked HTTP response.""" | ||
| original_value = app_settings.get("recaptcha") | ||
| try: | ||
| app_settings["recaptcha"] = {"private": "test-secret-key"} | ||
| request = utils.get_mocked_request(headers={VALIDATION_HEADER: "invalid-token"}) | ||
| utils.task_vars.request.set(request) | ||
|
|
||
| # Mock aiohttp response | ||
| mock_response = AsyncMock() | ||
| mock_response.json = AsyncMock(return_value={"success": False}) | ||
| mock_response.__aenter__ = AsyncMock(return_value=mock_response) | ||
| mock_response.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| mock_post = AsyncMock(return_value=mock_response) | ||
| mock_session = MagicMock() | ||
| mock_session.post = mock_post | ||
| mock_session.__aenter__ = AsyncMock(return_value=mock_session) | ||
| mock_session.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| with patch("aiohttp.ClientSession", return_value=mock_session): | ||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
|
|
||
| assert result is False | ||
| finally: | ||
| if original_value is not None: | ||
| app_settings["recaptcha"] = original_value | ||
| else: | ||
| app_settings.pop("recaptcha", None) | ||
|
|
||
| async def test_validate_error_handling(self): | ||
| """Test validation error handling (JSON decode error, missing success key).""" | ||
| original_value = app_settings.get("recaptcha") | ||
| try: | ||
| app_settings["recaptcha"] = {"private": "test-secret-key"} | ||
| request = utils.get_mocked_request(headers={VALIDATION_HEADER: "some-token"}) | ||
| utils.task_vars.request.set(request) | ||
|
|
||
| # Test JSON decode error | ||
| mock_response = AsyncMock() | ||
| mock_response.json = AsyncMock(side_effect=ValueError("Invalid JSON")) | ||
| mock_response.__aenter__ = AsyncMock(return_value=mock_response) | ||
| mock_response.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| mock_post = AsyncMock(return_value=mock_response) | ||
| mock_session = MagicMock() | ||
| mock_session.post = mock_post | ||
| mock_session.__aenter__ = AsyncMock(return_value=mock_session) | ||
| mock_session.__aexit__ = AsyncMock(return_value=None) | ||
|
|
||
| with patch("aiohttp.ClientSession", return_value=mock_session): | ||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
| assert result is False | ||
|
|
||
| # Test missing success key | ||
| mock_response.json = AsyncMock(return_value={}) | ||
| with patch("aiohttp.ClientSession", return_value=mock_session): | ||
| validator = RecaptchaValidator() | ||
| result = await validator.validate() | ||
| assert result is False | ||
| finally: | ||
| if original_value is not None: | ||
| app_settings["recaptcha"] = original_value | ||
| else: | ||
| app_settings.pop("recaptcha", None) | ||
|
|
||
|
|
||
| class TestRecaptchaUtilityIntegration: | ||
| """Test the utility pattern integration.""" | ||
|
|
||
| async def test_utility_registered_and_implements_interface(self, guillotina_main): | ||
| """Test that the utility is registered and implements the interface.""" | ||
| from zope.interface.verify import verifyObject | ||
|
|
||
| # guillotina_main fixture sets up the application and registers utilities | ||
| assert guillotina_main is not None # Ensure app is initialized | ||
|
|
||
| utility = query_utility(IRecaptchaValidationUtility) | ||
| assert utility is not None | ||
| assert isinstance(utility, RecaptchaValidator) | ||
| assert verifyObject(IRecaptchaValidationUtility, utility) | ||
|
|
||
|
|
||
| class TestRecaptchaEndpointIntegration: | ||
| """Test endpoints that use reCAPTCHA validation.""" | ||
|
|
||
| @pytest.mark.app_settings({"_fake_recaptcha_": FAKE_RECAPTCHA}) | ||
| async def test_endpoint_rejects_invalid_recaptcha(self, container_requester): | ||
| """Test that endpoints reject requests with invalid reCAPTCHA.""" | ||
| async with container_requester as requester: | ||
| # Mock the utility to return False | ||
| utility = query_utility(IRecaptchaValidationUtility) | ||
| original_validate = utility.validate | ||
| utility.validate = AsyncMock(return_value=False) | ||
|
|
||
| try: | ||
| # Test @info endpoint | ||
| _, status = await requester( | ||
| "GET", | ||
| "/db/guillotina/@info", | ||
| authenticated=False, | ||
| headers={VALIDATION_HEADER: "invalid-token"}, | ||
| ) | ||
| assert status == 401 | ||
|
|
||
| # Test @users registration endpoint | ||
| _, status = await requester( | ||
| "POST", | ||
| "/db/guillotina/@users", | ||
| data=json.dumps( | ||
| { | ||
| "id": "[email protected]", | ||
| "email": "[email protected]", | ||
| "password": "testpassword", | ||
| "fullname": "Test User", | ||
| } | ||
| ), | ||
| authenticated=False, | ||
| headers={VALIDATION_HEADER: "invalid-token"}, | ||
| ) | ||
| assert status == 401 | ||
| finally: | ||
| utility.validate = original_validate |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.