|
| 1 | +# Copyright 2025 Akretion (http://www.akretion.com). |
| 2 | +# @author Florian Mounier <florian.mounier@akretion.com> |
| 3 | +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). |
| 4 | + |
| 5 | +import re |
| 6 | +from typing import Annotated |
| 7 | + |
| 8 | +import requests |
| 9 | +from starlette.middleware import Middleware |
| 10 | + |
| 11 | +from odoo import _, api, fields, models |
| 12 | +from odoo.exceptions import AccessError, UserError, ValidationError |
| 13 | + |
| 14 | +from fastapi import Depends, Header |
| 15 | + |
| 16 | +from ..captcha_middleware import CaptchaMiddleware |
| 17 | + |
| 18 | + |
| 19 | +class FastapiEndpoint(models.Model): |
| 20 | + _inherit = "fastapi.endpoint" |
| 21 | + |
| 22 | + use_captcha = fields.Boolean( |
| 23 | + help="If checked, this endpoint will be protected by a captcha", |
| 24 | + ) |
| 25 | + |
| 26 | + captcha_type = fields.Selection( |
| 27 | + [ |
| 28 | + ("recaptcha", "Recaptcha"), |
| 29 | + ("hcaptcha", "Hcaptcha"), |
| 30 | + ("altcha", "Altcha"), |
| 31 | + ], |
| 32 | + help="Type of captcha to use for this endpoint", |
| 33 | + ) |
| 34 | + |
| 35 | + captcha_secret_key = fields.Char( |
| 36 | + help="Secret key to use for the captcha validation", |
| 37 | + groups="base.group_system", |
| 38 | + ) |
| 39 | + |
| 40 | + captcha_routes_regex = fields.Char( |
| 41 | + help="Regexes to match against routes url that should be protected " |
| 42 | + "by this captcha, comma separated. If empty, all routes will be protected", |
| 43 | + ) |
| 44 | + |
| 45 | + captcha_minimum_score = fields.Float( |
| 46 | + default=0.5, |
| 47 | + help="Minimum score to accept the captcha if a score is provided by the " |
| 48 | + "captcha service.", |
| 49 | + ) |
| 50 | + |
| 51 | + @property |
| 52 | + def _server_env_fields(self): |
| 53 | + fields = getattr(super(), "_server_env_fields", None) or {} |
| 54 | + fields["captcha_secret_key"] = {} |
| 55 | + return fields |
| 56 | + |
| 57 | + @api.constrains("captcha_routes_regex") |
| 58 | + def _check_captcha_routes_regex(self): |
| 59 | + """Check that the captcha routes regex is valid""" |
| 60 | + for record in self: |
| 61 | + if record.captcha_routes_regex: |
| 62 | + for rex in record.captcha_routes_regex.split(","): |
| 63 | + rex = rex.strip() |
| 64 | + if not rex: |
| 65 | + continue |
| 66 | + # Check that the regex is valid |
| 67 | + try: |
| 68 | + re.compile(rex) |
| 69 | + except re.error as e: |
| 70 | + raise ValidationError( |
| 71 | + _( |
| 72 | + "Invalid regex for captcha routes: %(regex)s (error: %(error)s)" |
| 73 | + ) |
| 74 | + % { |
| 75 | + "regex": rex, |
| 76 | + "error": str(e), |
| 77 | + } |
| 78 | + ) from e |
| 79 | + |
| 80 | + def _get_fastapi_app_middlewares(self): |
| 81 | + # Add the captcha middleware to the list of middlewares if enabled |
| 82 | + middlewares = super()._get_fastapi_app_middlewares() |
| 83 | + if self.use_captcha: |
| 84 | + middlewares.append( |
| 85 | + Middleware( |
| 86 | + CaptchaMiddleware, |
| 87 | + endpoint_id=self.id, |
| 88 | + root_path=self.root_path, |
| 89 | + routes_regex=[ |
| 90 | + re.compile(rex) for rex in self.captcha_routes_regex.split(",") |
| 91 | + ] |
| 92 | + if self.captcha_routes_regex |
| 93 | + else None, |
| 94 | + ) |
| 95 | + ) |
| 96 | + return middlewares |
| 97 | + |
| 98 | + def _get_fastapi_app_dependencies(self): |
| 99 | + # Add the captcha header to the list of dependencies |
| 100 | + dependencies = super()._get_fastapi_app_dependencies() |
| 101 | + if self.use_captcha: |
| 102 | + dependencies.append(Depends(captcha_token)) |
| 103 | + |
| 104 | + return dependencies |
| 105 | + |
| 106 | + def validate_captcha(self, captcha_response): |
| 107 | + """Validate the captcha response.""" |
| 108 | + secret_key = self.captcha_secret_key |
| 109 | + if not secret_key: |
| 110 | + raise UserError(_("No secret key found for this endpoint")) |
| 111 | + |
| 112 | + if self.captcha_type == "recaptcha": |
| 113 | + return self._validate_recaptcha(captcha_response, secret_key) |
| 114 | + elif self.captcha_type == "hcaptcha": |
| 115 | + return self._validate_hcaptcha(captcha_response, secret_key) |
| 116 | + elif self.captcha_type == "altcha": |
| 117 | + return self._validate_altcha(captcha_response, secret_key) |
| 118 | + |
| 119 | + def _validate_recaptcha(self, captcha_response, secret_key): |
| 120 | + """Validate the recaptcha response""" |
| 121 | + data = { |
| 122 | + "secret": secret_key, |
| 123 | + "response": captcha_response, |
| 124 | + } |
| 125 | + response = requests.post( |
| 126 | + "https://www.google.com/recaptcha/api/siteverify", |
| 127 | + data=data, |
| 128 | + timeout=10, |
| 129 | + ) |
| 130 | + result = response.json() |
| 131 | + success = result.get("success", False) |
| 132 | + if not success: |
| 133 | + error_codes = result.get("error-codes", ["?"]) |
| 134 | + raise AccessError( |
| 135 | + _("Recaptcha validation failed: %s") % ", ".join(error_codes) |
| 136 | + ) |
| 137 | + score = result.get("score", 1) |
| 138 | + if score < self.captcha_minimum_score: |
| 139 | + raise AccessError( |
| 140 | + _("Recaptcha validation failed: score %(score)s < %(min_score)s") |
| 141 | + % { |
| 142 | + "score": score, |
| 143 | + "min_score": self.captcha_minimum_score, |
| 144 | + } |
| 145 | + ) |
| 146 | + |
| 147 | + def _validate_hcaptcha(self, captcha_response, secret_key): |
| 148 | + """Validate the hcaptcha response""" |
| 149 | + |
| 150 | + data = { |
| 151 | + "secret": secret_key, |
| 152 | + "response": captcha_response, |
| 153 | + } |
| 154 | + response = requests.post( |
| 155 | + "https://api.hcaptcha.com/siteverify", data=data, timeout=10 |
| 156 | + ) |
| 157 | + result = response.json() |
| 158 | + success = result.get("success", False) |
| 159 | + if not success: |
| 160 | + error_codes = result.get("error-codes", ["?"]) |
| 161 | + raise AccessError( |
| 162 | + _("Hcaptcha validation failed: %s") % ", ".join(error_codes) |
| 163 | + ) |
| 164 | + score = result.get("score", 1) |
| 165 | + if score < self.captcha_minimum_score: |
| 166 | + raise AccessError( |
| 167 | + _( |
| 168 | + "Hcaptcha validation failed: score %(score)s < %(min_score)s (%(reason)s)" |
| 169 | + ) |
| 170 | + % { |
| 171 | + "score": score, |
| 172 | + "min_score": self.captcha_minimum_score, |
| 173 | + "reason": result.get("score_reason", ""), |
| 174 | + } |
| 175 | + ) |
| 176 | + |
| 177 | + def _validate_altcha(self, captcha_response, secret_key): |
| 178 | + """Validate the altcha response""" |
| 179 | + data = { |
| 180 | + "apiKey": secret_key, |
| 181 | + "payload": captcha_response, |
| 182 | + } |
| 183 | + response = requests.post( |
| 184 | + "https://eu.altcha.org/api/v1/challenge/verify", |
| 185 | + data=data, |
| 186 | + timeout=10, |
| 187 | + ) |
| 188 | + result = response.json() |
| 189 | + success = result.get("verified", False) |
| 190 | + if not success: |
| 191 | + error = result.get("error", "?") |
| 192 | + raise AccessError(_("Altcha validation failed: %s") % error) |
| 193 | + |
| 194 | + @api.model |
| 195 | + def _fastapi_app_fields(self): |
| 196 | + # We need to reload fastapi app when we change these captcha fields |
| 197 | + fields = super()._fastapi_app_fields() |
| 198 | + return [ |
| 199 | + "use_captcha", |
| 200 | + "captcha_routes_regex", |
| 201 | + ] + fields |
| 202 | + |
| 203 | + |
| 204 | +def captcha_token( |
| 205 | + captcha_token: Annotated[ |
| 206 | + str | None, |
| 207 | + Header( |
| 208 | + alias="X-Captcha-Token", |
| 209 | + description="The X-Captcha-Token header is used to specify the captcha ", |
| 210 | + ), |
| 211 | + ] = None, |
| 212 | +) -> str: |
| 213 | + return captcha_token |
0 commit comments