cripcha 1.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. cripcha-1.0.3/PKG-INFO +55 -0
  2. cripcha-1.0.3/README.md +28 -0
  3. cripcha-1.0.3/pyproject.toml +39 -0
  4. cripcha-1.0.3/setup.cfg +4 -0
  5. cripcha-1.0.3/src/cripcha/__init__.py +100 -0
  6. cripcha-1.0.3/src/cripcha/django.py +63 -0
  7. cripcha-1.0.3/src/cripcha/fastapi.py +35 -0
  8. cripcha-1.0.3/src/cripcha/flask.py +41 -0
  9. cripcha-1.0.3/src/cripcha/locale/de/LC_MESSAGES/django.mo +0 -0
  10. cripcha-1.0.3/src/cripcha/locale/de/LC_MESSAGES/django.po +7 -0
  11. cripcha-1.0.3/src/cripcha/locale/es/LC_MESSAGES/django.mo +0 -0
  12. cripcha-1.0.3/src/cripcha/locale/es/LC_MESSAGES/django.po +7 -0
  13. cripcha-1.0.3/src/cripcha/locale/fr/LC_MESSAGES/django.mo +0 -0
  14. cripcha-1.0.3/src/cripcha/locale/fr/LC_MESSAGES/django.po +7 -0
  15. cripcha-1.0.3/src/cripcha/locale/it/LC_MESSAGES/django.mo +0 -0
  16. cripcha-1.0.3/src/cripcha/locale/it/LC_MESSAGES/django.po +7 -0
  17. cripcha-1.0.3/src/cripcha/locale/nl/LC_MESSAGES/django.mo +0 -0
  18. cripcha-1.0.3/src/cripcha/locale/nl/LC_MESSAGES/django.po +7 -0
  19. cripcha-1.0.3/src/cripcha/locale/pt/LC_MESSAGES/django.mo +0 -0
  20. cripcha-1.0.3/src/cripcha/locale/pt/LC_MESSAGES/django.po +7 -0
  21. cripcha-1.0.3/src/cripcha/locale/ro/LC_MESSAGES/django.mo +0 -0
  22. cripcha-1.0.3/src/cripcha/locale/ro/LC_MESSAGES/django.po +7 -0
  23. cripcha-1.0.3/src/cripcha/locale/ru/LC_MESSAGES/django.mo +0 -0
  24. cripcha-1.0.3/src/cripcha/locale/ru/LC_MESSAGES/django.po +7 -0
  25. cripcha-1.0.3/src/cripcha/locale/uk/LC_MESSAGES/django.mo +0 -0
  26. cripcha-1.0.3/src/cripcha/locale/uk/LC_MESSAGES/django.po +7 -0
  27. cripcha-1.0.3/src/cripcha.egg-info/PKG-INFO +55 -0
  28. cripcha-1.0.3/src/cripcha.egg-info/SOURCES.txt +30 -0
  29. cripcha-1.0.3/src/cripcha.egg-info/dependency_links.txt +1 -0
  30. cripcha-1.0.3/src/cripcha.egg-info/requires.txt +10 -0
  31. cripcha-1.0.3/src/cripcha.egg-info/top_level.txt +1 -0
  32. cripcha-1.0.3/tests/test_cripcha.py +157 -0
