django-admin-api-mcp 0.1.0a2__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.
Files changed (49) hide show
  1. admin_api/__init__.py +9 -0
  2. admin_api/actions.py +115 -0
  3. admin_api/admin.py +108 -0
  4. admin_api/apps.py +9 -0
  5. admin_api/auth.py +62 -0
  6. admin_api/changelist.py +194 -0
  7. admin_api/checks.py +35 -0
  8. admin_api/contrib/__init__.py +1 -0
  9. admin_api/contrib/subadmin.py +37 -0
  10. admin_api/custom_views.py +458 -0
  11. admin_api/decorators.py +26 -0
  12. admin_api/deletion.py +54 -0
  13. admin_api/detail.py +127 -0
  14. admin_api/encoders.py +59 -0
  15. admin_api/errors.py +44 -0
  16. admin_api/jsonschema.py +216 -0
  17. admin_api/management/__init__.py +0 -0
  18. admin_api/management/commands/__init__.py +0 -0
  19. admin_api/management/commands/create_api_token.py +40 -0
  20. admin_api/management/commands/mcp_serve.py +86 -0
  21. admin_api/mcp/__init__.py +7 -0
  22. admin_api/mcp/bridge.py +71 -0
  23. admin_api/mcp/confirm.py +54 -0
  24. admin_api/mcp/handlers.py +665 -0
  25. admin_api/mcp/server.py +75 -0
  26. admin_api/mcp/sites.py +198 -0
  27. admin_api/mcp/stdio.py +53 -0
  28. admin_api/mcp/tools.py +84 -0
  29. admin_api/mcp/views.py +69 -0
  30. admin_api/middleware.py +18 -0
  31. admin_api/migrations/0001_initial.py +40 -0
  32. admin_api/migrations/__init__.py +0 -0
  33. admin_api/mixins.py +144 -0
  34. admin_api/models.py +113 -0
  35. admin_api/nested.py +122 -0
  36. admin_api/resolver.py +95 -0
  37. admin_api/scopes.py +121 -0
  38. admin_api/services.py +423 -0
  39. admin_api/sites.py +225 -0
  40. admin_api/views/__init__.py +0 -0
  41. admin_api/views/changelist.py +50 -0
  42. admin_api/views/custom.py +31 -0
  43. admin_api/views/detail.py +39 -0
  44. admin_api/views/nested.py +70 -0
  45. admin_api/views/registry.py +15 -0
  46. admin_api/writes.py +479 -0
  47. django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
  48. django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
  49. django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
