|
| 1 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 | +# you may not use this file except in compliance with the License. |
| 3 | +# You may obtain a copy of the License at |
| 4 | +# |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# |
| 7 | +# Unless required by applicable law or agreed to in writing, software |
| 8 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | +# See the License for the specific language governing permissions and |
| 11 | +# limitations under the License. |
| 12 | + |
| 13 | +import http |
| 14 | + |
| 15 | +from urllib.parse import urlencode |
| 16 | + |
| 17 | +from zope.interface import implementer |
| 18 | + |
| 19 | +from .interfaces import ChallengeResponse, ICaptchaService |
| 20 | + |
| 21 | +VERIFY_URL = "https://api.hcaptcha.com/siteverify" |
| 22 | + |
| 23 | + |
| 24 | +class HCaptchaError(ValueError): |
| 25 | + pass |
| 26 | + |
| 27 | + |
| 28 | +class MissingInputSecretError(HCaptchaError): |
| 29 | + pass |
| 30 | + |
| 31 | + |
| 32 | +class InvalidInputSecretError(HCaptchaError): |
| 33 | + pass |
| 34 | + |
| 35 | + |
| 36 | +class MissingInputResponseError(HCaptchaError): |
| 37 | + pass |
| 38 | + |
| 39 | + |
| 40 | +class InvalidInputResponseError(HCaptchaError): |
| 41 | + pass |
| 42 | + |
| 43 | + |
| 44 | +class BadRequestError(HCaptchaError): |
| 45 | + pass |
| 46 | + |
| 47 | + |
| 48 | +class InvalidOrAlreadySeenResponseError(HCaptchaError): |
| 49 | + pass |
| 50 | + |
| 51 | + |
| 52 | +class NotUsingDummyPasscodeError(HCaptchaError): |
| 53 | + pass |
| 54 | + |
| 55 | + |
| 56 | +class SitekeySecretMismatchError(HCaptchaError): |
| 57 | + pass |
| 58 | + |
| 59 | + |
| 60 | +class UnexpectedError(HCaptchaError): |
| 61 | + pass |
| 62 | + |
| 63 | + |
| 64 | +# https://docs.hcaptcha.com/#siteverify-error-codes-table |
| 65 | +ERROR_CODE_MAP = { |
| 66 | + "missing-input-secret": MissingInputSecretError, |
| 67 | + "invalid-input-secret": InvalidInputSecretError, |
| 68 | + "missing-input-response": MissingInputResponseError, |
| 69 | + "invalid-input-response": InvalidInputResponseError, |
| 70 | + "invalid-or-already-seen-response": InvalidOrAlreadySeenResponseError, |
| 71 | + "not-using-dummy-passcode": NotUsingDummyPasscodeError, |
| 72 | + "sitekey-secret-mismatch": SitekeySecretMismatchError, |
| 73 | + "bad-request": BadRequestError, |
| 74 | +} |
| 75 | + |
| 76 | + |
| 77 | +_CSP_ENTRIES = [ |
| 78 | + "https://hcaptcha.com", |
| 79 | + "https://*.hcaptcha.com", |
| 80 | +] |
| 81 | + |
| 82 | + |
| 83 | +@implementer(ICaptchaService) |
| 84 | +class Service: |
| 85 | + def __init__(self, *, request, script_src_url, site_key, secret_key): |
| 86 | + self.request = request |
| 87 | + self.script_src_url = script_src_url |
| 88 | + self.site_key = site_key |
| 89 | + self.secret_key = secret_key |
| 90 | + self.class_name = "h-captcha" |
| 91 | + |
| 92 | + @classmethod |
| 93 | + def create_service(cls, context, request) -> "Service": |
| 94 | + return cls( |
| 95 | + request=request, |
| 96 | + script_src_url="https://js.hcaptcha.com/1/api.js", |
| 97 | + site_key=request.registry.settings.get("hcaptcha.site_key"), |
| 98 | + secret_key=request.registry.settings.get("hcaptcha.secret_key"), |
| 99 | + ) |
| 100 | + |
| 101 | + @property |
| 102 | + def csp_policy(self) -> dict[str, list[str]]: |
| 103 | + return { |
| 104 | + "script-src": _CSP_ENTRIES, |
| 105 | + "frame-src": _CSP_ENTRIES, |
| 106 | + "style-src": _CSP_ENTRIES, |
| 107 | + "connect-src": _CSP_ENTRIES, |
| 108 | + } |
| 109 | + |
| 110 | + @property |
| 111 | + def enabled(self) -> bool: |
| 112 | + return bool(self.site_key and self.secret_key) |
| 113 | + |
| 114 | + def verify_response(self, response, remote_ip=None) -> ChallengeResponse | None: |
| 115 | + if not self.enabled: |
| 116 | + # TODO: debug logging |
| 117 | + return None |
| 118 | + |
| 119 | + payload = { |
| 120 | + "secret": self.secret_key, |
| 121 | + "response": response, |
| 122 | + } |
| 123 | + if remote_ip is not None: |
| 124 | + payload["remoteip"] = remote_ip |
| 125 | + |
| 126 | + try: |
| 127 | + # TODO: the timeout is hardcoded for now. it would be nice to do |
| 128 | + # something a little more generalized in the future. |
| 129 | + resp = self.request.http.post( |
| 130 | + VERIFY_URL, |
| 131 | + urlencode(payload), |
| 132 | + headers={ |
| 133 | + "Content-Type": "application/x-www-form-urlencoded; charset=utf-8" |
| 134 | + }, |
| 135 | + timeout=10, |
| 136 | + ) |
| 137 | + except Exception as err: |
| 138 | + raise UnexpectedError(str(err)) from err |
| 139 | + |
| 140 | + try: |
| 141 | + data = resp.json() |
| 142 | + except ValueError as e: |
| 143 | + raise UnexpectedError( |
| 144 | + f'Unexpected data in response body: {str(resp.content, "utf-8")}' |
| 145 | + ) from e |
| 146 | + |
| 147 | + if "success" not in data: |
| 148 | + raise UnexpectedError(f"Missing 'success' key in response: {data}") |
| 149 | + |
| 150 | + if resp.status_code != http.HTTPStatus.OK or not data["success"]: |
| 151 | + try: |
| 152 | + error_codes = data["error_codes"] |
| 153 | + except KeyError as e: |
| 154 | + raise UnexpectedError( |
| 155 | + f"Response missing 'error-codes' key: {data}" |
| 156 | + ) from e |
| 157 | + try: |
| 158 | + exc_tp = ERROR_CODE_MAP[error_codes[0]] |
| 159 | + except KeyError as exc: |
| 160 | + raise UnexpectedError( |
| 161 | + f"Unexpected error code: {error_codes[0]}" |
| 162 | + ) from exc |
| 163 | + raise exc_tp |
| 164 | + |
| 165 | + # challenge_ts = timestamp of the challenge load |
| 166 | + # (ISO format yyyy-MM-dd'T'HH:mm:ssZZ) |
| 167 | + # TODO: maybe run some validation against the hostname and timestamp? |
| 168 | + # TODO: log if either field is empty.. it shouldn't cause a failure, |
| 169 | + # but it likely means that google has changed their response structure |
| 170 | + return ChallengeResponse( |
| 171 | + data.get("challenge_ts"), |
| 172 | + data.get("hostname"), |
| 173 | + ) |
0 commit comments