django-gemini 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,35 @@
1
+ """Serve an existing Django site over the Gemini protocol, next to HTTP."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from .request import (
6
+ cert_fingerprint,
7
+ get_client_cert,
8
+ get_fingerprint,
9
+ get_input,
10
+ is_gemini,
11
+ )
12
+ from .responses import (
13
+ GeminiResponse,
14
+ certificate_response,
15
+ gemtext_response,
16
+ input_response,
17
+ render_gemtext,
18
+ )
19
+ from .status import GEMTEXT
20
+
21
+ __version__ = version("django-gemini")
22
+
23
+ __all__ = [
24
+ "GEMTEXT",
25
+ "GeminiResponse",
26
+ "cert_fingerprint",
27
+ "certificate_response",
28
+ "gemtext_response",
29
+ "get_client_cert",
30
+ "get_fingerprint",
31
+ "get_input",
32
+ "input_response",
33
+ "is_gemini",
34
+ "render_gemtext",
35
+ ]
django_gemini/admin.py ADDED
@@ -0,0 +1,16 @@
1
+ from django.contrib import admin
2
+
3
+ from .models import ClientCertificate
4
+
5
+
6
+ @admin.register(ClientCertificate)
7
+ class ClientCertificateAdmin(admin.ModelAdmin):
8
+ list_display = ["user", "label", "short_fingerprint", "created", "last_used"]
9
+ list_select_related = ["user"]
10
+ search_fields = ["fingerprint", "label", "user__username"]
11
+ readonly_fields = ["created", "last_used"]
12
+ raw_id_fields = ["user"]
13
+
14
+ @admin.display(description="fingerprint", ordering="fingerprint")
15
+ def short_fingerprint(self, obj):
16
+ return obj.fingerprint[:16] + "…"
django_gemini/apps.py ADDED
@@ -0,0 +1,10 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class DjangoGeminiConfig(AppConfig):
5
+ name = "django_gemini"
6
+ verbose_name = "Gemini"
7
+ default_auto_field = "django.db.models.BigAutoField"
8
+
9
+ def ready(self):
10
+ from . import checks as _checks # noqa: F401 (registers the checks)
django_gemini/asgi.py ADDED
@@ -0,0 +1,140 @@
1
+ """The ASGI side: serve a Django project over Gemini with asgi-gemini.
2
+
3
+ In your project's asgi.py::
4
+
5
+ import os
6
+ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
7
+
8
+ from django_gemini.asgi import get_asgi_application
9
+ application = get_asgi_application()
10
+
11
+ Run it with ``asgi-gemini mysite.asgi:application`` (or ``manage.py
12
+ rungemini`` while developing). The same application still serves HTTP with
13
+ any ASGI server: HTTP scopes go to Django untouched.
14
+
15
+ Django only understands ``http`` scopes, so ``GeminiBridge`` turns each Gemini
16
+ request into an HTTP GET (with the Gemini scope in ``scope["gemini"]``) and
17
+ Django's response back into a Gemini response.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import django
23
+ from django.core.handlers.asgi import ASGIHandler, ASGIRequest
24
+
25
+ from .status import to_gemini_status
26
+
27
+
28
+ class GeminiASGIRequest(ASGIRequest):
29
+ """An ASGI request that knows Gemini is always over TLS.
30
+
31
+ ``request.scheme`` is "gemini", so ``build_absolute_uri()`` gives gemini://
32
+ URLs, and ``is_secure()`` is True, so SECURE_SSL_REDIRECT doesn't send
33
+ Gemini clients to https://.
34
+ """
35
+
36
+ def is_secure(self):
37
+ return "gemini" in self.scope or super().is_secure()
38
+
39
+
40
+ class GeminiASGIHandler(ASGIHandler):
41
+ request_class = GeminiASGIRequest
42
+
43
+
44
+ def get_asgi_application() -> GeminiBridge:
45
+ """Like Django's get_asgi_application(), but serving Gemini too."""
46
+ django.setup(set_prefix=False)
47
+ return GeminiBridge(GeminiASGIHandler())
48
+
49
+
50
+ class GeminiBridge:
51
+ """ASGI app that serves an ASGI application (Django's) over Gemini.
52
+
53
+ Gemini scopes are translated; HTTP and WebSocket scopes are passed through,
54
+ so it can wrap anything, a Channels router included. A plain Django
55
+ ``ASGIHandler`` gets ``GeminiASGIRequest`` as its request class.
56
+ """
57
+
58
+ def __init__(self, app):
59
+ if isinstance(app, ASGIHandler) and app.request_class is ASGIRequest:
60
+ app.request_class = GeminiASGIRequest
61
+ self.app = app
62
+
63
+ async def __call__(self, scope, receive, send):
64
+ if scope["type"] == "gemini":
65
+ await self.handle_gemini(scope, receive, send)
66
+ elif scope["type"] == "lifespan" and isinstance(self.app, ASGIHandler):
67
+ await self._lifespan(receive, send) # Django has no lifespan support
68
+ else:
69
+ await self.app(scope, receive, send)
70
+
71
+ async def _lifespan(self, receive, send):
72
+ while True:
73
+ message = await receive()
74
+ if message["type"] == "lifespan.startup":
75
+ await send({"type": "lifespan.startup.complete"})
76
+ elif message["type"] == "lifespan.shutdown":
77
+ await send({"type": "lifespan.shutdown.complete"})
78
+ return
79
+
80
+ async def handle_gemini(self, scope, receive, send):
81
+ request_sent = False
82
+ gemini_status = None
83
+
84
+ async def http_receive():
85
+ nonlocal request_sent
86
+ if not request_sent:
87
+ request_sent = True
88
+ return {"type": "http.request", "body": b"", "more_body": False}
89
+ await receive() # only ever gemini.disconnect
90
+ return {"type": "http.disconnect"}
91
+
92
+ async def http_send(message):
93
+ nonlocal gemini_status
94
+ if message["type"] == "http.response.start":
95
+ headers = {
96
+ name.decode("latin-1").lower(): value.decode("latin-1")
97
+ for name, value in message.get("headers", [])
98
+ }
99
+ gemini_status, meta = to_gemini_status(message["status"], headers)
100
+ await send(
101
+ {
102
+ "type": "gemini.response.start",
103
+ "status": gemini_status,
104
+ "meta": meta,
105
+ }
106
+ )
107
+ elif message["type"] == "http.response.body":
108
+ # Only 2x Gemini responses have a body.
109
+ if gemini_status is not None and 20 <= gemini_status <= 29:
110
+ await send(
111
+ {
112
+ "type": "gemini.response.body",
113
+ "body": message.get("body", b""),
114
+ "more_body": message.get("more_body", False),
115
+ }
116
+ )
117
+
118
+ await self.app(to_http_scope(scope), http_receive, http_send)
119
+
120
+
121
+ def to_http_scope(scope: dict) -> dict:
122
+ """The HTTP GET scope Django sees for a Gemini request."""
123
+ host, _, port = scope["netloc"].rpartition("@")[2].partition(":")
124
+ host_header = host.encode("idna") + (f":{port}".encode() if port else b"")
125
+ return {
126
+ "type": "http",
127
+ "asgi": {"version": "3.0", "spec_version": "2.3"},
128
+ "http_version": "1.1",
129
+ "method": "GET",
130
+ "scheme": scope["scheme"],
131
+ "path": scope["path"] or "/",
132
+ "raw_path": scope["raw_path"] or b"/",
133
+ "query_string": scope["query"].encode("utf-8"),
134
+ "root_path": scope["root_path"],
135
+ "headers": [(b"host", host_header)],
136
+ "client": scope["client"],
137
+ "server": scope["server"],
138
+ "state": scope.get("state", {}),
139
+ "gemini": scope,
140
+ }
django_gemini/auth.py ADDED
@@ -0,0 +1,143 @@
1
+ """Client certificates as logins."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+ import urllib.parse
7
+
8
+ from asgiref.sync import sync_to_async
9
+ from django.contrib.auth.models import AnonymousUser
10
+ from django.core.cache import cache
11
+ from django.http import HttpRequest
12
+ from django.shortcuts import redirect
13
+ from django.urls import NoReverseMatch, reverse
14
+ from django.utils import timezone
15
+ from django.utils.functional import SimpleLazyObject
16
+
17
+ from . import conf
18
+ from .request import get_fingerprint, is_gemini
19
+ from .responses import GeminiResponse, certificate_response
20
+
21
+ #: How often last_used is updated.
22
+ TOUCH_INTERVAL = datetime.timedelta(minutes=5)
23
+
24
+
25
+ def get_certificate(fingerprint: str | None):
26
+ """The ClientCertificate for a fingerprint, with its user, or None."""
27
+ from .models import ClientCertificate
28
+
29
+ if not fingerprint:
30
+ return None
31
+ certificate = (
32
+ ClientCertificate.objects.select_related("user")
33
+ .filter(fingerprint=fingerprint)
34
+ .first()
35
+ )
36
+ if certificate is not None:
37
+ now = timezone.now()
38
+ if (
39
+ certificate.last_used is None
40
+ or now - certificate.last_used > TOUCH_INTERVAL
41
+ ):
42
+ ClientCertificate.objects.filter(pk=certificate.pk).update(last_used=now)
43
+ certificate.last_used = now
44
+ return certificate
45
+
46
+
47
+ def get_certificate_user(fingerprint: str | None):
48
+ """The active user a certificate is linked to, or AnonymousUser."""
49
+ certificate = get_certificate(fingerprint)
50
+ if certificate is not None and certificate.user.is_active:
51
+ return certificate.user
52
+ return AnonymousUser()
53
+
54
+
55
+ class CertificateAuthenticationMiddleware:
56
+ """Over Gemini, ``request.user`` is the user the client certificate is linked to.
57
+
58
+ Put it after Django's AuthenticationMiddleware, which it replaces for
59
+ Gemini requests (they have no session cookie). HTTP requests are untouched.
60
+ """
61
+
62
+ def __init__(self, get_response):
63
+ self.get_response = get_response
64
+
65
+ def __call__(self, request: HttpRequest):
66
+ if is_gemini(request):
67
+ fingerprint = get_fingerprint(request)
68
+ request.user = SimpleLazyObject(lambda: get_certificate_user(fingerprint))
69
+
70
+ async def auser():
71
+ return await sync_to_async(get_certificate_user)(fingerprint)
72
+
73
+ request.auser = auser
74
+ return self.get_response(request)
75
+
76
+
77
+ # -- Sending Gemini clients to the login ------------------------------------
78
+
79
+
80
+ def _next_key(fingerprint: str) -> str:
81
+ return f"django_gemini:next:{fingerprint}"
82
+
83
+
84
+ def remember_next(fingerprint: str, next_url: str) -> None:
85
+ cache.set(_next_key(fingerprint), next_url, conf.get("GEMINI_LOGIN_WINDOW"))
86
+
87
+
88
+ def pop_next(fingerprint: str) -> str | None:
89
+ key = _next_key(fingerprint)
90
+ value = cache.get(key)
91
+ cache.delete(key)
92
+ return value
93
+
94
+
95
+ def gemini_login_url(request: HttpRequest) -> str | None:
96
+ """The path of the Gemini login (GEMINI_LOGIN_URL), or None if it isn't routed."""
97
+ target = conf.get("GEMINI_LOGIN_URL")
98
+ if not target:
99
+ return None
100
+ if "/" in target:
101
+ return target
102
+ try:
103
+ return reverse(target, urlconf=getattr(request, "urlconf", None))
104
+ except NoReverseMatch:
105
+ return None
106
+
107
+
108
+ def login_redirect(request: HttpRequest, next_url: str | None = None):
109
+ """Send a Gemini client to the login, to come back to next_url afterwards.
110
+
111
+ Without a certificate it gets a 60 (it needs one to log in at all); if
112
+ there's no Gemini login view, a 61.
113
+ """
114
+ fingerprint = get_fingerprint(request)
115
+ if fingerprint is None:
116
+ return certificate_response("Log in with a client certificate")
117
+ login_url = gemini_login_url(request)
118
+ if login_url is None:
119
+ return GeminiResponse(61, "Login required")
120
+ remember_next(fingerprint, next_url or request.get_full_path())
121
+ return redirect(login_url)
122
+
123
+
124
+ def rewrite_login_redirect(request: HttpRequest, response):
125
+ """If a response redirects to settings.LOGIN_URL (``@login_required`` and
126
+ friends), send the Gemini client to the Gemini login instead."""
127
+ from django.conf import settings
128
+ from django.shortcuts import resolve_url
129
+
130
+ if (
131
+ response.status_code not in (301, 302, 303, 307, 308)
132
+ or "Location" not in response
133
+ ):
134
+ return response
135
+ try:
136
+ login_path = urllib.parse.urlsplit(resolve_url(settings.LOGIN_URL)).path
137
+ except NoReverseMatch:
138
+ return response
139
+ location = urllib.parse.urlsplit(response["Location"])
140
+ if location.path != login_path or login_path == gemini_login_url(request):
141
+ return response
142
+ next_url = urllib.parse.parse_qs(location.query).get("next", [None])[0]
143
+ return login_redirect(request, next_url)
@@ -0,0 +1,63 @@
1
+ from importlib import import_module
2
+
3
+ from django.conf import settings
4
+ from django.core import checks
5
+
6
+ GEMINI = "django_gemini.middleware.GeminiMiddleware"
7
+ CERT_AUTH = "django_gemini.auth.CertificateAuthenticationMiddleware"
8
+ DJANGO_AUTH = "django.contrib.auth.middleware.AuthenticationMiddleware"
9
+
10
+
11
+ @checks.register()
12
+ def check_settings(app_configs, **kwargs):
13
+ errors = []
14
+ middleware = list(settings.MIDDLEWARE)
15
+ if GEMINI not in middleware:
16
+ errors.append(
17
+ checks.Warning(
18
+ f"{GEMINI} isn't in MIDDLEWARE.",
19
+ hint="Add it first: it hides GEMINI_HIDDEN_PATHS, routes GEMINI_URLCONF, "
20
+ "converts HTML and sends login redirects to the Gemini login.",
21
+ id="django_gemini.W001",
22
+ )
23
+ )
24
+ else:
25
+ # Middleware that must see every request (an access log) can come first,
26
+ # but Django's own should run after it.
27
+ before = [
28
+ m for m in middleware[: middleware.index(GEMINI)] if m.startswith("django.")
29
+ ]
30
+ if before:
31
+ errors.append(
32
+ checks.Warning(
33
+ f"{GEMINI} comes after {before[0]}.",
34
+ hint="Put it before Django's middleware, which otherwise sees "
35
+ "Gemini requests for hidden paths, and responses before the "
36
+ "Gemini login redirect.",
37
+ id="django_gemini.W002",
38
+ )
39
+ )
40
+ if (
41
+ CERT_AUTH in middleware
42
+ and DJANGO_AUTH in middleware
43
+ and middleware.index(CERT_AUTH) < middleware.index(DJANGO_AUTH)
44
+ ):
45
+ errors.append(
46
+ checks.Error(
47
+ f"{CERT_AUTH} must come after {DJANGO_AUTH}.",
48
+ hint="Otherwise AuthenticationMiddleware replaces the certificate's user.",
49
+ id="django_gemini.E001",
50
+ )
51
+ )
52
+ urlconf = getattr(settings, "GEMINI_URLCONF", None)
53
+ if urlconf:
54
+ try:
55
+ import_module(urlconf)
56
+ except ImportError as e:
57
+ errors.append(
58
+ checks.Error(
59
+ f"GEMINI_URLCONF {urlconf!r} can't be imported: {e}",
60
+ id="django_gemini.E002",
61
+ )
62
+ )
63
+ return errors
django_gemini/conf.py ADDED
@@ -0,0 +1,24 @@
1
+ """Settings, with their defaults."""
2
+
3
+ from django.conf import settings
4
+
5
+ DEFAULTS = {
6
+ # URLconf for Gemini requests; None means ROOT_URLCONF, like HTTP.
7
+ "GEMINI_URLCONF": None,
8
+ # Path prefixes that are "not found" (51) over Gemini, e.g. ["/admin/"].
9
+ "GEMINI_HIDDEN_PATHS": [],
10
+ # Convert text/html responses to gemtext for Gemini clients.
11
+ "GEMINI_CONVERT_HTML": True,
12
+ # Where Gemini clients log in (a URL name or path); redirects to
13
+ # settings.LOGIN_URL are sent here instead.
14
+ "GEMINI_LOGIN_URL": "gemini:login",
15
+ # Allow linking a certificate by username and password over Gemini.
16
+ "GEMINI_PASSWORD_LOGIN": True,
17
+ # Wrong passwords allowed per certificate in GEMINI_LOGIN_WINDOW seconds.
18
+ "GEMINI_LOGIN_ATTEMPTS": 5,
19
+ "GEMINI_LOGIN_WINDOW": 15 * 60,
20
+ }
21
+
22
+
23
+ def get(name):
24
+ return getattr(settings, name, DEFAULTS[name])