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.
- admin_api/__init__.py +9 -0
- admin_api/actions.py +115 -0
- admin_api/admin.py +108 -0
- admin_api/apps.py +9 -0
- admin_api/auth.py +62 -0
- admin_api/changelist.py +194 -0
- admin_api/checks.py +35 -0
- admin_api/contrib/__init__.py +1 -0
- admin_api/contrib/subadmin.py +37 -0
- admin_api/custom_views.py +458 -0
- admin_api/decorators.py +26 -0
- admin_api/deletion.py +54 -0
- admin_api/detail.py +127 -0
- admin_api/encoders.py +59 -0
- admin_api/errors.py +44 -0
- admin_api/jsonschema.py +216 -0
- admin_api/management/__init__.py +0 -0
- admin_api/management/commands/__init__.py +0 -0
- admin_api/management/commands/create_api_token.py +40 -0
- admin_api/management/commands/mcp_serve.py +86 -0
- admin_api/mcp/__init__.py +7 -0
- admin_api/mcp/bridge.py +71 -0
- admin_api/mcp/confirm.py +54 -0
- admin_api/mcp/handlers.py +665 -0
- admin_api/mcp/server.py +75 -0
- admin_api/mcp/sites.py +198 -0
- admin_api/mcp/stdio.py +53 -0
- admin_api/mcp/tools.py +84 -0
- admin_api/mcp/views.py +69 -0
- admin_api/middleware.py +18 -0
- admin_api/migrations/0001_initial.py +40 -0
- admin_api/migrations/__init__.py +0 -0
- admin_api/mixins.py +144 -0
- admin_api/models.py +113 -0
- admin_api/nested.py +122 -0
- admin_api/resolver.py +95 -0
- admin_api/scopes.py +121 -0
- admin_api/services.py +423 -0
- admin_api/sites.py +225 -0
- admin_api/views/__init__.py +0 -0
- admin_api/views/changelist.py +50 -0
- admin_api/views/custom.py +31 -0
- admin_api/views/detail.py +39 -0
- admin_api/views/nested.py +70 -0
- admin_api/views/registry.py +15 -0
- admin_api/writes.py +479 -0
- django_admin_api_mcp-0.1.0a2.dist-info/METADATA +274 -0
- django_admin_api_mcp-0.1.0a2.dist-info/RECORD +49 -0
- django_admin_api_mcp-0.1.0a2.dist-info/WHEEL +4 -0
admin_api/mixins.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
|
|
5
|
+
from . import scopes
|
|
6
|
+
from .resolver import is_resolving, resolve, resolving
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _is_api(request) -> bool:
|
|
10
|
+
return bool(getattr(request, "is_api", False))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
MCP_NOTE = "Via MCP."
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _with_mcp_note(request, message):
|
|
17
|
+
"""``message`` (the change-message list or a string) as text ending in :data:`MCP_NOTE`, for MCP
|
|
18
|
+
requests. Other requests keep Django's structured message."""
|
|
19
|
+
if not getattr(request, "is_mcp", False):
|
|
20
|
+
return message
|
|
21
|
+
from django.contrib.admin.models import LogEntry
|
|
22
|
+
|
|
23
|
+
if isinstance(message, list):
|
|
24
|
+
message = LogEntry(change_message=json.dumps(message)).get_change_message()
|
|
25
|
+
return f"{message or ''} {MCP_NOTE}".strip()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class ApiAdminMixin:
|
|
29
|
+
"""Routes Django's normal ``get_X`` getters to their ``api_`` twin when ``request.is_api``.
|
|
30
|
+
|
|
31
|
+
Because Django's getters call each other (``get_form`` → ``get_fieldsets`` →
|
|
32
|
+
``get_fields``; ``get_readonly_fields`` decides exclusions), routing *inside* the getters
|
|
33
|
+
makes every internal call API-aware.
|
|
34
|
+
|
|
35
|
+
If you override one of these getters on your admin, call ``super()`` to keep the routing.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
api_enabled = True
|
|
39
|
+
|
|
40
|
+
def get_mcp_description(self, request) -> str | None:
|
|
41
|
+
"""Context shown to the LLM for this admin. Override to return another attribute, such as
|
|
42
|
+
the admin's ordinary ``description``; defaults to ``mcp_description`` (str or callable)."""
|
|
43
|
+
description = getattr(self, "mcp_description", None)
|
|
44
|
+
if callable(description):
|
|
45
|
+
description = description(request)
|
|
46
|
+
return str(description) if description else None
|
|
47
|
+
|
|
48
|
+
# --- changelist-level ------------------------------------------------------------------
|
|
49
|
+
def get_list_display(self, request):
|
|
50
|
+
if _is_api(request) and not is_resolving(request, "list_display"):
|
|
51
|
+
return resolve(self, "list_display", request)
|
|
52
|
+
return super().get_list_display(request)
|
|
53
|
+
|
|
54
|
+
def get_list_filter(self, request):
|
|
55
|
+
if _is_api(request) and not is_resolving(request, "list_filter"):
|
|
56
|
+
return resolve(self, "list_filter", request)
|
|
57
|
+
return super().get_list_filter(request)
|
|
58
|
+
|
|
59
|
+
def get_search_fields(self, request):
|
|
60
|
+
if _is_api(request) and not is_resolving(request, "search_fields"):
|
|
61
|
+
return resolve(self, "search_fields", request)
|
|
62
|
+
return super().get_search_fields(request)
|
|
63
|
+
|
|
64
|
+
def get_ordering(self, request):
|
|
65
|
+
if _is_api(request) and not is_resolving(request, "ordering"):
|
|
66
|
+
return resolve(self, "ordering", request)
|
|
67
|
+
return super().get_ordering(request)
|
|
68
|
+
|
|
69
|
+
def get_queryset(self, request):
|
|
70
|
+
if _is_api(request) and not is_resolving(request, "queryset"):
|
|
71
|
+
return resolve(self, "queryset", request)
|
|
72
|
+
return super().get_queryset(request)
|
|
73
|
+
|
|
74
|
+
# --- changeform-level ------------------------------------------------------------------
|
|
75
|
+
def get_fields(self, request, obj=None):
|
|
76
|
+
if _is_api(request) and not is_resolving(request, "fields"):
|
|
77
|
+
return resolve(self, "fields", request, obj)
|
|
78
|
+
return super().get_fields(request, obj)
|
|
79
|
+
|
|
80
|
+
def get_fieldsets(self, request, obj=None):
|
|
81
|
+
if _is_api(request) and not is_resolving(request, "fieldsets"):
|
|
82
|
+
return resolve(self, "fieldsets", request, obj)
|
|
83
|
+
return super().get_fieldsets(request, obj)
|
|
84
|
+
|
|
85
|
+
def get_readonly_fields(self, request, obj=None):
|
|
86
|
+
if _is_api(request) and not is_resolving(request, "readonly_fields"):
|
|
87
|
+
return resolve(self, "readonly_fields", request, obj)
|
|
88
|
+
return super().get_readonly_fields(request, obj)
|
|
89
|
+
|
|
90
|
+
def get_inlines(self, request, obj):
|
|
91
|
+
if _is_api(request) and not is_resolving(request, "inlines"):
|
|
92
|
+
inlines = resolve(self, "inlines", request, obj)
|
|
93
|
+
if scopes.request_scopes(request) is not None:
|
|
94
|
+
# inline formsets check the inline's own has_*_permission: scope those too
|
|
95
|
+
inlines = [scopes.scoped_inline_class(inline) for inline in inlines]
|
|
96
|
+
return inlines
|
|
97
|
+
return super().get_inlines(request, obj)
|
|
98
|
+
|
|
99
|
+
# --- audit trail: MCP writes say so in the LogEntry ----------------------------------------
|
|
100
|
+
def log_addition(self, request, obj, message):
|
|
101
|
+
return super().log_addition(request, obj, _with_mcp_note(request, message))
|
|
102
|
+
|
|
103
|
+
def log_change(self, request, obj, message):
|
|
104
|
+
return super().log_change(request, obj, _with_mcp_note(request, message))
|
|
105
|
+
|
|
106
|
+
# --- permissions: token scopes narrow, never widen ---------------------------------------
|
|
107
|
+
def has_view_permission(self, request, obj=None):
|
|
108
|
+
return super().has_view_permission(request, obj) and scopes.request_allows(request, self.opts, "view")
|
|
109
|
+
|
|
110
|
+
def has_add_permission(self, request):
|
|
111
|
+
return super().has_add_permission(request) and scopes.request_allows(request, self.opts, "add")
|
|
112
|
+
|
|
113
|
+
def has_change_permission(self, request, obj=None):
|
|
114
|
+
return super().has_change_permission(request, obj) and scopes.request_allows(request, self.opts, "change")
|
|
115
|
+
|
|
116
|
+
def has_delete_permission(self, request, obj=None):
|
|
117
|
+
return super().has_delete_permission(request, obj) and scopes.request_allows(request, self.opts, "delete")
|
|
118
|
+
|
|
119
|
+
def get_actions(self, request, action_location=None):
|
|
120
|
+
if _is_api(request) and not is_resolving(request, "actions"):
|
|
121
|
+
method = getattr(self, "get_api_actions", None)
|
|
122
|
+
if method is not None:
|
|
123
|
+
with resolving(request, "actions"):
|
|
124
|
+
return method(request)
|
|
125
|
+
api_actions = getattr(self, "api_actions", None)
|
|
126
|
+
if api_actions is not None:
|
|
127
|
+
base = [a for a in (self.get_action(name) for name in api_actions) if a]
|
|
128
|
+
allowed = self._filter_actions_by_permissions(request, base)
|
|
129
|
+
return {getattr(action, "name", None) or action[1]: action for action in allowed}
|
|
130
|
+
if action_location is None:
|
|
131
|
+
return super().get_actions(request)
|
|
132
|
+
return super().get_actions(request, action_location=action_location)
|
|
133
|
+
|
|
134
|
+
def get_form(self, request, obj=None, change=False, **kwargs):
|
|
135
|
+
if _is_api(request) and not is_resolving(request, "form"):
|
|
136
|
+
method = getattr(self, "get_api_form", None)
|
|
137
|
+
if method is not None:
|
|
138
|
+
with resolving(request, "form"):
|
|
139
|
+
return method(request, obj, change, **kwargs)
|
|
140
|
+
api_form = getattr(self, "api_form", None)
|
|
141
|
+
if api_form is not None and "form" not in kwargs:
|
|
142
|
+
# api_form is a *base* form class, like ModelAdmin.form.
|
|
143
|
+
kwargs["form"] = api_form
|
|
144
|
+
return super().get_form(request, obj, change=change, **kwargs)
|
admin_api/models.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""Personal access tokens. Built small, with room to grow (see docs/DESIGN.md §9).
|
|
2
|
+
|
|
3
|
+
Raw token format: ``aapi_<prefix>_<secret>``. Only ``sha256(secret)`` is stored; the raw
|
|
4
|
+
token is shown once, at creation.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import hmac
|
|
11
|
+
import secrets
|
|
12
|
+
|
|
13
|
+
from django.conf import settings
|
|
14
|
+
from django.db import models
|
|
15
|
+
from django.utils import timezone
|
|
16
|
+
from django.utils.translation import gettext_lazy as _
|
|
17
|
+
|
|
18
|
+
TOKEN_PREFIX = "aapi_"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def hash_secret(secret: str) -> str:
|
|
22
|
+
return hashlib.sha256(secret.encode()).hexdigest()
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class ApiTokenManager(models.Manager):
|
|
26
|
+
def create_token(self, user, name, *, expires_at=None, kind="pat", scopes=None):
|
|
27
|
+
"""Create a token. Returns ``(token, raw)``; ``raw`` is not stored anywhere.
|
|
28
|
+
|
|
29
|
+
``scopes`` (see :mod:`admin_api.scopes`) narrow the user's permissions; ``[]`` = full.
|
|
30
|
+
Raises ``ValidationError`` for an invalid scope.
|
|
31
|
+
"""
|
|
32
|
+
from .scopes import normalize_scopes
|
|
33
|
+
|
|
34
|
+
token = self.model(user=user, name=name, expires_at=expires_at, kind=kind, scopes=normalize_scopes(scopes))
|
|
35
|
+
raw = token.set_new_secret()
|
|
36
|
+
token.save()
|
|
37
|
+
return token, raw
|
|
38
|
+
|
|
39
|
+
def get_for_raw(self, raw: str):
|
|
40
|
+
"""The active token matching ``raw``, or ``None``."""
|
|
41
|
+
if not raw.startswith(TOKEN_PREFIX):
|
|
42
|
+
return None
|
|
43
|
+
prefix, sep, secret = raw[len(TOKEN_PREFIX) :].partition("_")
|
|
44
|
+
if not sep or not prefix or not secret:
|
|
45
|
+
return None
|
|
46
|
+
token = self.select_related("user").filter(prefix=prefix).first()
|
|
47
|
+
if token is None or not hmac.compare_digest(token.key_hash, hash_secret(secret)):
|
|
48
|
+
return None
|
|
49
|
+
return token if token.is_active else None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class AbstractApiToken(models.Model):
|
|
53
|
+
KIND_CHOICES = [("pat", _("Personal access token")), ("mcp", _("MCP client")), ("service", _("Service"))]
|
|
54
|
+
|
|
55
|
+
user = models.ForeignKey(
|
|
56
|
+
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="api_tokens", verbose_name=_("user")
|
|
57
|
+
)
|
|
58
|
+
name = models.CharField(_("name"), max_length=100, help_text=_("What is this token for?"))
|
|
59
|
+
prefix = models.CharField(_("prefix"), max_length=16, unique=True, editable=False)
|
|
60
|
+
key_hash = models.CharField(max_length=64, editable=False)
|
|
61
|
+
created = models.DateTimeField(_("created"), auto_now_add=True)
|
|
62
|
+
expires_at = models.DateTimeField(_("expires at"), null=True, blank=True)
|
|
63
|
+
last_used_at = models.DateTimeField(_("last used at"), null=True, blank=True, editable=False)
|
|
64
|
+
revoked_at = models.DateTimeField(_("revoked at"), null=True, blank=True, editable=False)
|
|
65
|
+
# scopes = [] means "the user's full admin permissions". Scopes only narrow; see admin_api.scopes.
|
|
66
|
+
# Edited through ApiTokenAdmin's form field (editable=False keeps the original migration).
|
|
67
|
+
scopes = models.JSONField(default=list, blank=True, editable=False)
|
|
68
|
+
kind = models.CharField(_("kind"), max_length=20, choices=KIND_CHOICES, default="pat")
|
|
69
|
+
|
|
70
|
+
objects = ApiTokenManager()
|
|
71
|
+
|
|
72
|
+
class Meta:
|
|
73
|
+
abstract = True
|
|
74
|
+
ordering = ["-created"]
|
|
75
|
+
verbose_name = _("API token")
|
|
76
|
+
verbose_name_plural = _("API tokens")
|
|
77
|
+
|
|
78
|
+
def __str__(self):
|
|
79
|
+
return f"{self.name} ({TOKEN_PREFIX}{self.prefix}_…)"
|
|
80
|
+
|
|
81
|
+
def set_new_secret(self) -> str:
|
|
82
|
+
prefix = secrets.token_hex(4)
|
|
83
|
+
while type(self).objects.filter(prefix=prefix).exists():
|
|
84
|
+
prefix = secrets.token_hex(4)
|
|
85
|
+
secret = secrets.token_urlsafe(32)
|
|
86
|
+
self.prefix = prefix
|
|
87
|
+
self.key_hash = hash_secret(secret)
|
|
88
|
+
return f"{TOKEN_PREFIX}{prefix}_{secret}"
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def is_expired(self) -> bool:
|
|
92
|
+
return self.expires_at is not None and self.expires_at <= timezone.now()
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def is_active(self) -> bool:
|
|
96
|
+
return self.revoked_at is None and not self.is_expired
|
|
97
|
+
|
|
98
|
+
def revoke(self):
|
|
99
|
+
if self.revoked_at is None:
|
|
100
|
+
self.revoked_at = timezone.now()
|
|
101
|
+
self.save(update_fields=["revoked_at"])
|
|
102
|
+
|
|
103
|
+
def touch(self, min_interval_seconds: int = 60):
|
|
104
|
+
"""Record usage, at most once per ``min_interval_seconds``."""
|
|
105
|
+
now = timezone.now()
|
|
106
|
+
if self.last_used_at is None or (now - self.last_used_at).total_seconds() >= min_interval_seconds:
|
|
107
|
+
type(self).objects.filter(pk=self.pk).update(last_used_at=now)
|
|
108
|
+
self.last_used_at = now
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class ApiToken(AbstractApiToken):
|
|
112
|
+
class Meta(AbstractApiToken.Meta):
|
|
113
|
+
swappable = "ADMIN_API_TOKEN_MODEL"
|
admin_api/nested.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Nested admins: ModelAdmins mounted inside a parent object (e.g. django-subadmin).
|
|
2
|
+
|
|
3
|
+
A nested admin is addressed by a **model path** plus the **parents** (one pk per level):
|
|
4
|
+
|
|
5
|
+
========= ===================================================================
|
|
6
|
+
HTML ``/admin/store/client/1/sales/7/salesitem/``
|
|
7
|
+
REST ``/api/v1/store/client/1/sales/7/salesitem/``
|
|
8
|
+
MCP ``model="store.client/sales/salesitem"``, ``parents=[1, 7]``
|
|
9
|
+
========= ===================================================================
|
|
10
|
+
|
|
11
|
+
The REST path minus the pks is the model path; the pks in order are the parents. Each child
|
|
12
|
+
segment is the child's ``model_name``.
|
|
13
|
+
|
|
14
|
+
The core is generic. Libraries plug in through a :class:`NestedAdapter` listed in
|
|
15
|
+
``AdminApiSite.nested_adapters``; the django-subadmin adapter lives in
|
|
16
|
+
:mod:`admin_api.contrib.subadmin` and is enabled by default (duck-typed, no import).
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from dataclasses import dataclass, field
|
|
22
|
+
|
|
23
|
+
from .errors import ApiError
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class BadModelPath(ApiError):
|
|
27
|
+
status = 400
|
|
28
|
+
code = "bad_model"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class BadParents(ApiError):
|
|
32
|
+
status = 400
|
|
33
|
+
code = "bad_parents"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class ModelPath:
|
|
38
|
+
"""``app_label.model_name`` of a registered admin, then one segment per nesting level."""
|
|
39
|
+
|
|
40
|
+
app_label: str
|
|
41
|
+
model_name: str
|
|
42
|
+
segments: tuple[str, ...] = ()
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def parse(cls, label: str) -> ModelPath:
|
|
46
|
+
"""``"store.client/sales/salesitem"`` → ``ModelPath("store", "client", ("sales", "salesitem"))``."""
|
|
47
|
+
root, *segments = (label or "").strip().lower().split("/")
|
|
48
|
+
app_label, sep, model_name = root.partition(".")
|
|
49
|
+
if not sep or not app_label or not model_name or not all(segments):
|
|
50
|
+
raise BadModelPath(
|
|
51
|
+
f"Expected 'app_label.model_name' (or a nested path like 'app.parent/child'), got {label!r}."
|
|
52
|
+
)
|
|
53
|
+
return cls(app_label, model_name, tuple(segments))
|
|
54
|
+
|
|
55
|
+
@property
|
|
56
|
+
def root_label(self) -> str:
|
|
57
|
+
return f"{self.app_label}.{self.model_name}"
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def label(self) -> str:
|
|
61
|
+
return "/".join((self.root_label, *self.segments))
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def depth(self) -> int:
|
|
65
|
+
return len(self.segments)
|
|
66
|
+
|
|
67
|
+
def child(self, segment: str) -> ModelPath:
|
|
68
|
+
return ModelPath(self.app_label, self.model_name, (*self.segments, segment))
|
|
69
|
+
|
|
70
|
+
def url(self, base: str, parents=(), *, quote=None) -> str:
|
|
71
|
+
"""REST url of the changelist, under ``base`` (e.g. ``/api/v1/``)."""
|
|
72
|
+
if quote is None:
|
|
73
|
+
from django.contrib.admin.utils import quote
|
|
74
|
+
url = f"{base}{self.app_label}/{self.model_name}/"
|
|
75
|
+
for pk, segment in zip(parents, self.segments):
|
|
76
|
+
url += f"{quote(str(pk))}/{segment}/"
|
|
77
|
+
return url
|
|
78
|
+
|
|
79
|
+
def url_template(self, base: str) -> str:
|
|
80
|
+
"""Like :meth:`url` with ``{0}``, ``{1}``… in place of the parent pks."""
|
|
81
|
+
return self.url(base, [f"{{{i}}}" for i in range(self.depth)], quote=str)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@dataclass
|
|
85
|
+
class Target:
|
|
86
|
+
"""What the current API call operates on. Set on ``request.admin_api_target`` by
|
|
87
|
+
:func:`admin_api.services.get_model_admin`."""
|
|
88
|
+
|
|
89
|
+
api_site: object
|
|
90
|
+
path: ModelPath
|
|
91
|
+
parents: list = field(default_factory=list)
|
|
92
|
+
chain: list = field(default_factory=list) # API admins, root first
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class NestedAdapter:
|
|
96
|
+
"""How admin_api discovers and prepares the nested admins of one library.
|
|
97
|
+
|
|
98
|
+
Subclass and add to ``AdminApiSite.nested_adapters``. All methods receive API admins
|
|
99
|
+
(``ApiAdminMixin`` in the MRO) except :meth:`init_args`, which receives the raw child.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def get_children(self, model_admin) -> list:
|
|
103
|
+
"""The (raw) child admins mounted on ``model_admin``. ``[]`` when none or not handled."""
|
|
104
|
+
return []
|
|
105
|
+
|
|
106
|
+
def is_child(self, model_admin) -> bool:
|
|
107
|
+
"""Is ``model_admin`` a nested admin handled by this adapter?"""
|
|
108
|
+
return False
|
|
109
|
+
|
|
110
|
+
def segment(self, child) -> str:
|
|
111
|
+
"""The path segment of ``child`` under its parent."""
|
|
112
|
+
return child.model._meta.model_name
|
|
113
|
+
|
|
114
|
+
def init_args(self, child) -> tuple:
|
|
115
|
+
"""Constructor arguments to build an API twin of ``child``: ``type(child)(*init_args)``."""
|
|
116
|
+
raise NotImplementedError
|
|
117
|
+
|
|
118
|
+
def prepare_request(self, model_admin, request, parents: list) -> None:
|
|
119
|
+
"""Make ``request`` usable by the nested ``model_admin`` for the given parent pks
|
|
120
|
+
(load and check every ancestor). Raise :class:`ApiError` (``NotFound``,
|
|
121
|
+
``PermissionDeniedError``) on failure."""
|
|
122
|
+
raise NotImplementedError
|
admin_api/resolver.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Twin resolution: ``get_api_X(request) → api_X → get_X(request) → X``.
|
|
2
|
+
|
|
3
|
+
Two entry points:
|
|
4
|
+
|
|
5
|
+
* :func:`resolve` implements the lookup order. It is used by ``ApiAdminMixin``'s routed
|
|
6
|
+
getters and, for admins without the mixin, by the API views.
|
|
7
|
+
* :func:`api_value` is what API views call. For mixin admins it goes through the normal
|
|
8
|
+
getter (``admin.get_X``) so that user overrides above the mixin in the MRO are honoured;
|
|
9
|
+
the mixin then routes to the twin. For plain admins it calls :func:`resolve` directly.
|
|
10
|
+
|
|
11
|
+
Re-entrancy: a ``get_api_queryset`` that calls ``super().get_queryset(request)`` must get the
|
|
12
|
+
*normal* queryset, not recurse back into itself. While a twin method runs, its name is held in
|
|
13
|
+
a per-request stack and routed getters fall through to the normal implementation.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from contextlib import contextmanager
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
# Hooks that ApiAdminMixin routes inside the normal Django getter (get_<name>).
|
|
22
|
+
ROUTED = frozenset(
|
|
23
|
+
{
|
|
24
|
+
"list_display",
|
|
25
|
+
"list_filter",
|
|
26
|
+
"search_fields",
|
|
27
|
+
"ordering",
|
|
28
|
+
"fields",
|
|
29
|
+
"fieldsets",
|
|
30
|
+
"readonly_fields",
|
|
31
|
+
"inlines",
|
|
32
|
+
"queryset",
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
_STACK_ATTR = "_admin_api_resolving"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _stack(request) -> set:
|
|
40
|
+
stack = getattr(request, _STACK_ATTR, None)
|
|
41
|
+
if stack is None:
|
|
42
|
+
stack = set()
|
|
43
|
+
setattr(request, _STACK_ATTR, stack)
|
|
44
|
+
return stack
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_resolving(request, name: str) -> bool:
|
|
48
|
+
return name in getattr(request, _STACK_ATTR, ())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@contextmanager
|
|
52
|
+
def resolving(request, name: str):
|
|
53
|
+
stack = _stack(request)
|
|
54
|
+
stack.add(name)
|
|
55
|
+
try:
|
|
56
|
+
yield
|
|
57
|
+
finally:
|
|
58
|
+
stack.discard(name)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _normal(model_admin, name: str, request, *args, **kwargs) -> Any:
|
|
62
|
+
"""The non-API value: ``get_X(request, ...)`` if it exists, else attribute ``X``."""
|
|
63
|
+
from .mixins import ApiAdminMixin
|
|
64
|
+
|
|
65
|
+
getter_name = f"get_{name}"
|
|
66
|
+
if isinstance(model_admin, ApiAdminMixin):
|
|
67
|
+
# Skip the mixin's routing layer; we are already past any user override above it.
|
|
68
|
+
getter = getattr(super(ApiAdminMixin, model_admin), getter_name, None)
|
|
69
|
+
else:
|
|
70
|
+
getter = getattr(model_admin, getter_name, None)
|
|
71
|
+
if getter is not None:
|
|
72
|
+
return getter(request, *args, **kwargs)
|
|
73
|
+
return getattr(model_admin, name, None)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def resolve(model_admin, name: str, request, *args, **kwargs) -> Any:
|
|
77
|
+
"""Return the API value of hook ``name`` following the twin lookup order."""
|
|
78
|
+
if not is_resolving(request, name):
|
|
79
|
+
method = getattr(model_admin, f"get_api_{name}", None)
|
|
80
|
+
if method is not None:
|
|
81
|
+
with resolving(request, name):
|
|
82
|
+
return method(request, *args, **kwargs)
|
|
83
|
+
value = getattr(model_admin, f"api_{name}", None)
|
|
84
|
+
if value is not None:
|
|
85
|
+
return value
|
|
86
|
+
return _normal(model_admin, name, request, *args, **kwargs)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def api_value(model_admin, name: str, request, *args, **kwargs) -> Any:
|
|
90
|
+
"""Entry point for API views."""
|
|
91
|
+
from .mixins import ApiAdminMixin
|
|
92
|
+
|
|
93
|
+
if isinstance(model_admin, ApiAdminMixin) and name in ROUTED:
|
|
94
|
+
return getattr(model_admin, f"get_{name}")(request, *args, **kwargs)
|
|
95
|
+
return resolve(model_admin, name, request, *args, **kwargs)
|
admin_api/scopes.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Token scopes: narrow what an API token may do below its user's admin permissions.
|
|
2
|
+
|
|
3
|
+
A scope is ``"<app_label>.<model_name>:<op>"`` with ``op`` one of ``view``, ``add``,
|
|
4
|
+
``change``, ``delete``; any part may be ``*``. Examples: ``store.sales:view``,
|
|
5
|
+
``store.*:view``, ``cash.*:*``, ``*.*:view``.
|
|
6
|
+
|
|
7
|
+
* A token with ``scopes == []`` has its user's full permissions (unchanged behaviour).
|
|
8
|
+
* Scopes only *narrow*: ``has_*_permission`` stays the ceiling, a scope never grants anything.
|
|
9
|
+
* As in Django, ``change`` implies ``view``.
|
|
10
|
+
|
|
11
|
+
Enforcement is in :class:`admin_api.mixins.ApiAdminMixin` (``has_*_permission``, and scoped
|
|
12
|
+
inline classes so formset permissions follow too) and, as a second line, in
|
|
13
|
+
:mod:`admin_api.services`.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import re
|
|
19
|
+
|
|
20
|
+
from django.core.exceptions import ValidationError
|
|
21
|
+
|
|
22
|
+
OPS = ("view", "add", "change", "delete")
|
|
23
|
+
_SCOPE_RE = re.compile(r"^(\*|[a-z_][a-z0-9_]*)\.(\*|[a-z_][a-z0-9_]*):(\*|view|add|change|delete)$")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parse_scope(scope: str) -> tuple[str, str, str]:
|
|
27
|
+
match = _SCOPE_RE.match((scope or "").strip().lower())
|
|
28
|
+
if not match:
|
|
29
|
+
raise ValidationError(
|
|
30
|
+
"Invalid scope %(scope)r. Expected '<app_label>.<model_name>:<view|add|change|delete>', "
|
|
31
|
+
"'*' allowed in any part.",
|
|
32
|
+
params={"scope": scope},
|
|
33
|
+
code="invalid_scope",
|
|
34
|
+
)
|
|
35
|
+
return match.group(1), match.group(2), match.group(3)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def normalize_scopes(scopes) -> list[str]:
|
|
39
|
+
"""Validate and normalize (lower-case, stripped, de-duplicated, order kept)."""
|
|
40
|
+
if scopes is None:
|
|
41
|
+
return []
|
|
42
|
+
if isinstance(scopes, str):
|
|
43
|
+
scopes = scopes.replace(",", "\n").splitlines()
|
|
44
|
+
out: list[str] = []
|
|
45
|
+
for scope in scopes:
|
|
46
|
+
if not str(scope).strip():
|
|
47
|
+
continue
|
|
48
|
+
app, model, op = parse_scope(str(scope))
|
|
49
|
+
normalized = f"{app}.{model}:{op}"
|
|
50
|
+
if normalized not in out:
|
|
51
|
+
out.append(normalized)
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def scopes_allow(scopes, app_label: str, model_name: str, op: str) -> bool:
|
|
56
|
+
if not scopes:
|
|
57
|
+
return True
|
|
58
|
+
wanted = {op, "change"} if op == "view" else {op}
|
|
59
|
+
for scope in scopes:
|
|
60
|
+
try:
|
|
61
|
+
s_app, s_model, s_op = parse_scope(scope)
|
|
62
|
+
except ValidationError:
|
|
63
|
+
continue # an invalid stored scope grants nothing
|
|
64
|
+
if s_app not in ("*", app_label) or s_model not in ("*", model_name):
|
|
65
|
+
continue
|
|
66
|
+
if s_op == "*" or s_op in wanted:
|
|
67
|
+
return True
|
|
68
|
+
return False
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def request_scopes(request):
|
|
72
|
+
"""The scopes restricting ``request``, or ``None`` when unrestricted."""
|
|
73
|
+
token = getattr(request, "api_token", None)
|
|
74
|
+
scopes = getattr(token, "scopes", None) if token is not None else None
|
|
75
|
+
return scopes or None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def request_allows(request, opts, op: str) -> bool:
|
|
79
|
+
"""Do the request's token scopes allow ``op`` on the model with ``_meta`` ``opts``?"""
|
|
80
|
+
scopes = request_scopes(request) if request is not None else None
|
|
81
|
+
if scopes is None:
|
|
82
|
+
return True
|
|
83
|
+
return scopes_allow(scopes, opts.app_label, opts.model_name, op)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def check(request, opts, op: str):
|
|
87
|
+
from .errors import PermissionDeniedError
|
|
88
|
+
|
|
89
|
+
if not request_allows(request, opts, op):
|
|
90
|
+
raise PermissionDeniedError(f"Token scopes do not allow '{op}' on {opts.app_label}.{opts.model_name}.")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class ScopedInlineMixin:
|
|
94
|
+
"""Mixed into inline classes for scoped requests (see ``ApiAdminMixin.get_inlines``)."""
|
|
95
|
+
|
|
96
|
+
def _scope_opts(self):
|
|
97
|
+
# auto-created M2M "through" inlines are governed by the parent model, as in Django
|
|
98
|
+
return self.parent_model._meta if self.opts.auto_created else self.opts
|
|
99
|
+
|
|
100
|
+
def has_view_permission(self, request, obj=None):
|
|
101
|
+
return super().has_view_permission(request, obj) and request_allows(request, self._scope_opts(), "view")
|
|
102
|
+
|
|
103
|
+
def has_add_permission(self, request, obj=None):
|
|
104
|
+
return super().has_add_permission(request, obj) and request_allows(request, self._scope_opts(), "add")
|
|
105
|
+
|
|
106
|
+
def has_change_permission(self, request, obj=None):
|
|
107
|
+
return super().has_change_permission(request, obj) and request_allows(request, self._scope_opts(), "change")
|
|
108
|
+
|
|
109
|
+
def has_delete_permission(self, request, obj=None):
|
|
110
|
+
return super().has_delete_permission(request, obj) and request_allows(request, self._scope_opts(), "delete")
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_scoped_inline_classes: dict = {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def scoped_inline_class(inline_class):
|
|
117
|
+
cls = _scoped_inline_classes.get(inline_class)
|
|
118
|
+
if cls is None:
|
|
119
|
+
cls = type(f"Scoped{inline_class.__name__}", (ScopedInlineMixin, inline_class), {"__module__": __name__})
|
|
120
|
+
_scoped_inline_classes[inline_class] = cls
|
|
121
|
+
return cls
|