cripcha-1.0.3/PKG-INFO ADDED
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: cripcha
3
+ Version: 1.0.3
4
+ Summary: Server side check of Cripcha tokens (Django, Flask, FastAPI): the privacy-first, cookie-free captcha hosted in the EU
5
+ Author-email: Crispy Medias <contact@crispy-medias.fr>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://cripcha.crispy-medias.fr
8
+ Project-URL: Documentation, https://cripcha.crispy-medias.fr
9
+ Project-URL: Source, https://github.com/cripcha/cripcha-python
10
+ Keywords: captcha,cripcha,anti-spam,gdpr,django,flask,fastapi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Flask
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: django
21
+ Requires-Dist: django>=4.2; extra == "django"
22
+ Provides-Extra: flask
23
+ Requires-Dist: flask>=2.3; extra == "flask"
24
+ Provides-Extra: fastapi
25
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
26
+ Requires-Dist: python-multipart; extra == "fastapi"
27
+
28
+ # cripcha
29
+
30
+ Server side check of [Cripcha](https://cripcha.crispy-medias.fr) tokens for Python 3.9+: Django, Flask, FastAPI. No dependency.
31
+
32
+ ```bash
33
+ pip install cripcha # or: pip install "cripcha[django]", "cripcha[flask]", "cripcha[fastapi]"
34
+ ```
35
+
36
+ ```python
37
+ from cripcha import verify, TOKEN_FIELD
38
+ result = verify(form_data.get(TOKEN_FIELD), secret=os.environ["CRIPCHA_SECRET"])
39
+ ```
40
+
41
+ Django (`CRIPCHA_SITE_KEY`, `CRIPCHA_SECRET` in the settings; `"cripcha"` in `INSTALLED_APPS` for the translated
42
+ message):
43
+
44
+ ```python
45
+ from cripcha.django import CripchaField
46
+ class ContactForm(forms.Form):
47
+ message = forms.CharField(widget=forms.Textarea)
48
+ cripcha = CripchaField()
49
+ ```
50
+
51
+ Flask: `cripcha = Cripcha(app)`, `cripcha.verify_request()` in the view, `{{ cripcha_widget() }}` in the template.
52
+
53
+ FastAPI: `guard = CripchaGuard(secret=…)` then `Depends(guard)` on the route (403 when refused).
54
+
55
+ Fails closed, never raises for an API error. Test secrets: `cs_test_always_pass` / `cs_test_always_fail`.
@@ -0,0 +1,28 @@
1
+ # cripcha
2
+
3
+ Server side check of [Cripcha](https://cripcha.crispy-medias.fr) tokens for Python 3.9+: Django, Flask, FastAPI. No dependency.
4
+
5
+ ```bash
6
+ pip install cripcha # or: pip install "cripcha[django]", "cripcha[flask]", "cripcha[fastapi]"
7
+ ```
8
+
9
+ ```python
10
+ from cripcha import verify, TOKEN_FIELD
11
+ result = verify(form_data.get(TOKEN_FIELD), secret=os.environ["CRIPCHA_SECRET"])
12
+ ```
13
+
14
+ Django (`CRIPCHA_SITE_KEY`, `CRIPCHA_SECRET` in the settings; `"cripcha"` in `INSTALLED_APPS` for the translated
15
+ message):
16
+
17
+ ```python
18
+ from cripcha.django import CripchaField
19
+ class ContactForm(forms.Form):
20
+ message = forms.CharField(widget=forms.Textarea)
21
+ cripcha = CripchaField()
22
+ ```
23
+
24
+ Flask: `cripcha = Cripcha(app)`, `cripcha.verify_request()` in the view, `{{ cripcha_widget() }}` in the template.
25
+
26
+ FastAPI: `guard = CripchaGuard(secret=…)` then `Depends(guard)` on the route (403 when refused).
27
+
28
+ Fails closed, never raises for an API error. Test secrets: `cs_test_always_pass` / `cs_test_always_fail`.
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cripcha"
7
+ version = "1.0.3"
8
+ description = "Server side check of Cripcha tokens (Django, Flask, FastAPI): the privacy-first, cookie-free captcha hosted in the EU"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [{name = "Crispy Medias", email = "contact@crispy-medias.fr"}]
12
+ requires-python = ">=3.9"
13
+ keywords = ["captcha", "cripcha", "anti-spam", "gdpr", "django", "flask", "fastapi"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Framework :: Django",
17
+ "Framework :: Flask",
18
+ "Framework :: FastAPI",
19
+ "Intended Audience :: Developers",
20
+ "Topic :: Internet :: WWW/HTTP",
21
+ "Topic :: Security",
22
+ ]
23
+ dependencies = []
24
+
25
+ [project.optional-dependencies]
26
+ django = ["django>=4.2"]
27
+ flask = ["flask>=2.3"]
28
+ fastapi = ["fastapi>=0.100", "python-multipart"]
29
+
30
+ [project.urls]
31
+ Homepage = "https://cripcha.crispy-medias.fr"
32
+ Documentation = "https://cripcha.crispy-medias.fr"
33
+ Source = "https://github.com/cripcha/cripcha-python"
34
+
35
+ [tool.setuptools.packages.find]
36
+ where = ["src"]
37
+
38
+ [tool.setuptools.package-data]
39
+ cripcha = ["locale/*/LC_MESSAGES/*.po", "locale/*/LC_MESSAGES/*.mo"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,100 @@
1
+ """Cripcha · server side check of the tokens of the widget (POST <api>/siteverify).
2
+
3
+ Fails closed: only {"success": true} accepts the form; an unreachable API or an unexpected answer refuses it,
4
+ without raising. No dependency (urllib).
5
+
6
+ from cripcha import verify, TOKEN_FIELD
7
+ result = verify(request.POST.get(TOKEN_FIELD), secret=settings.CRIPCHA_SECRET)
8
+ if not result.success:
9
+ ... # refuse the form
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import urllib.error
16
+ import urllib.parse
17
+ import urllib.request
18
+ from dataclasses import dataclass, field
19
+ from typing import Callable, Optional
20
+
21
+ __all__ = ["verify", "Result", "TOKEN_FIELD", "DEFAULT_API_URL", "DEFAULT_WIDGET_URL", "widget_html"]
22
+
23
+ TOKEN_FIELD = "cripcha-response"
24
+ DEFAULT_API_URL = "https://cripcha.crispy-medias.fr/api/v1"
25
+ DEFAULT_WIDGET_URL = "https://cripcha-widget.s3.eu-west-par.io.cloud.ovh.net/v1/widget.js"
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class Result:
30
+ success: bool
31
+ error_codes: list = field(default_factory=list)
32
+ challenge_ts: Optional[str] = None
33
+ site_key: Optional[str] = None
34
+
35
+ def __bool__(self) -> bool:
36
+ return self.success
37
+
38
+
39
+ def _failure(code: str) -> Result:
40
+ return Result(False, [code])
41
+
42
+
43
+ # (url, form fields, timeout) -> (status, body); raises OSError when the API cannot be reached
44
+ Transport = Callable[[str, dict, float], "tuple[int, str]"]
45
+
46
+
47
+ def _urllib_transport(url: str, fields: dict, timeout: float) -> "tuple[int, str]":
48
+ request = urllib.request.Request(
49
+ url,
50
+ data=urllib.parse.urlencode(fields).encode(),
51
+ headers={"Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json", "User-Agent": "cripcha-python"},
52
+ method="POST",
53
+ )
54
+ try:
55
+ with urllib.request.urlopen(request, timeout=timeout) as response:
56
+ return response.status, response.read().decode("utf-8", "replace")
57
+ except urllib.error.HTTPError as error:
58
+ return error.code, error.read().decode("utf-8", "replace")
59
+
60
+
61
+ def verify(token: object, secret: str, api_url: str = DEFAULT_API_URL, timeout: float = 5.0, transport: Optional[Transport] = None) -> Result:
62
+ # no secret configured: every form refused, without calling the API
63
+ if not isinstance(secret, str) or secret.strip() == "":
64
+ return _failure("missing-input-secret")
65
+ value = token.strip() if isinstance(token, str) else ""
66
+ if value == "":
67
+ return _failure("missing-input-response")
68
+ try:
69
+ status, body = (transport or _urllib_transport)(api_url.rstrip("/") + "/siteverify", {"secret": secret, "response": value}, timeout)
70
+ except (OSError, ValueError):
71
+ return _failure("network-error")
72
+ if status != 200:
73
+ return _failure("bad-response")
74
+ try:
75
+ data = json.loads(body)
76
+ except ValueError:
77
+ return _failure("bad-response")
78
+ if not isinstance(data, dict):
79
+ return _failure("bad-response")
80
+ errors = [code for code in data.get("error-codes", []) if isinstance(code, str)] if isinstance(data.get("error-codes"), list) else []
81
+ if data.get("success") is not True:
82
+ return Result(False, errors)
83
+ challenge_ts = data.get("challenge_ts")
84
+ site_key = data.get("sitekey")
85
+ return Result(True, [], challenge_ts if isinstance(challenge_ts, str) else None, site_key if isinstance(site_key, str) else None)
86
+
87
+
88
+ def widget_html(site_key: str, widget_url: str = DEFAULT_WIDGET_URL, lang: Optional[str] = None, form: Optional[str] = None, with_script: bool = True) -> str:
89
+ """the widget for a template (Jinja2: {{ cripcha_widget|safe }})"""
90
+ from html import escape
91
+
92
+ attributes = f' data-sitekey="{escape(site_key)}"'
93
+ if lang:
94
+ attributes += f' data-lang="{escape(lang)}"'
95
+ if form:
96
+ attributes += f' data-form="{escape(form)}"'
97
+ html = f'<div class="cripcha"{attributes}></div>'
98
+ if with_script:
99
+ html += f'<script src="{escape(widget_url)}" async defer></script>'
100
+ return html
@@ -0,0 +1,63 @@
1
+ """Django: a form field showing the widget and checking the token.
2
+
3
+ # settings.py
4
+ CRIPCHA_SITE_KEY = "ck_…"
5
+ CRIPCHA_SECRET = env("CRIPCHA_SECRET")
6
+
7
+ # forms.py
8
+ from cripcha.django import CripchaField
9
+ class ContactForm(forms.Form):
10
+ message = forms.CharField(widget=forms.Textarea)
11
+ cripcha = CripchaField()
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from django import forms
17
+ from django.conf import settings
18
+ from django.core.exceptions import ValidationError
19
+ from django.utils.safestring import mark_safe
20
+ from django.utils.translation import get_language, gettext_lazy as _
21
+
22
+ from . import DEFAULT_API_URL, DEFAULT_WIDGET_URL, TOKEN_FIELD, verify, widget_html
23
+
24
+
25
+ class CripchaWidget(forms.Widget):
26
+ """the widget of Cripcha; the token comes from the field cripcha-response that the widget adds to the form"""
27
+
28
+ def render(self, name, value, attrs=None, renderer=None):
29
+ lang = (get_language() or "")[:2] or None
30
+ return mark_safe(widget_html(getattr(settings, "CRIPCHA_SITE_KEY", ""), getattr(settings, "CRIPCHA_WIDGET_URL", DEFAULT_WIDGET_URL), lang=lang))
31
+
32
+ def value_from_datadict(self, data, files, name):
33
+ return data.get(TOKEN_FIELD, "")
34
+
35
+ def value_omitted_from_data(self, data, files, name):
36
+ return TOKEN_FIELD not in data
37
+
38
+
39
+ class CripchaField(forms.Field):
40
+ widget = CripchaWidget
41
+ default_error_messages = {"invalid": _("The bot check did not complete: wait a second, then send the form again.")}
42
+
43
+ def __init__(self, **kwargs):
44
+ kwargs.setdefault("label", "")
45
+ kwargs.setdefault("required", True)
46
+ super().__init__(**kwargs)
47
+
48
+ def validate(self, value):
49
+ if not getattr(settings, "CRIPCHA_ENABLED", True):
50
+ return
51
+ result = verify(
52
+ value,
53
+ secret=getattr(settings, "CRIPCHA_SECRET", ""),
54
+ api_url=getattr(settings, "CRIPCHA_API_URL", DEFAULT_API_URL),
55
+ timeout=getattr(settings, "CRIPCHA_TIMEOUT", 5.0),
56
+ )
57
+ if not result.success:
58
+ raise ValidationError(self.error_messages["invalid"], code="invalid")
59
+
60
+ def clean(self, value):
61
+ # the token is only checked, never kept in cleaned_data
62
+ self.validate(value)
63
+ return None
@@ -0,0 +1,35 @@
1
+ """FastAPI: a dependency refusing the request (403) when the token of the form is not valid.
2
+
3
+ from cripcha.fastapi import CripchaGuard
4
+ guard = CripchaGuard(secret=os.environ["CRIPCHA_SECRET"])
5
+
6
+ @app.post("/contact")
7
+ async def contact(message: str = Form(...), _: Result = Depends(guard)):
8
+ ...
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Optional
14
+
15
+ from fastapi import Form, HTTPException
16
+ from starlette.concurrency import run_in_threadpool
17
+
18
+ from . import DEFAULT_API_URL, TOKEN_FIELD, Result, verify
19
+
20
+
21
+ class CripchaGuard:
22
+ def __init__(self, secret: str, api_url: str = DEFAULT_API_URL, timeout: float = 5.0, enabled: bool = True):
23
+ self.secret = secret
24
+ self.api_url = api_url
25
+ self.timeout = timeout
26
+ self.enabled = enabled
27
+
28
+ async def __call__(self, token: Optional[str] = Form(default=None, alias=TOKEN_FIELD)) -> Result:
29
+ if not self.enabled:
30
+ return Result(True)
31
+ # urllib blocks: in the thread pool, not in the event loop
32
+ result = await run_in_threadpool(verify, token, self.secret, self.api_url, self.timeout)
33
+ if not result.success:
34
+ raise HTTPException(status_code=403, detail={"error": "cripcha", "error_codes": result.error_codes})
35
+ return result
@@ -0,0 +1,41 @@
1
+ """Flask: the token of the submitted form, checked; and the widget in the Jinja2 templates.
2
+
3
+ from cripcha.flask import Cripcha
4
+ cripcha = Cripcha(app) # CRIPCHA_SITE_KEY, CRIPCHA_SECRET in app.config
5
+
6
+ @app.post("/contact")
7
+ def contact():
8
+ if not cripcha.verify_request():
9
+ abort(403)
10
+
11
+ {{ cripcha_widget() }} in the form
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from flask import Flask, request
17
+ from markupsafe import Markup
18
+
19
+ from . import DEFAULT_API_URL, DEFAULT_WIDGET_URL, TOKEN_FIELD, Result, verify, widget_html
20
+
21
+
22
+ class Cripcha:
23
+ def __init__(self, app: Flask | None = None):
24
+ if app is not None:
25
+ self.init_app(app)
26
+
27
+ def init_app(self, app: Flask) -> None:
28
+ app.config.setdefault("CRIPCHA_SITE_KEY", "")
29
+ app.config.setdefault("CRIPCHA_SECRET", "")
30
+ app.config.setdefault("CRIPCHA_API_URL", DEFAULT_API_URL)
31
+ app.config.setdefault("CRIPCHA_WIDGET_URL", DEFAULT_WIDGET_URL)
32
+ app.config.setdefault("CRIPCHA_ENABLED", True)
33
+ app.extensions["cripcha"] = self
34
+ app.jinja_env.globals["cripcha_widget"] = lambda **options: Markup(widget_html(app.config["CRIPCHA_SITE_KEY"], app.config["CRIPCHA_WIDGET_URL"], **options))
35
+ self.app = app
36
+
37
+ def verify_request(self) -> Result:
38
+ config = self.app.config
39
+ if not config["CRIPCHA_ENABLED"]:
40
+ return Result(True)
41
+ return verify(request.form.get(TOKEN_FIELD), secret=config["CRIPCHA_SECRET"], api_url=config["CRIPCHA_API_URL"])
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: de\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Die Bot-Prüfung wurde nicht abgeschlossen: Warten Sie eine Sekunde und senden Sie das Formular erneut."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: es\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La verificación antirrobots no se ha completado: espere un segundo y vuelva a enviar el formulario."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: fr\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La vérification anti-robot n'a pas abouti : patientez une seconde puis renvoyez le formulaire."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: it\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "La verifica antibot non è stata completata: attenda un secondo e invii di nuovo il modulo."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: nl\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "De botcontrole is niet voltooid: wacht een seconde en verstuur het formulier opnieuw."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: pt\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "A verificação anti-robô não foi concluída: aguarde um segundo e envie o formulário de novo."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: ro\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Verificarea anti-robot nu s-a încheiat: așteptați o secundă și trimiteți din nou formularul."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: ru\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Проверка на робота не завершена: подождите секунду и отправьте форму ещё раз."
@@ -0,0 +1,7 @@
1
+ msgid ""
2
+ msgstr ""
3
+ "Content-Type: text/plain; charset=UTF-8\n"
4
+ "Language: uk\n"
5
+
6
+ msgid "The bot check did not complete: wait a second, then send the form again."
7
+ msgstr "Перевірку на робота не завершено: зачекайте секунду й надішліть форму ще раз."
@@ -0,0 +1,55 @@
1
+ Metadata-Version: 2.4
2
+ Name: cripcha
3
+ Version: 1.0.3
4
+ Summary: Server side check of Cripcha tokens (Django, Flask, FastAPI): the privacy-first, cookie-free captcha hosted in the EU
5
+ Author-email: Crispy Medias <contact@crispy-medias.fr>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://cripcha.crispy-medias.fr
8
+ Project-URL: Documentation, https://cripcha.crispy-medias.fr
9
+ Project-URL: Source, https://github.com/cripcha/cripcha-python
10
+ Keywords: captcha,cripcha,anti-spam,gdpr,django,flask,fastapi
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Framework :: Django
13
+ Classifier: Framework :: Flask
14
+ Classifier: Framework :: FastAPI
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Topic :: Internet :: WWW/HTTP
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ Provides-Extra: django
21
+ Requires-Dist: django>=4.2; extra == "django"
22
+ Provides-Extra: flask
23
+ Requires-Dist: flask>=2.3; extra == "flask"
24
+ Provides-Extra: fastapi
25
+ Requires-Dist: fastapi>=0.100; extra == "fastapi"
26
+ Requires-Dist: python-multipart; extra == "fastapi"
27
+
28
+ # cripcha
29
+
30
+ Server side check of [Cripcha](https://cripcha.crispy-medias.fr) tokens for Python 3.9+: Django, Flask, FastAPI. No dependency.
31
+
32
+ ```bash
33
+ pip install cripcha # or: pip install "cripcha[django]", "cripcha[flask]", "cripcha[fastapi]"
34
+ ```
35
+
36
+ ```python
37
+ from cripcha import verify, TOKEN_FIELD
38
+ result = verify(form_data.get(TOKEN_FIELD), secret=os.environ["CRIPCHA_SECRET"])
39
+ ```
40
+
41
+ Django (`CRIPCHA_SITE_KEY`, `CRIPCHA_SECRET` in the settings; `"cripcha"` in `INSTALLED_APPS` for the translated
42
+ message):
43
+
44
+ ```python
45
+ from cripcha.django import CripchaField
46
+ class ContactForm(forms.Form):
47
+ message = forms.CharField(widget=forms.Textarea)
48
+ cripcha = CripchaField()
49
+ ```
50
+
51
+ Flask: `cripcha = Cripcha(app)`, `cripcha.verify_request()` in the view, `{{ cripcha_widget() }}` in the template.
52
+
53
+ FastAPI: `guard = CripchaGuard(secret=…)` then `Depends(guard)` on the route (403 when refused).
54
+
55
+ Fails closed, never raises for an API error. Test secrets: `cs_test_always_pass` / `cs_test_always_fail`.
@@ -0,0 +1,30 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/cripcha/__init__.py
4
+ src/cripcha/django.py
5
+ src/cripcha/fastapi.py
6
+ src/cripcha/flask.py
7
+ src/cripcha.egg-info/PKG-INFO
8
+ src/cripcha.egg-info/SOURCES.txt
9
+ src/cripcha.egg-info/dependency_links.txt
10
+ src/cripcha.egg-info/requires.txt
11
+ src/cripcha.egg-info/top_level.txt
12
+ src/cripcha/locale/de/LC_MESSAGES/django.mo
13
+ src/cripcha/locale/de/LC_MESSAGES/django.po
14
+ src/cripcha/locale/es/LC_MESSAGES/django.mo
15
+ src/cripcha/locale/es/LC_MESSAGES/django.po
16
+ src/cripcha/locale/fr/LC_MESSAGES/django.mo
17
+ src/cripcha/locale/fr/LC_MESSAGES/django.po
18
+ src/cripcha/locale/it/LC_MESSAGES/django.mo
19
+ src/cripcha/locale/it/LC_MESSAGES/django.po
20
+ src/cripcha/locale/nl/LC_MESSAGES/django.mo
21
+ src/cripcha/locale/nl/LC_MESSAGES/django.po
22
+ src/cripcha/locale/pt/LC_MESSAGES/django.mo
23
+ src/cripcha/locale/pt/LC_MESSAGES/django.po
24
+ src/cripcha/locale/ro/LC_MESSAGES/django.mo
25
+ src/cripcha/locale/ro/LC_MESSAGES/django.po
26
+ src/cripcha/locale/ru/LC_MESSAGES/django.mo
27
+ src/cripcha/locale/ru/LC_MESSAGES/django.po
28
+ src/cripcha/locale/uk/LC_MESSAGES/django.mo
29
+ src/cripcha/locale/uk/LC_MESSAGES/django.po
30
+ tests/test_cripcha.py
@@ -0,0 +1,10 @@
1
+
2
+ [django]
3
+ django>=4.2
4
+
5
+ [fastapi]
6
+ fastapi>=0.100
7
+ python-multipart
8
+
9
+ [flask]
10
+ flask>=2.3
@@ -0,0 +1 @@
1
+ cripcha
@@ -0,0 +1,157 @@
1
+ import json
2
+ import os
3
+ import pathlib
4
+ import unittest
5
+
6
+ from cripcha import Result, verify, widget_html
7
+
8
+ # spec/ of the monorepo, or a copy next to the tests in the public repository (scripts/publish-split.sh)
9
+ _SPEC_FILE = next(p for p in (pathlib.Path(__file__).parents[2] / "spec" / "cases.json", pathlib.Path(__file__).parent / "cases.json") if p.exists())
10
+ SPEC = json.loads(_SPEC_FILE.read_text())
11
+
12
+
13
+ def fake_api(accepted="good"):
14
+ calls = []
15
+
16
+ def transport(url, fields, timeout):
17
+ calls.append((url, fields))
18
+ return 200, json.dumps({"success": fields["response"] == accepted})
19
+
20
+ return transport, calls
21
+
22
+
23
+ class SharedCasesTest(unittest.TestCase):
24
+ def test_shared_cases(self):
25
+ for case in SPEC["cases"]:
26
+ with self.subTest(case["name"]):
27
+ calls = []
28
+
29
+ def transport(url, fields, timeout, case=case):
30
+ calls.append((url, fields))
31
+ if case["response"] == "network-error":
32
+ raise OSError("down")
33
+ return case["response"]["status"], case["response"]["body"]
34
+
35
+ result = verify(case["token"], secret="cs_secret", api_url="https://api.example.test/api/v1/", transport=transport)
36
+ expected = case["expected"]
37
+ self.assertEqual(result, Result(expected["success"], expected["error_codes"], expected["challenge_ts"], expected["sitekey"]))
38
+ self.assertEqual(calls, [] if case["response"] is None else [("https://api.example.test/api/v1/siteverify", {"secret": "cs_secret", "response": case["token"]})])
39
+
40
+ def test_widget_html_is_escaped(self):
41
+ html = widget_html('ck_"x', lang="fr", form="#login")
42
+ self.assertIn('data-sitekey="ck_&quot;x"', html)
43
+ self.assertIn('data-form="#login"', html)
44
+ self.assertEqual(widget_html("ck", with_script=False).count("<script"), 0)
45
+
46
+ @unittest.skipUnless(os.environ.get("CRIPCHA_E2E_API"), "CRIPCHA_E2E_API not set")
47
+ def test_against_the_api(self):
48
+ api = os.environ["CRIPCHA_E2E_API"]
49
+ self.assertTrue(verify("test.test.0.0", secret="cs_test_always_pass", api_url=api).success)
50
+ self.assertFalse(verify("test.test.0.0", secret="cs_test_always_fail", api_url=api).success)
51
+ self.assertEqual(verify("test.test.0.0", secret="cs_wrong", api_url=api).error_codes, ["invalid-input-secret"])
52
+
53
+
54
+ class DjangoTest(unittest.TestCase):
55
+ @classmethod
56
+ def setUpClass(cls):
57
+ import django
58
+ from django.conf import settings
59
+
60
+ if not settings.configured:
61
+ settings.configure(CRIPCHA_SITE_KEY="ck_abc", CRIPCHA_SECRET="cs_x", USE_I18N=True, LANGUAGE_CODE="en", INSTALLED_APPS=["cripcha"])
62
+ django.setup()
63
+
64
+ def test_the_field(self):
65
+ from unittest import mock
66
+
67
+ from django import forms
68
+
69
+ from cripcha.django import CripchaField
70
+
71
+ class ContactForm(forms.Form):
72
+ message = forms.CharField()
73
+ cripcha = CripchaField()
74
+
75
+ transport, calls = fake_api()
76
+ with mock.patch("cripcha._urllib_transport", transport):
77
+ self.assertTrue(ContactForm({"message": "hi", "cripcha-response": "good"}).is_valid())
78
+ form = ContactForm({"message": "hi", "cripcha-response": "bad"})
79
+ self.assertFalse(form.is_valid())
80
+ self.assertIn("bot check", str(form.errors["cripcha"]))
81
+ self.assertFalse(ContactForm({"message": "hi"}).is_valid())
82
+ from django.utils import translation
83
+
84
+ with translation.override("fr"):
85
+ form = ContactForm({"message": "hi", "cripcha-response": "bad"})
86
+ self.assertIn("anti-robot", str(form.errors["cripcha"]))
87
+ html = str(ContactForm()["cripcha"])
88
+ self.assertIn('data-sitekey="ck_abc"', html)
89
+
90
+
91
+ class FlaskTest(unittest.TestCase):
92
+ def test_the_extension(self):
93
+ from unittest import mock
94
+
95
+ from flask import Flask, render_template_string
96
+
97
+ from cripcha.flask import Cripcha
98
+
99
+ app = Flask(__name__)
100
+ app.config["CRIPCHA_SECRET"] = "cs_x"
101
+ cripcha = Cripcha(app)
102
+
103
+ @app.post("/contact")
104
+ def contact():
105
+ return ("ok", 200) if cripcha.verify_request() else ("no", 403)
106
+
107
+ transport, _ = fake_api()
108
+ with mock.patch("cripcha._urllib_transport", transport):
109
+ client = app.test_client()
110
+ self.assertEqual(client.post("/contact", data={"cripcha-response": "good"}).status_code, 200)
111
+ self.assertEqual(client.post("/contact", data={"cripcha-response": "bad"}).status_code, 403)
112
+ with app.app_context():
113
+ self.assertIn('class="cripcha"', render_template_string("{{ cripcha_widget(lang='fr') }}"))
114
+
115
+
116
+ class NoSecretTest(unittest.TestCase):
117
+ def test_refused_without_calling_the_api(self):
118
+ calls = []
119
+
120
+ def transport(url, fields, timeout):
121
+ calls.append(url)
122
+ return 200, '{"success": true}'
123
+
124
+ for secret in ("", " ", None):
125
+ result = verify("tok", secret=secret, transport=transport)
126
+ self.assertFalse(result.success)
127
+ self.assertEqual(result.error_codes, ["missing-input-secret"])
128
+ self.assertEqual(calls, [])
129
+
130
+
131
+ class FastApiTest(unittest.TestCase):
132
+ def test_the_guard(self):
133
+ from unittest import mock
134
+
135
+ from fastapi import Depends, FastAPI, Form
136
+ from fastapi.testclient import TestClient
137
+
138
+ from cripcha.fastapi import CripchaGuard
139
+
140
+ app = FastAPI()
141
+ guard = CripchaGuard(secret="cs_x")
142
+
143
+ @app.post("/contact")
144
+ async def contact(message: str = Form(...), _=Depends(guard)):
145
+ return {"ok": True}
146
+
147
+ transport, _ = fake_api()
148
+ with mock.patch("cripcha._urllib_transport", transport):
149
+ client = TestClient(app)
150
+ self.assertEqual(client.post("/contact", data={"message": "hi", "cripcha-response": "good"}).status_code, 200)
151
+ refused = client.post("/contact", data={"message": "hi", "cripcha-response": "bad"})
152
+ self.assertEqual(refused.status_code, 403)
153
+ self.assertEqual(client.post("/contact", data={"message": "hi"}).status_code, 403)
154
+
155
+
156
+ if __name__ == "__main__":
157
+ unittest.main()