Example #1
0
    def check_csrf_token(self, request: Any, supplied_token: str) -> bool:
        """Return True if the supplied_token is valid.

        This is called automatically by Pyramid if you have configured it
        to require CSRF.
        """
        try:
            version_str, sep, signature = supplied_token.partition(".")
            token_version = int(version_str)
        except Exception:
            return False

        if sep != ".":
            return False

        if token_version != self.VERSION:
            return False

        _, payload = _make_csrf_token_payload(
            version=token_version, account_id=request.authenticated_userid)

        try:
            validate_signature(self._get_secret(), payload, signature.encode())
        except SignatureError:
            return False

        return True
Example #2
0
def test_expired(mock_time):
    mock_time.return_value = 2000

    with pytest.raises(crypto.ExpiredSignatureError) as exc:
        crypto.validate_signature(TEST_SECRET, MESSAGE, VALID_TIL_1030)

    assert exc.value.expiration == 1030
Example #3
0
 def test_new_csrf_token(self, time_mock):
     time_mock.time.return_value = 1000.0
     request = mock.Mock()
     request.authenticated_userid = "t2_1"
     token = self.policy.new_csrf_token(request)
     self.assertTrue(token.startswith("1."))
     self.assertEqual(token, "1.AQAA-BEAAF-br-ovnk0q8Wd0kA98-jsak9elbMqo0WbjT0GuyRTD")
     signature = token.split(".")[-1]
     validate_signature(self.policy._get_secret(), "1.t2_1", signature)
Example #4
0
def test_secret_rotation(mock_time, rotated_secret):
    mock_time.return_value = 1000

    result = crypto.validate_signature(rotated_secret, MESSAGE, VALID_TIL_1030)

    assert result.version == 1
    assert result.expiration == 1030
Example #5
0
def test_bad_signature(mock_time):
    mock_time.return_value = 1000

    with pytest.raises(crypto.IncorrectSignatureError):
        crypto.validate_signature(TEST_SECRET, "SNEAKY DIFFERENT MESSAGE",
                                  VALID_TIL_1030)
Example #6
0
def test_bogus_signature(signature):
    with pytest.raises(crypto.UnreadableSignatureError):
        crypto.validate_signature(TEST_SECRET, MESSAGE, signature)