admin_api/encoders.py ADDED
@@ -0,0 +1,59 @@
1
+ """Python value → JSON-ready value."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import datetime
6
+
7
+ from django.core.serializers.json import DjangoJSONEncoder
8
+ from django.db import models
9
+ from django.db.models.fields.files import FieldFile
10
+ from django.utils import timezone
11
+
12
+ _encoder = DjangoJSONEncoder()
13
+
14
+
15
+ def encode_value(value):
16
+ if value is None or isinstance(value, (bool, int, float, str)):
17
+ return value
18
+ if isinstance(value, models.Model):
19
+ return {"pk": encode_value(value.pk), "str": str(value)}
20
+ if isinstance(value, FieldFile):
21
+ return value.name or None
22
+ if isinstance(value, (list, tuple, set, frozenset)):
23
+ return [encode_value(v) for v in value]
24
+ if isinstance(value, dict):
25
+ return {str(k): encode_value(v) for k, v in value.items()}
26
+ if isinstance(value, datetime.datetime) and timezone.is_aware(value):
27
+ # One representation everywhere (list, detail, after save): the current time zone,
28
+ # like the admin displays it.
29
+ value = timezone.localtime(value)
30
+ try:
31
+ # datetime/date/time (ISO 8601), timedelta, Decimal, UUID, lazy translation strings
32
+ return _encoder.default(value)
33
+ except TypeError:
34
+ return str(value)
35
+
36
+
37
+ _FIELD_TYPES = [
38
+ (models.BooleanField, "boolean"),
39
+ (models.AutoField, "integer"),
40
+ (models.IntegerField, "integer"),
41
+ (models.DecimalField, "decimal"),
42
+ (models.FloatField, "number"),
43
+ (models.DateTimeField, "datetime"), # before DateField (subclass)
44
+ (models.DateField, "date"),
45
+ (models.TimeField, "time"),
46
+ (models.DurationField, "duration"),
47
+ (models.UUIDField, "uuid"),
48
+ (models.FileField, "file"),
49
+ (models.JSONField, "json"),
50
+ (models.ForeignKey, "related"), # covers OneToOneField
51
+ (models.ManyToManyField, "related_many"),
52
+ ]
53
+
54
+
55
+ def field_type(field) -> str:
56
+ for cls, name in _FIELD_TYPES:
57
+ if isinstance(field, cls):
58
+ return name
59
+ return "string"
admin_api/errors.py ADDED
@@ -0,0 +1,44 @@
1
+ from __future__ import annotations
2
+
3
+ from django.http import JsonResponse
4
+
5
+
6
+ class ApiError(Exception):
7
+ status = 400
8
+ code = "bad_request"
9
+
10
+ def __init__(self, detail: str | None = None, *, status: int | None = None, code: str | None = None, **extra):
11
+ super().__init__(detail or self.code)
12
+ self.detail = detail
13
+ if status is not None:
14
+ self.status = status
15
+ if code is not None:
16
+ self.code = code
17
+ self.extra = extra
18
+
19
+ def as_response(self) -> JsonResponse:
20
+ payload = {"error": self.code}
21
+ if self.detail:
22
+ payload["detail"] = self.detail
23
+ payload.update(self.extra)
24
+ return JsonResponse(payload, status=self.status)
25
+
26
+
27
+ class NotAuthenticated(ApiError):
28
+ status = 401
29
+ code = "not_authenticated"
30
+
31
+
32
+ class PermissionDeniedError(ApiError):
33
+ status = 403
34
+ code = "permission_denied"
35
+
36
+
37
+ class NotFound(ApiError):
38
+ status = 404
39
+ code = "not_found"
40
+
41
+
42
+ class MethodNotAllowed(ApiError):
43
+ status = 405
44
+ code = "method_not_allowed"
@@ -0,0 +1,216 @@
1
+ """JSON Schema (draft 2020-12) for write payloads, generated from the admin's own forms.
2
+
3
+ The schema describes what :func:`admin_api.writes.build_post_data` accepts: the fields of
4
+ ``get_form()`` (readonly fields are already excluded by the admin) and, under ``"inlines"``,
5
+ one array of rows per inline formset prefix.
6
+
7
+ Two variants:
8
+
9
+ * ``create``: required = the form's required fields without an initial value (the API fills
10
+ missing fields from the add form's initial values, given as ``default``); inline rows are new.
11
+ * ``update``: PATCH semantics, nothing is required; inline rows may carry ``pk`` (update that
12
+ row) and ``"_delete": true``. Rows without ``pk`` are new rows.
13
+
14
+ Vendor keywords: ``x-related-model`` (``"app_label.model_name"``) on relation fields.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from django import forms
20
+ from django.db import models
21
+ from django.utils.html import strip_tags
22
+ from django.utils.translation import gettext_lazy as _
23
+
24
+ from .detail import inline_prefixes
25
+ from .encoders import encode_value
26
+ from .writes import INLINES_KEY, ROW_DELETE_KEY, form_initial
27
+
28
+ # ModelAdmin.formfield_for_manytomany appends this widget hint to M2M help texts
29
+ _M2M_WIDGET_HINT = _("Hold down “Control”, or “Command” on a Mac, to select more than one.")
30
+
31
+ SCHEMA_DIALECT = "https://json-schema.org/draft/2020-12/schema"
32
+ DECIMAL_PATTERN = r"^-?\d+(\.\d+)?$"
33
+
34
+
35
+ def _nullable(schema: dict) -> dict:
36
+ if "enum" in schema:
37
+ return {**schema, "enum": [*schema["enum"], None]}
38
+ t = schema.get("type")
39
+ if t is None:
40
+ return schema
41
+ types = t if isinstance(t, list) else [t]
42
+ return {**schema, "type": [*types, "null"]} if "null" not in types else schema
43
+
44
+
45
+ def _pk_schema(model, to_field_name=None) -> dict:
46
+ field = model._meta.get_field(to_field_name) if to_field_name else model._meta.pk
47
+ if isinstance(field, (models.AutoField, models.IntegerField)):
48
+ return {"type": "integer"}
49
+ if isinstance(field, models.UUIDField):
50
+ return {"type": "string", "format": "uuid"}
51
+ return {"type": "string"}
52
+
53
+
54
+ def field_schema(form_field) -> dict | None:
55
+ """JSON Schema for one form field, or ``None`` if the JSON API cannot set it (files)."""
56
+ f = form_field
57
+ if isinstance(f, forms.FileField):
58
+ return None
59
+ if isinstance(f, forms.ModelMultipleChoiceField):
60
+ model = f.queryset.model
61
+ schema = {"type": "array", "items": _pk_schema(model, f.to_field_name), "uniqueItems": True}
62
+ schema["x-related-model"] = f"{model._meta.app_label}.{model._meta.model_name}"
63
+ elif isinstance(f, forms.ModelChoiceField):
64
+ model = f.queryset.model
65
+ schema = {**_pk_schema(model, f.to_field_name)}
66
+ schema["x-related-model"] = f"{model._meta.app_label}.{model._meta.model_name}"
67
+ elif isinstance(f, forms.MultipleChoiceField):
68
+ schema = {"type": "array", "items": {"enum": _choice_values(f)}, "uniqueItems": True}
69
+ elif isinstance(f, forms.ChoiceField):
70
+ schema = {"enum": _choice_values(f)}
71
+ elif isinstance(f, forms.NullBooleanField):
72
+ schema = {"type": ["boolean", "null"]}
73
+ elif isinstance(f, forms.BooleanField):
74
+ schema = {"type": "boolean"}
75
+ elif isinstance(f, forms.DecimalField):
76
+ # strings keep precision; plain JSON numbers are accepted too
77
+ schema = {"type": ["string", "number"], "pattern": DECIMAL_PATTERN}
78
+ if f.max_digits is not None and f.decimal_places is not None:
79
+ schema["description"] = f"Decimal: max {f.max_digits} digits, {f.decimal_places} decimal places."
80
+ elif isinstance(f, forms.FloatField):
81
+ schema = {"type": "number"}
82
+ elif isinstance(f, forms.IntegerField):
83
+ schema = {"type": "integer"}
84
+ if f.min_value is not None:
85
+ schema["minimum"] = f.min_value
86
+ if f.max_value is not None:
87
+ schema["maximum"] = f.max_value
88
+ elif isinstance(f, (forms.SplitDateTimeField, forms.DateTimeField)):
89
+ schema = {"type": "string", "format": "date-time"}
90
+ elif isinstance(f, forms.DateField):
91
+ schema = {"type": "string", "format": "date"}
92
+ elif isinstance(f, forms.TimeField):
93
+ schema = {"type": "string", "format": "time"}
94
+ elif isinstance(f, forms.DurationField):
95
+ schema = {"type": "string", "description": "Duration, e.g. '1 02:03:04' or ISO 8601 'P1DT2H'."}
96
+ elif isinstance(f, forms.UUIDField):
97
+ schema = {"type": "string", "format": "uuid"}
98
+ elif isinstance(f, forms.JSONField):
99
+ schema = {}
100
+ elif isinstance(f, forms.EmailField):
101
+ schema = {"type": "string", "format": "email"}
102
+ elif isinstance(f, forms.URLField):
103
+ schema = {"type": "string", "format": "uri"}
104
+ else:
105
+ schema = {"type": "string"}
106
+ if getattr(f, "max_length", None):
107
+ schema["maxLength"] = f.max_length
108
+ if getattr(f, "min_length", None):
109
+ schema["minLength"] = f.min_length
110
+
111
+ if f.label:
112
+ schema["title"] = str(f.label)
113
+ help_text = strip_tags(str(f.help_text or "")).replace(str(_M2M_WIDGET_HINT), "").strip()
114
+ if help_text:
115
+ schema["description"] = f"{schema['description']} {help_text}" if "description" in schema else help_text
116
+ if not f.required and not isinstance(f, (forms.BooleanField, forms.JSONField)) and schema.get("type") != "array":
117
+ schema = _nullable(schema)
118
+ return schema
119
+
120
+
121
+ def _choice_values(f) -> list:
122
+ out = []
123
+ for value, label in f.choices:
124
+ if isinstance(label, (list, tuple)): # optgroup
125
+ out.extend(encode_value(v) for v, _ in label if v != "")
126
+ elif value != "":
127
+ out.append(encode_value(value))
128
+ return out
129
+
130
+
131
+ def _has_value(value) -> bool:
132
+ return value not in (None, "", [], ())
133
+
134
+
135
+ def form_object_schema(form_class, *, required: bool, exclude=()) -> dict:
136
+ """Object schema for a form class. With ``required``, a form-required field is only required
137
+ in the payload when the add form has no initial value for it (the API fills those in)."""
138
+ initial = form_initial(form_class, None) if required else {}
139
+ properties, required_names = {}, []
140
+ for name, f in form_class.base_fields.items():
141
+ if name in exclude:
142
+ continue
143
+ schema = field_schema(f)
144
+ if schema is None:
145
+ continue
146
+ if required and _has_value(initial.get(name)):
147
+ default = encode_value(initial[name])
148
+ if isinstance(default, (str, int, float, bool, list)) or default is None:
149
+ schema["default"] = default
150
+ properties[name] = schema
151
+ if required and f.required and not _has_value(initial.get(name)):
152
+ required_names.append(name)
153
+ out = {"type": "object", "properties": properties, "additionalProperties": False}
154
+ if required_names:
155
+ out["required"] = required_names
156
+ return out
157
+
158
+
159
+ def _inline_schemas(model_admin, request, obj, *, change: bool) -> dict:
160
+ out = {}
161
+ for prefix, FormSet, inline in inline_prefixes(model_admin, request, obj, change):
162
+ fk = getattr(FormSet, "fk", None)
163
+ exclude = {fk.name} if fk is not None else set()
164
+ row = form_object_schema(FormSet.form, required=not change, exclude=exclude)
165
+ opts = FormSet.model._meta
166
+ description = f"Rows of {opts.verbose_name_plural}."
167
+ if change:
168
+ row["properties"] = {
169
+ "pk": {**_pk_schema(FormSet.model), "description": "Existing row to update; omit for a new row."},
170
+ ROW_DELETE_KEY: {"type": "boolean", "description": "Delete the existing row given by pk."},
171
+ **row["properties"],
172
+ }
173
+ initial = form_initial(FormSet.form, None)
174
+ required = [
175
+ n
176
+ for n, f in FormSet.form.base_fields.items()
177
+ if f.required and n not in exclude and not _has_value(initial.get(n))
178
+ ]
179
+ description += " Rows not mentioned are kept unchanged."
180
+ if required:
181
+ description += f" New rows (without pk) need: {', '.join(required)}."
182
+ schema = {"type": "array", "items": row, "description": description}
183
+ if not change and FormSet.max_num is not None:
184
+ schema["maxItems"] = FormSet.max_num
185
+ if not change and FormSet.min_num:
186
+ schema["minItems"] = FormSet.min_num
187
+ schema["x-related-model"] = f"{opts.app_label}.{opts.model_name}"
188
+ out[prefix] = schema
189
+ return out
190
+
191
+
192
+ def payload_schema(model_admin, request, obj=None, *, change: bool) -> dict:
193
+ """Schema of the JSON body for create (``change=False``) or update (``change=True``)."""
194
+ form_class = model_admin.get_form(request, obj, change=change)
195
+ schema = {"$schema": SCHEMA_DIALECT, **form_object_schema(form_class, required=not change)}
196
+ inlines = _inline_schemas(model_admin, request, obj, change=change)
197
+ if inlines:
198
+ schema["properties"][INLINES_KEY] = {
199
+ "type": "object",
200
+ "properties": inlines,
201
+ "additionalProperties": False,
202
+ "description": "Inline rows, keyed by inline prefix.",
203
+ }
204
+ return schema
205
+
206
+
207
+ def input_schemas(model_admin, request, obj=None) -> dict:
208
+ """``{"create": schema | None, "update": schema | None}`` for what ``request.user`` may do."""
209
+ return {
210
+ "create": payload_schema(model_admin, request, None, change=False)
211
+ if obj is None and model_admin.has_add_permission(request)
212
+ else None,
213
+ "update": payload_schema(model_admin, request, obj, change=True)
214
+ if model_admin.has_change_permission(request, obj)
215
+ else None,
216
+ }
File without changes
File without changes
@@ -0,0 +1,40 @@
1
+ import datetime
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.core.exceptions import ValidationError
5
+ from django.core.management.base import BaseCommand, CommandError
6
+ from django.utils import timezone
7
+
8
+ from admin_api.auth import get_token_model
9
+
10
+
11
+ class Command(BaseCommand):
12
+ help = "Create an API token for a user and print it (shown only once)."
13
+
14
+ def add_arguments(self, parser):
15
+ parser.add_argument("username")
16
+ parser.add_argument("--name", default="cli")
17
+ parser.add_argument("--kind", default="pat", choices=["pat", "mcp", "service"])
18
+ parser.add_argument("--expires-days", type=int, default=None)
19
+ parser.add_argument(
20
+ "--scope",
21
+ action="append",
22
+ default=[],
23
+ dest="scopes",
24
+ help="Narrow the token, e.g. --scope store.sales:view --scope 'cash.*:*'. Repeatable.",
25
+ )
26
+
27
+ def handle(self, username, name, kind, expires_days, scopes, **options):
28
+ User = get_user_model()
29
+ try:
30
+ user = User.objects.get(**{User.USERNAME_FIELD: username})
31
+ except User.DoesNotExist as exc:
32
+ raise CommandError(f"No user {username!r}.") from exc
33
+ expires_at = timezone.now() + datetime.timedelta(days=expires_days) if expires_days else None
34
+ try:
35
+ _token, raw = get_token_model().objects.create_token(
36
+ user, name, expires_at=expires_at, kind=kind, scopes=scopes
37
+ )
38
+ except ValidationError as exc:
39
+ raise CommandError("; ".join(exc.messages)) from exc
40
+ self.stdout.write(raw)
@@ -0,0 +1,86 @@
1
+ """Serve an AdminMcpSite over stdio, for local MCP clients (Claude Code, Claude Desktop, ...).
2
+
3
+ claude mcp add erp -e ADMIN_API_TOKEN=aapi_... -- python manage.py mcp_serve
4
+
5
+ Off when ``ADMIN_API_MCP_ENABLED = False``. Logs go to stderr; stdout carries the protocol.
6
+ """
7
+
8
+ import os
9
+ from importlib import import_module
10
+
11
+ from django.conf import settings
12
+ from django.contrib.auth import get_user_model
13
+ from django.core.management.base import BaseCommand, CommandError
14
+ from django.utils.module_loading import import_string
15
+
16
+ TOKEN_ENV = "ADMIN_API_TOKEN"
17
+
18
+
19
+ class Command(BaseCommand):
20
+ help = "Serve the admin as an MCP server over stdio."
21
+ requires_system_checks = [] # checks print to stdout, which belongs to the protocol
22
+
23
+ def add_arguments(self, parser):
24
+ parser.add_argument(
25
+ "--token",
26
+ help=f"API token to act as (default: ${TOKEN_ENV}; the env var keeps it out of the process list).",
27
+ )
28
+ parser.add_argument("--user", help="Act as this user without a token. Only allowed with DEBUG=True.")
29
+ parser.add_argument(
30
+ "--site",
31
+ help="Dotted path to the AdminMcpSite instance. Default: the only one defined in your URLconf.",
32
+ )
33
+
34
+ def handle(self, *args, token=None, user=None, site=None, **options):
35
+ from admin_api.auth import get_token_model
36
+ from admin_api.mcp.sites import mcp_enabled
37
+ from admin_api.mcp.stdio import StdioRequestFactory, serve
38
+
39
+ if not mcp_enabled():
40
+ raise CommandError("MCP is disabled (ADMIN_API_MCP_ENABLED = False).")
41
+ mcp_site = self.get_site(site)
42
+ raw = token or os.environ.get(TOKEN_ENV)
43
+ if raw and user:
44
+ raise CommandError("Use either a token or --user, not both.")
45
+ if raw:
46
+ api_token = get_token_model().objects.get_for_raw(raw)
47
+ if api_token is None or not api_token.user.is_active:
48
+ raise CommandError("Invalid, revoked or expired token.")
49
+ factory = StdioRequestFactory(mcp_site, raw_token=raw)
50
+ who = f"{api_token.user} (token {api_token.prefix})"
51
+ elif user:
52
+ if not settings.DEBUG:
53
+ raise CommandError("--user is only allowed with DEBUG=True. Use an API token.")
54
+ User = get_user_model()
55
+ try:
56
+ account = User.objects.get(**{User.USERNAME_FIELD: user})
57
+ except User.DoesNotExist as exc:
58
+ raise CommandError(f"No user {user!r}.") from exc
59
+ factory = StdioRequestFactory(mcp_site, user=account)
60
+ who = f"{account} (no token, DEBUG)"
61
+ else:
62
+ raise CommandError(f"Give --token, set ${TOKEN_ENV}, or (DEBUG only) --user.")
63
+
64
+ self.stderr.write(f"admin_api MCP server '{mcp_site.server_name}' on stdio as {who}")
65
+ serve(mcp_site, factory)
66
+
67
+ def get_site(self, dotted):
68
+ from admin_api.mcp import AdminMcpSite
69
+ from admin_api.mcp.sites import all_mcp_sites
70
+
71
+ if dotted:
72
+ try:
73
+ site = import_string(dotted)
74
+ except ImportError as exc:
75
+ raise CommandError(f"Cannot import {dotted!r}: {exc}") from exc
76
+ if not isinstance(site, AdminMcpSite):
77
+ raise CommandError(f"{dotted!r} is not an AdminMcpSite.")
78
+ return site
79
+ import_module(settings.ROOT_URLCONF) # sites are usually created in urls.py
80
+ sites = all_mcp_sites()
81
+ if len(sites) == 1:
82
+ return sites[0]
83
+ if not sites:
84
+ raise CommandError("No AdminMcpSite found. Create one (see admin_api.mcp) or pass --site.")
85
+ names = ", ".join(sorted(s.name for s in sites))
86
+ raise CommandError(f"Several AdminMcpSites ({names}); pick one with --site dotted.path.")
@@ -0,0 +1,7 @@
1
+ """MCP for admin_api: the tool layer plus the transports (Streamable HTTP view, ``manage.py mcp_serve``).
2
+ Set ``ADMIN_API_MCP_ENABLED = False`` to turn both transports off."""
3
+
4
+ from .sites import AdminMcpSite
5
+ from .tools import ToolResult, ToolSpec
6
+
7
+ __all__ = ["AdminMcpSite", "ToolResult", "ToolSpec"]
@@ -0,0 +1,71 @@
1
+ """Run the SDK's Streamable HTTP transport inside a (sync) Django view.
2
+
3
+ A fresh stateless ``StreamableHTTPSessionManager`` handles each request with plain JSON
4
+ responses (no SSE, no sessions). The Django request is translated into an ASGI scope; the
5
+ ASGI response is collected into an ``HttpResponse``.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from django.http import HttpResponse
11
+ from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
12
+
13
+ from .server import current_request
14
+
15
+
16
+ def _scope(request, body: bytes) -> dict:
17
+ host = request.get_host()
18
+ name, _, port = host.rpartition(":") if host.rsplit(":", 1)[-1].isdigit() else (host, "", "")
19
+ headers = [
20
+ (key.lower().encode("latin-1"), value.encode("latin-1"))
21
+ for key, value in request.headers.items()
22
+ if key.lower() != "content-length"
23
+ ]
24
+ headers.append((b"content-length", str(len(body)).encode("latin-1")))
25
+ return {
26
+ "type": "http",
27
+ "asgi": {"version": "3.0"},
28
+ "http_version": "1.1",
29
+ "method": request.method,
30
+ "scheme": "https" if request.is_secure() else "http",
31
+ "path": request.path,
32
+ "raw_path": request.path.encode("utf-8"),
33
+ "root_path": "",
34
+ "query_string": request.META.get("QUERY_STRING", "").encode("latin-1"),
35
+ "headers": headers,
36
+ "client": (request.META.get("REMOTE_ADDR") or "", 0),
37
+ "server": (name or host, int(port) if port else (443 if request.is_secure() else 80)),
38
+ }
39
+
40
+
41
+ async def handle(server, request) -> HttpResponse:
42
+ """Serve one Django request with ``server`` (an SDK ``Server``)."""
43
+ current_request.set(request)
44
+ body = request.body
45
+ sent = False
46
+
47
+ async def receive():
48
+ nonlocal sent
49
+ if sent:
50
+ return {"type": "http.disconnect"}
51
+ sent = True
52
+ return {"type": "http.request", "body": body, "more_body": False}
53
+
54
+ status, headers, chunks = 500, [], []
55
+
56
+ async def send(message):
57
+ nonlocal status, headers
58
+ if message["type"] == "http.response.start":
59
+ status, headers = message["status"], message.get("headers", [])
60
+ elif message["type"] == "http.response.body":
61
+ chunks.append(message.get("body", b""))
62
+
63
+ manager = StreamableHTTPSessionManager(app=server, json_response=True, stateless=True)
64
+ async with manager.run():
65
+ await manager.handle_request(_scope(request, body), receive, send)
66
+
67
+ response = HttpResponse(b"".join(chunks), status=status)
68
+ for key, value in headers:
69
+ if key.lower() not in (b"content-length",):
70
+ response[key.decode("latin-1")] = value.decode("latin-1")
71
+ return response
@@ -0,0 +1,54 @@
1
+ """Confirm tokens for ``require_dry_run``: a signed fingerprint of one write, issued by its dry run.
2
+
3
+ Stateless (the HTTP transport keeps no session between calls): the token is a timestamp-signed
4
+ SHA-256 of the user, the operation and its exact arguments. The real write recomputes the
5
+ fingerprint and refuses unless the token matches and is younger than ``max_age`` seconds.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+
13
+ from django.core import signing
14
+ from django.utils.crypto import constant_time_compare
15
+
16
+ from ..errors import ApiError
17
+
18
+
19
+ class DryRunRequired(ApiError):
20
+ status = 409
21
+ code = "dry_run_required"
22
+
23
+
24
+ class InvalidConfirmToken(ApiError):
25
+ status = 409
26
+ code = "invalid_confirm_token"
27
+
28
+
29
+ def fingerprint(request, operation: str, scope: dict) -> str:
30
+ body = json.dumps([request.user.pk, operation, scope], sort_keys=True, default=str)
31
+ return hashlib.sha256(body.encode()).hexdigest()
32
+
33
+
34
+ def issue(salt: str, request, operation: str, scope: dict) -> str:
35
+ return signing.TimestampSigner(salt=salt).sign(fingerprint(request, operation, scope))
36
+
37
+
38
+ def verify(salt: str, max_age: int, token, request, operation: str, scope: dict) -> None:
39
+ if not token:
40
+ raise DryRunRequired(
41
+ "This server requires a dry run first. Call again with dry_run=true, then repeat the call "
42
+ "without dry_run and pass the confirm_token the dry run returned."
43
+ )
44
+ try:
45
+ signed = signing.TimestampSigner(salt=salt).unsign(str(token), max_age=max_age)
46
+ except signing.SignatureExpired:
47
+ raise InvalidConfirmToken("The confirm_token has expired. Repeat the dry run.") from None
48
+ except signing.BadSignature:
49
+ signed = None
50
+ if signed is None or not constant_time_compare(signed, fingerprint(request, operation, scope)):
51
+ raise InvalidConfirmToken(
52
+ "The confirm_token does not belong to this write. Repeat the dry run with exactly the "
53
+ "arguments you are about to save."
54
+ )