tortoise-orm-studio 1.0.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.
- tortoise_orm_studio/__init__.py +11 -0
- tortoise_orm_studio/adapters/__init__.py +1 -0
- tortoise_orm_studio/adapters/aiohttp_adapter.py +31 -0
- tortoise_orm_studio/adapters/asgi.py +89 -0
- tortoise_orm_studio/adapters/base.py +25 -0
- tortoise_orm_studio/adapters/django_adapter.py +84 -0
- tortoise_orm_studio/adapters/quart_adapter.py +32 -0
- tortoise_orm_studio/adapters/registry.py +39 -0
- tortoise_orm_studio/adapters/sanic_adapter.py +39 -0
- tortoise_orm_studio/auth.py +34 -0
- tortoise_orm_studio/cli.py +41 -0
- tortoise_orm_studio/core/__init__.py +1 -0
- tortoise_orm_studio/core/aerich.py +86 -0
- tortoise_orm_studio/core/ai.py +87 -0
- tortoise_orm_studio/core/audit.py +69 -0
- tortoise_orm_studio/core/config.py +58 -0
- tortoise_orm_studio/core/filters.py +94 -0
- tortoise_orm_studio/core/handler.py +249 -0
- tortoise_orm_studio/core/http.py +55 -0
- tortoise_orm_studio/core/i18n.py +18 -0
- tortoise_orm_studio/core/introspect.py +197 -0
- tortoise_orm_studio/core/manifest.py +128 -0
- tortoise_orm_studio/core/pagination.py +59 -0
- tortoise_orm_studio/core/permissions.py +46 -0
- tortoise_orm_studio/core/plugins.py +214 -0
- tortoise_orm_studio/core/ratelimit.py +32 -0
- tortoise_orm_studio/core/scoping.py +23 -0
- tortoise_orm_studio/core/serializers.py +61 -0
- tortoise_orm_studio/core/service.py +594 -0
- tortoise_orm_studio/plugins.py +8 -0
- tortoise_orm_studio/static/ALPINE_LICENSE.txt +11 -0
- tortoise_orm_studio/static/_types.d.ts +706 -0
- tortoise_orm_studio/static/a11y.js +115 -0
- tortoise_orm_studio/static/ai.js +66 -0
- tortoise_orm_studio/static/alpine.min.js +23 -0
- tortoise_orm_studio/static/app.css +514 -0
- tortoise_orm_studio/static/app.js +1443 -0
- tortoise_orm_studio/static/audit.js +171 -0
- tortoise_orm_studio/static/copy-as.js +118 -0
- tortoise_orm_studio/static/er-layout.js +227 -0
- tortoise_orm_studio/static/er.js +296 -0
- tortoise_orm_studio/static/filters.js +114 -0
- tortoise_orm_studio/static/i18n.en.js +190 -0
- tortoise_orm_studio/static/i18n.js +140 -0
- tortoise_orm_studio/static/i18n.zh-CN.js +189 -0
- tortoise_orm_studio/static/index.html +515 -0
- tortoise_orm_studio/static/inline-edit.js +107 -0
- tortoise_orm_studio/static/json-view.js +161 -0
- tortoise_orm_studio/static/migrations.js +139 -0
- tortoise_orm_studio/static/palette.js +141 -0
- tortoise_orm_studio/static/pending.js +240 -0
- tortoise_orm_studio/static/pickers.js +230 -0
- tortoise_orm_studio/static/playground.js +105 -0
- tortoise_orm_studio/static/query-history.js +84 -0
- tortoise_orm_studio/static/shortcuts.js +145 -0
- tortoise_orm_studio/static/state-hash.js +112 -0
- tortoise_orm_studio/static/tabs.js +368 -0
- tortoise_orm_studio/static/theme-init.js +33 -0
- tortoise_orm_studio/static/theme.js +106 -0
- tortoise_orm_studio/static/toasts.js +76 -0
- tortoise_orm_studio/static/views.js +70 -0
- tortoise_orm_studio/static/widgets.js +345 -0
- tortoise_orm_studio/studio.py +51 -0
- tortoise_orm_studio-1.0.0.dist-info/METADATA +177 -0
- tortoise_orm_studio-1.0.0.dist-info/RECORD +68 -0
- tortoise_orm_studio-1.0.0.dist-info/WHEEL +4 -0
- tortoise_orm_studio-1.0.0.dist-info/entry_points.txt +2 -0
- tortoise_orm_studio-1.0.0.dist-info/licenses/LICENSE +13 -0
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
"""Reads Tortoise model metadata and turns it into plain dicts the API can serve."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Any, Dict, List
|
|
5
|
+
|
|
6
|
+
from tortoise import Tortoise, fields
|
|
7
|
+
|
|
8
|
+
_KINDS = [
|
|
9
|
+
(fields.BooleanField, "bool"),
|
|
10
|
+
(fields.IntField, "int"), (fields.BigIntField, "int"), (fields.SmallIntField, "int"),
|
|
11
|
+
(fields.FloatField, "float"), (fields.DecimalField, "decimal"),
|
|
12
|
+
(fields.UUIDField, "uuid"), (fields.DatetimeField, "datetime"),
|
|
13
|
+
(fields.DateField, "date"), (fields.TimeField, "time"),
|
|
14
|
+
(fields.JSONField, "json"), (fields.BinaryField, "binary"),
|
|
15
|
+
(fields.TextField, "text"), (fields.CharField, "string"),
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def field_kind(f: Any) -> str:
|
|
20
|
+
if getattr(f, "enum_type", None) is not None:
|
|
21
|
+
return "enum"
|
|
22
|
+
for cls, kind in _KINDS:
|
|
23
|
+
if isinstance(f, cls):
|
|
24
|
+
return kind
|
|
25
|
+
return "string"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def model_key(model: type) -> str:
|
|
29
|
+
return f"{model._meta.app}.{model.__name__}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def all_models() -> Dict[str, type]:
|
|
33
|
+
return {f"{app}.{name}": m for app, models in Tortoise.apps.items() for name, m in models.items()}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def enum_type(model: type, name: str) -> Any:
|
|
37
|
+
return getattr(model._meta.fields_map[name], "enum_type", None)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _pick_display_field(related: type, related_pk_name: str) -> str:
|
|
41
|
+
"""Best human-readable scalar on the related model, or the pk as a fallback."""
|
|
42
|
+
meta = related._meta
|
|
43
|
+
skip = (meta.fk_fields | meta.o2o_fields | meta.m2m_fields
|
|
44
|
+
| meta.backward_fk_fields | meta.backward_o2o_fields)
|
|
45
|
+
for fname, rf in meta.fields_map.items():
|
|
46
|
+
if fname in skip or fname == related_pk_name:
|
|
47
|
+
continue
|
|
48
|
+
if field_kind(rf) == "string":
|
|
49
|
+
return fname
|
|
50
|
+
return related_pk_name
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _filter_paths(model: type, data: List[Dict[str, Any]], rels: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
|
|
54
|
+
"""Direct fields plus one-level traversal through forward FK/O2O."""
|
|
55
|
+
paths: Dict[str, Dict[str, Any]] = {}
|
|
56
|
+
for f in data:
|
|
57
|
+
paths[f["name"]] = {"kind": f["kind"], "traversal": False}
|
|
58
|
+
|
|
59
|
+
am = all_models()
|
|
60
|
+
for r in rels:
|
|
61
|
+
if r["type"] not in ("fk", "o2o"):
|
|
62
|
+
continue
|
|
63
|
+
rel_model = am.get(r["model"])
|
|
64
|
+
if rel_model is None:
|
|
65
|
+
continue
|
|
66
|
+
rel_meta = rel_model._meta
|
|
67
|
+
rel_skip = (rel_meta.fk_fields | rel_meta.o2o_fields | rel_meta.m2m_fields
|
|
68
|
+
| rel_meta.backward_fk_fields | rel_meta.backward_o2o_fields)
|
|
69
|
+
for rname, rf in rel_meta.fields_map.items():
|
|
70
|
+
if rname in rel_skip:
|
|
71
|
+
continue
|
|
72
|
+
paths[f"{r['name']}.{rname}"] = {
|
|
73
|
+
"kind": field_kind(rf),
|
|
74
|
+
"traversal": True,
|
|
75
|
+
"via": r["name"],
|
|
76
|
+
}
|
|
77
|
+
return paths
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def describe(model: type, config: Any) -> Dict[str, Any]:
|
|
81
|
+
meta, cfg = model._meta, config.cfg_for(model)
|
|
82
|
+
hidden = set(cfg.exclude)
|
|
83
|
+
data: List[Dict[str, Any]] = []
|
|
84
|
+
rels: List[Dict[str, Any]] = []
|
|
85
|
+
|
|
86
|
+
for name, f in meta.fields_map.items():
|
|
87
|
+
if name in hidden:
|
|
88
|
+
continue
|
|
89
|
+
|
|
90
|
+
if name in meta.fk_fields or name in meta.o2o_fields:
|
|
91
|
+
kind = "fk" if name in meta.fk_fields else "o2o"
|
|
92
|
+
related = f.related_model
|
|
93
|
+
# A FK may point at a non-pk unique field via `to_field`. Resolve
|
|
94
|
+
# that field (not always the pk) so coercion, validation and the
|
|
95
|
+
# related route all use the same target column.
|
|
96
|
+
related_pk_name = getattr(f, "to_field", None) or related._meta.pk_attr
|
|
97
|
+
pk_kind = field_kind(related._meta.fields_map[related_pk_name])
|
|
98
|
+
column = getattr(f, "source_field", None) or f"{name}_id"
|
|
99
|
+
display = _pick_display_field(related, related_pk_name)
|
|
100
|
+
|
|
101
|
+
rels.append({
|
|
102
|
+
"name": name, "type": kind,
|
|
103
|
+
"model": model_key(related),
|
|
104
|
+
"nullable": bool(f.null),
|
|
105
|
+
"column": column,
|
|
106
|
+
"via": None,
|
|
107
|
+
"related_pk": related_pk_name,
|
|
108
|
+
"pk_kind": pk_kind,
|
|
109
|
+
})
|
|
110
|
+
data.append({
|
|
111
|
+
"name": name, "kind": kind, "pk": False,
|
|
112
|
+
"null": bool(f.null), "generated": False,
|
|
113
|
+
"readonly": name in cfg.readonly_fields,
|
|
114
|
+
"max_length": None,
|
|
115
|
+
"related_model": model_key(related),
|
|
116
|
+
"related_pk": related_pk_name,
|
|
117
|
+
"column": column,
|
|
118
|
+
"pk_kind": pk_kind,
|
|
119
|
+
"display_field": display,
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
elif name in meta.m2m_fields:
|
|
123
|
+
rels.append({
|
|
124
|
+
"name": name, "type": "m2m",
|
|
125
|
+
"model": model_key(f.related_model),
|
|
126
|
+
"nullable": True, "column": None, "via": None,
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
elif name in meta.backward_fk_fields or name in meta.backward_o2o_fields:
|
|
130
|
+
kind = "backward_fk" if name in meta.backward_fk_fields else "backward_o2o"
|
|
131
|
+
rels.append({
|
|
132
|
+
"name": name, "type": kind,
|
|
133
|
+
"model": model_key(f.related_model),
|
|
134
|
+
"nullable": True, "column": None,
|
|
135
|
+
"via": f.relation_field,
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
else:
|
|
139
|
+
kind = field_kind(f)
|
|
140
|
+
d: Dict[str, Any] = {
|
|
141
|
+
"name": name, "kind": kind,
|
|
142
|
+
"pk": name == meta.pk_attr, "null": bool(f.null),
|
|
143
|
+
"generated": bool(f.generated),
|
|
144
|
+
"readonly": bool(f.generated or getattr(f, "auto_now", False)
|
|
145
|
+
or getattr(f, "auto_now_add", False)
|
|
146
|
+
or name in cfg.readonly_fields),
|
|
147
|
+
"max_length": getattr(f, "max_length", None),
|
|
148
|
+
}
|
|
149
|
+
if kind == "enum":
|
|
150
|
+
d["choices"] = [e.value for e in f.enum_type]
|
|
151
|
+
data.append(d)
|
|
152
|
+
|
|
153
|
+
names = [d["name"] for d in data]
|
|
154
|
+
default_cols = [d["name"] for d in data if d["kind"] not in ("json", "binary", "text")][:8]
|
|
155
|
+
shown = [n for n in (cfg.list_display or default_cols) if n in names]
|
|
156
|
+
searchable = cfg.search_fields if cfg.search_fields is not None else \
|
|
157
|
+
[d["name"] for d in data if d["kind"] in ("string", "text")][:5]
|
|
158
|
+
|
|
159
|
+
return {
|
|
160
|
+
"key": model_key(model), "app": meta.app, "name": model.__name__, "table": meta.db_table,
|
|
161
|
+
"pk": meta.pk_attr, "fields": data, "relations": rels, "list_display": shown,
|
|
162
|
+
"search_fields": [n for n in searchable if n in names],
|
|
163
|
+
"filter_paths": _filter_paths(model, data, rels),
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def er_mermaid(models: Dict[str, type], config: Any) -> str:
|
|
168
|
+
def ent(key: str) -> str:
|
|
169
|
+
"""Mermaid entity names cannot contain dots."""
|
|
170
|
+
return key.replace(".", "_")
|
|
171
|
+
|
|
172
|
+
out, seen = ["erDiagram"], set()
|
|
173
|
+
descs = {k: describe(m, config) for k, m in models.items()}
|
|
174
|
+
for key, d in descs.items():
|
|
175
|
+
out.append(f" {ent(key)} {{")
|
|
176
|
+
out += [f" {f['kind']} {f['name']}" + (" PK" if f["pk"] else "") for f in d["fields"]]
|
|
177
|
+
out.append(" }")
|
|
178
|
+
for key, d in descs.items():
|
|
179
|
+
for r in d["relations"]:
|
|
180
|
+
if r["type"] == "fk":
|
|
181
|
+
out.append(f' {ent(r["model"])} ||--o{{ {ent(key)} : "{r["name"]}"')
|
|
182
|
+
elif r["type"] == "o2o":
|
|
183
|
+
out.append(f' {ent(r["model"])} ||--|| {ent(key)} : "{r["name"]}"')
|
|
184
|
+
elif r["type"] == "m2m":
|
|
185
|
+
pair = frozenset((key, r["model"]))
|
|
186
|
+
if pair not in seen:
|
|
187
|
+
seen.add(pair)
|
|
188
|
+
out.append(f' {ent(key)} }}o--o{{ {ent(r["model"])} : "{r["name"]}"')
|
|
189
|
+
return "\n".join(out)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def pydantic_code(model: type) -> str:
|
|
193
|
+
n = model.__name__
|
|
194
|
+
return (f"from tortoise.contrib.pydantic import pydantic_model_creator\n"
|
|
195
|
+
f"from {model.__module__} import {n}\n\n"
|
|
196
|
+
f"{n}_Pydantic = pydantic_model_creator({n})\n"
|
|
197
|
+
f'{n}In_Pydantic = pydantic_model_creator({n}, name="{n}In", exclude_readonly=True)\n')
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""The single source of truth for which files are served, and how.
|
|
2
|
+
|
|
3
|
+
Before this module the whitelist lived in ``handler.py`` as a literal dict, so
|
|
4
|
+
every new JS/CSS file needed a handler edit. Moving it here keeps the *policy*
|
|
5
|
+
(exact-path lookups only, never a directory, never outside ``static/``) in one
|
|
6
|
+
place while letting data — :data:`ASSETS` — change on its own.
|
|
7
|
+
|
|
8
|
+
Security model, unchanged from before but now enforced centrally:
|
|
9
|
+
|
|
10
|
+
* a URL is served only if its **exact** string is a key here;
|
|
11
|
+
* no path arithmetic happens on user input, so ``..`` and encoded traversal
|
|
12
|
+
are structurally impossible (they only ever fail the lookup);
|
|
13
|
+
* a resolved file must still be a regular file inside ``static/`` (catches a
|
|
14
|
+
mistake in this table, e.g. a typo pointing at a directory).
|
|
15
|
+
"""
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import pathlib
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Dict, Iterable, List, Optional, Tuple
|
|
21
|
+
|
|
22
|
+
#: The directory every asset is served from.
|
|
23
|
+
STATIC = pathlib.Path(__file__).resolve().parent.parent / "static"
|
|
24
|
+
|
|
25
|
+
_JS = "text/javascript; charset=utf-8"
|
|
26
|
+
_CSS = "text/css; charset=utf-8"
|
|
27
|
+
_HTML = "text/html; charset=utf-8"
|
|
28
|
+
|
|
29
|
+
_DEFAULT_TYPES = {".js": _JS, ".css": _CSS, ".html": _HTML}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass(frozen=True)
|
|
33
|
+
class Asset:
|
|
34
|
+
"""One served file. ``url`` is matched verbatim against ``req.path``."""
|
|
35
|
+
|
|
36
|
+
url: str
|
|
37
|
+
file: str # relative to static/
|
|
38
|
+
content_type: str = ""
|
|
39
|
+
vendored: bool = False # third-party: needs a license file
|
|
40
|
+
|
|
41
|
+
def __post_init__(self) -> None:
|
|
42
|
+
if not self.url.startswith("/"):
|
|
43
|
+
raise ValueError(f"asset url must be absolute: {self.url!r}")
|
|
44
|
+
if pathlib.Path(self.file).is_absolute() or ".." in pathlib.Path(self.file).parts:
|
|
45
|
+
raise ValueError(f"asset file must be relative to static/: {self.file!r}")
|
|
46
|
+
if not self.content_type:
|
|
47
|
+
suffix = pathlib.Path(self.file).suffix
|
|
48
|
+
if suffix not in _DEFAULT_TYPES:
|
|
49
|
+
raise ValueError(f"no content type for {self.file!r}")
|
|
50
|
+
object.__setattr__(self, "content_type", _DEFAULT_TYPES[suffix])
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class Manifest:
|
|
54
|
+
"""An immutable set of :class:`Asset` objects, looked up by exact URL."""
|
|
55
|
+
|
|
56
|
+
def __init__(self, assets: Iterable[Asset]):
|
|
57
|
+
self._by_url: Dict[str, Asset] = {}
|
|
58
|
+
for asset in assets:
|
|
59
|
+
if asset.url in self._by_url:
|
|
60
|
+
raise ValueError(f"duplicate asset url: {asset.url}")
|
|
61
|
+
self._by_url[asset.url] = asset
|
|
62
|
+
|
|
63
|
+
def lookup(self, url: str) -> Optional[Asset]:
|
|
64
|
+
"""Return the asset for ``url``, or ``None``. Never does path math."""
|
|
65
|
+
return self._by_url.get(url)
|
|
66
|
+
|
|
67
|
+
def entries(self) -> List[Asset]:
|
|
68
|
+
return list(self._by_url.values())
|
|
69
|
+
|
|
70
|
+
def read(self, url: str) -> Optional[Tuple[Asset, bytes]]:
|
|
71
|
+
"""Read the bytes for ``url``. ``None`` if it is not a safe regular file."""
|
|
72
|
+
asset = self.lookup(url)
|
|
73
|
+
if asset is None:
|
|
74
|
+
return None
|
|
75
|
+
path = (STATIC / asset.file).resolve()
|
|
76
|
+
if path != STATIC / asset.file or not path.is_file():
|
|
77
|
+
return None
|
|
78
|
+
return asset, path.read_bytes()
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
#: Every file the UI may load. Adding a file means adding a row here — and the
|
|
82
|
+
#: ``tests/test_manifest.py`` test fails until the row exists.
|
|
83
|
+
ASSETS: Tuple[Asset, ...] = (
|
|
84
|
+
Asset("/", "index.html"),
|
|
85
|
+
Asset("/index.html", "index.html"),
|
|
86
|
+
Asset("/static/app.css", "app.css"),
|
|
87
|
+
Asset("/static/a11y.js", "a11y.js"),
|
|
88
|
+
Asset("/static/ai.js", "ai.js"),
|
|
89
|
+
Asset("/static/app.js", "app.js"),
|
|
90
|
+
Asset("/static/audit.js", "audit.js"),
|
|
91
|
+
Asset("/static/copy-as.js", "copy-as.js"),
|
|
92
|
+
Asset("/static/inline-edit.js", "inline-edit.js"),
|
|
93
|
+
Asset("/static/er.js", "er.js"),
|
|
94
|
+
Asset("/static/er-layout.js", "er-layout.js"),
|
|
95
|
+
Asset("/static/filters.js", "filters.js"),
|
|
96
|
+
# v0.9.0 — i18n runtime plus two bundled locales. Locale files are plain
|
|
97
|
+
# JS dictionaries (no fetch, no inline script) loaded before app.js.
|
|
98
|
+
Asset("/static/i18n.js", "i18n.js"),
|
|
99
|
+
Asset("/static/i18n.en.js", "i18n.en.js"),
|
|
100
|
+
Asset("/static/i18n.zh-CN.js", "i18n.zh-CN.js"),
|
|
101
|
+
Asset("/static/json-view.js", "json-view.js"),
|
|
102
|
+
Asset("/static/migrations.js", "migrations.js"),
|
|
103
|
+
Asset("/static/pickers.js", "pickers.js"),
|
|
104
|
+
Asset("/static/palette.js", "palette.js"),
|
|
105
|
+
Asset("/static/pending.js", "pending.js"),
|
|
106
|
+
Asset("/static/query-history.js", "query-history.js"),
|
|
107
|
+
Asset("/static/shortcuts.js", "shortcuts.js"),
|
|
108
|
+
Asset("/static/state-hash.js", "state-hash.js"),
|
|
109
|
+
Asset("/static/tabs.js", "tabs.js"),
|
|
110
|
+
Asset("/static/playground.js", "playground.js"),
|
|
111
|
+
Asset("/static/theme.js", "theme.js"),
|
|
112
|
+
# Loaded synchronously in <head>, before first paint, to set data-theme.
|
|
113
|
+
Asset("/static/theme-init.js", "theme-init.js"),
|
|
114
|
+
Asset("/static/toasts.js", "toasts.js"),
|
|
115
|
+
Asset("/static/views.js", "views.js"),
|
|
116
|
+
Asset("/static/widgets.js", "widgets.js"),
|
|
117
|
+
Asset("/static/alpine.min.js", "alpine.min.js", vendored=True),
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
MANIFEST = Manifest(ASSETS)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def lookup(url: str) -> Optional[Asset]:
|
|
124
|
+
return MANIFEST.lookup(url)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def entries() -> List[Asset]:
|
|
128
|
+
return MANIFEST.entries()
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Opaque, tamper-proof keyset cursors for v0.4.0.
|
|
2
|
+
|
|
3
|
+
A cursor carries only the *ordering values* needed to resume a list plus a
|
|
4
|
+
primary key, never a whole row. It is signed with HMAC-SHA256 so a client
|
|
5
|
+
cannot forge one, and the payload is base64url so values are not readable at a
|
|
6
|
+
glance. Callers build cursors from the *permission-filtered* description, so a
|
|
7
|
+
hidden field never enters a cursor.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import base64
|
|
12
|
+
import hashlib
|
|
13
|
+
import hmac
|
|
14
|
+
import json
|
|
15
|
+
from typing import Any, Dict, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _b64(data: bytes) -> str:
|
|
19
|
+
return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _unb64(text: str) -> bytes:
|
|
23
|
+
return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def encode_cursor(payload: Dict[str, Any], secret: str) -> str:
|
|
27
|
+
"""Sign and encode a small payload. Keys should be visible field names."""
|
|
28
|
+
body = _b64(json.dumps(payload, separators=(",", ":"), sort_keys=True).encode("utf-8"))
|
|
29
|
+
sig = _b64(hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest())
|
|
30
|
+
return body + "." + sig
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def decode_cursor(token: str, secret: str) -> Optional[Dict[str, Any]]:
|
|
34
|
+
"""Return the payload only when the signature is valid; else None."""
|
|
35
|
+
try:
|
|
36
|
+
body, sig = token.split(".", 1)
|
|
37
|
+
except (ValueError, AttributeError):
|
|
38
|
+
return None
|
|
39
|
+
expected = _b64(hmac.new(secret.encode("utf-8"), body.encode("ascii"), hashlib.sha256).digest())
|
|
40
|
+
if not hmac.compare_digest(sig, expected):
|
|
41
|
+
return None
|
|
42
|
+
try:
|
|
43
|
+
data = json.loads(_unb64(body))
|
|
44
|
+
except Exception:
|
|
45
|
+
return None
|
|
46
|
+
return data if isinstance(data, dict) else None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cursor_payload(desc: Dict[str, Any], row: Dict[str, Any], visible: set) -> Dict[str, Any]:
|
|
50
|
+
"""Build a cursor payload from only the fields in `visible` plus the pk.
|
|
51
|
+
|
|
52
|
+
`desc` carries the ordering keys; any ordering field the caller cannot
|
|
53
|
+
read is omitted, so its value can never leak through the cursor.
|
|
54
|
+
"""
|
|
55
|
+
payload: Dict[str, Any] = {"pk": row.get("_pk")}
|
|
56
|
+
for key in desc.get("cursor_fields", []):
|
|
57
|
+
if key in visible and key in row:
|
|
58
|
+
payload[key] = row[key]
|
|
59
|
+
return payload
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Per-model and per-field read/write rules, enforced in the service layer.
|
|
2
|
+
|
|
3
|
+
A rule is a plain callable or mapping supplied by the host as
|
|
4
|
+
``Studio(permissions=...)``. This module never touches the request or the UI:
|
|
5
|
+
it returns the effective field lists that the service must use everywhere
|
|
6
|
+
(schema, rows, filters, sort, export, cursors).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from typing import Any, Callable, Dict, List, Optional, Set
|
|
11
|
+
|
|
12
|
+
Rule = Callable[[str, Optional[str], str], bool] # (model_key, field_or_None, action) -> bool
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class Permissions:
|
|
16
|
+
"""Evaluate read/write rules with a permissive default.
|
|
17
|
+
|
|
18
|
+
``rule(model_key, field, action)`` returns True to allow. ``field=None``
|
|
19
|
+
means the model itself (e.g. can the user see this model at all). Unknown
|
|
20
|
+
fields are denies. Errors in host rules fail closed.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, rule: Optional[Rule] = None):
|
|
24
|
+
self.rule = rule
|
|
25
|
+
|
|
26
|
+
def allow_model(self, key: str, action: str = "read") -> bool:
|
|
27
|
+
if self.rule is None:
|
|
28
|
+
return True
|
|
29
|
+
try:
|
|
30
|
+
return bool(self.rule(key, None, action))
|
|
31
|
+
except Exception:
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
def allow_field(self, key: str, field: str, action: str = "read") -> bool:
|
|
35
|
+
if self.rule is None:
|
|
36
|
+
return True
|
|
37
|
+
try:
|
|
38
|
+
return bool(self.rule(key, field, action))
|
|
39
|
+
except Exception:
|
|
40
|
+
return False
|
|
41
|
+
|
|
42
|
+
def visible_fields(self, key: str, fields: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
|
43
|
+
return [f for f in fields if self.allow_field(key, f["name"], "read")]
|
|
44
|
+
|
|
45
|
+
def writable_fields(self, key: str, fields: List[Dict[str, Any]]) -> Set[str]:
|
|
46
|
+
return {f["name"] for f in fields if self.allow_field(key, f["name"], "write")}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Host-supplied plugins for tortoise-orm-studio (v0.9.0).
|
|
2
|
+
|
|
3
|
+
A plugin is a passive Python object that contributes three things:
|
|
4
|
+
|
|
5
|
+
* **routes** under ``/api/plugins/<name>/...`` (the ``/api/v1`` prefix is an
|
|
6
|
+
alias, exactly as for built-in routes);
|
|
7
|
+
* **UI actions** that the shell renders as buttons and invokes with a plain GET;
|
|
8
|
+
* **metadata** merged into ``/api/schema`` under ``plugins.<name>``.
|
|
9
|
+
|
|
10
|
+
Design constraints, deliberate and test-pinned:
|
|
11
|
+
|
|
12
|
+
* plugin routes are dispatched **inside** the normal handler, after the shared
|
|
13
|
+
guard, so auth, localhost rules, CSRF and rate limiting still apply;
|
|
14
|
+
* the namespace is validated at registration, so a plugin cannot shadow a
|
|
15
|
+
built-in route, escape its prefix or collide with another plugin;
|
|
16
|
+
* everything published in ``/api/schema`` is a JSON-safe dict — handlers are
|
|
17
|
+
never serialised or exposed;
|
|
18
|
+
* plugins opt in to writes explicitly: ``read_only`` does not police their
|
|
19
|
+
handlers, but auth/CSRF do. A host that installs a plugin is trusting its code.
|
|
20
|
+
|
|
21
|
+
For framework adapters there is a separate, older mechanism:
|
|
22
|
+
``adapters.registry.register()`` / entry points. This module is for *Studio
|
|
23
|
+
features*, not framework mounting.
|
|
24
|
+
"""
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import inspect
|
|
28
|
+
import re
|
|
29
|
+
from dataclasses import dataclass
|
|
30
|
+
from typing import Any, Awaitable, Callable, Dict, Iterable, List, Optional, Tuple, Union
|
|
31
|
+
|
|
32
|
+
from .http import StudioError, StudioResponse, json_response
|
|
33
|
+
|
|
34
|
+
#: Lowercase, URL-safe, at most 40 characters. ``-`` and ``_`` are allowed so
|
|
35
|
+
#: ordinary package names can be used verbatim.
|
|
36
|
+
NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{0,39}$")
|
|
37
|
+
|
|
38
|
+
Handler = Callable[..., Union[StudioResponse, Dict[str, Any], List[Any], str, None,
|
|
39
|
+
Awaitable[Union[StudioResponse, Dict[str, Any], List[Any], str, None]]]]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass(frozen=True)
|
|
43
|
+
class PluginRoute:
|
|
44
|
+
"""One route owned by a plugin. ``path`` is relative to the plugin prefix.
|
|
45
|
+
|
|
46
|
+
``path`` may contain named regex groups (e.g. ``/item/(?P<id>[0-9]+)``);
|
|
47
|
+
their string values are passed to the handler as keyword arguments.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
method: str
|
|
51
|
+
path: str
|
|
52
|
+
handler: Handler
|
|
53
|
+
summary: str = ""
|
|
54
|
+
|
|
55
|
+
def __post_init__(self) -> None:
|
|
56
|
+
method = self.method.upper()
|
|
57
|
+
if method not in {"GET", "POST", "PATCH", "DELETE"}:
|
|
58
|
+
raise ValueError(f"unsupported plugin route method: {self.method!r}")
|
|
59
|
+
path = self.path
|
|
60
|
+
# A path is a regex *fragment* (named groups are supported), but the
|
|
61
|
+
# fragment must not be able to escape the plugin's namespace. V1.0.0
|
|
62
|
+
# hardening: reject alternation, anchors, backslash escapes and
|
|
63
|
+
# whitespace in addition to the original structural checks. Leaving
|
|
64
|
+
# ``|`` unescaped used to let a path like ``/x|/y`` compile to
|
|
65
|
+
# ``^/api/plugins/name/x|/y$`` and capture the top-level path ``/y``.
|
|
66
|
+
forbidden = set("|^$\\") | {" "}
|
|
67
|
+
if (not path.startswith("/") or ".." in path
|
|
68
|
+
or any(c in forbidden or c.isspace() for c in path)):
|
|
69
|
+
raise ValueError(f"plugin route path must be an absolute, safe suffix: {path!r}")
|
|
70
|
+
# Fail at construction on unbalanced groups rather than at first request.
|
|
71
|
+
try:
|
|
72
|
+
re.compile("(?:" + path + r")\Z")
|
|
73
|
+
except re.error as exc:
|
|
74
|
+
raise ValueError(f"invalid plugin route path {path!r}: {exc}") from exc
|
|
75
|
+
object.__setattr__(self, "method", method)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class PluginAction:
|
|
80
|
+
"""A declarative UI action: a labelled GET button for the plugin panel."""
|
|
81
|
+
|
|
82
|
+
id: str
|
|
83
|
+
label: str
|
|
84
|
+
path: str
|
|
85
|
+
description: str = ""
|
|
86
|
+
|
|
87
|
+
def __post_init__(self) -> None:
|
|
88
|
+
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,39}", self.id):
|
|
89
|
+
raise ValueError(f"invalid plugin action id: {self.id!r}")
|
|
90
|
+
if not self.path.startswith("/") or ".." in self.path:
|
|
91
|
+
raise ValueError(f"plugin action path must be an absolute, safe suffix: {self.path!r}")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
class StudioPlugin:
|
|
95
|
+
"""Base class for Studio plugins. Every hook is optional.
|
|
96
|
+
|
|
97
|
+
Subclasses set ``name`` and may override ``version``, ``configure``,
|
|
98
|
+
``routes``, ``ui_actions`` and ``schema``. ``configure`` is called once,
|
|
99
|
+
synchronously, while the ``Studio`` object is being constructed.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
name: str = ""
|
|
103
|
+
version: str = "0"
|
|
104
|
+
|
|
105
|
+
def configure(self, studio: Any) -> None:
|
|
106
|
+
"""Called once with the ``Studio`` facade, before any request."""
|
|
107
|
+
|
|
108
|
+
def routes(self) -> Iterable[PluginRoute]:
|
|
109
|
+
return ()
|
|
110
|
+
|
|
111
|
+
def ui_actions(self) -> Iterable[PluginAction]:
|
|
112
|
+
return ()
|
|
113
|
+
|
|
114
|
+
def schema(self) -> Dict[str, Any]:
|
|
115
|
+
return {}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class _CompiledRoute:
|
|
120
|
+
method: str
|
|
121
|
+
pattern: re.Pattern[str]
|
|
122
|
+
handler: Handler
|
|
123
|
+
summary: str
|
|
124
|
+
path: str
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
Match = Tuple[Handler, Dict[str, str]]
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class PluginManager:
|
|
131
|
+
"""Validates plugins once, then offers match/describe/dispatch operations."""
|
|
132
|
+
|
|
133
|
+
def __init__(self, plugins: Iterable[StudioPlugin]):
|
|
134
|
+
self.plugins: List[StudioPlugin] = []
|
|
135
|
+
self._routes: List[_CompiledRoute] = []
|
|
136
|
+
names: set[str] = set()
|
|
137
|
+
for plugin in plugins:
|
|
138
|
+
if not isinstance(plugin, StudioPlugin):
|
|
139
|
+
raise TypeError("Studio(plugins=[...]) accepts StudioPlugin instances only")
|
|
140
|
+
if not NAME_RE.fullmatch(plugin.name):
|
|
141
|
+
raise ValueError(f"invalid plugin name: {plugin.name!r}")
|
|
142
|
+
if plugin.name in names:
|
|
143
|
+
raise ValueError(f"duplicate plugin name: {plugin.name!r}")
|
|
144
|
+
names.add(plugin.name)
|
|
145
|
+
self.plugins.append(plugin)
|
|
146
|
+
for route in plugin.routes():
|
|
147
|
+
if not isinstance(route, PluginRoute):
|
|
148
|
+
raise TypeError(f"plugin {plugin.name!r} returned a non-PluginRoute from routes()")
|
|
149
|
+
# The fragment is wrapped in a non-capturing group so any
|
|
150
|
+
# regex constructs inside it stay within the plugin prefix.
|
|
151
|
+
# ``\Z`` (not ``$``) forbids a trailing newline bypass.
|
|
152
|
+
pattern = re.compile("^/api/plugins/" + re.escape(plugin.name)
|
|
153
|
+
+ "(?:" + route.path + r")\Z")
|
|
154
|
+
self._routes.append(_CompiledRoute(
|
|
155
|
+
method=route.method, pattern=pattern, handler=route.handler,
|
|
156
|
+
summary=route.summary, path=route.path,
|
|
157
|
+
))
|
|
158
|
+
|
|
159
|
+
def configure(self, studio: Any) -> None:
|
|
160
|
+
for plugin in self.plugins:
|
|
161
|
+
plugin.configure(studio)
|
|
162
|
+
|
|
163
|
+
def match(self, method: str, path: str) -> Optional[Match]:
|
|
164
|
+
for route in self._routes:
|
|
165
|
+
if route.method != method:
|
|
166
|
+
continue
|
|
167
|
+
m = route.pattern.match(path)
|
|
168
|
+
if m:
|
|
169
|
+
groups = {k: v for k, v in m.groupdict().items() if v is not None}
|
|
170
|
+
return route.handler, groups
|
|
171
|
+
return None
|
|
172
|
+
|
|
173
|
+
def describe(self) -> Dict[str, Any]:
|
|
174
|
+
"""JSON-safe description for ``/api/schema`` -> ``plugins``."""
|
|
175
|
+
out: Dict[str, Any] = {}
|
|
176
|
+
for plugin in self.plugins:
|
|
177
|
+
actions = [
|
|
178
|
+
{"id": a.id, "label": a.label, "path": a.path, "description": a.description}
|
|
179
|
+
for a in plugin.ui_actions()
|
|
180
|
+
]
|
|
181
|
+
routes = [
|
|
182
|
+
{"method": r.method, "path": r.path, "summary": r.summary}
|
|
183
|
+
for r in plugin.routes()
|
|
184
|
+
]
|
|
185
|
+
out[plugin.name] = {
|
|
186
|
+
"version": plugin.version,
|
|
187
|
+
"routes": routes,
|
|
188
|
+
"actions": actions,
|
|
189
|
+
"metadata": plugin.schema(),
|
|
190
|
+
}
|
|
191
|
+
return out
|
|
192
|
+
|
|
193
|
+
@staticmethod
|
|
194
|
+
async def dispatch(handler: Handler, req: Any, groups: Dict[str, str]) -> StudioResponse:
|
|
195
|
+
try:
|
|
196
|
+
result = handler(req, **groups)
|
|
197
|
+
if inspect.isawaitable(result):
|
|
198
|
+
result = await result
|
|
199
|
+
except StudioError:
|
|
200
|
+
raise
|
|
201
|
+
if isinstance(result, StudioResponse):
|
|
202
|
+
return result
|
|
203
|
+
if result is None:
|
|
204
|
+
return StudioResponse(204)
|
|
205
|
+
if isinstance(result, (dict, list)):
|
|
206
|
+
return json_response(result)
|
|
207
|
+
if isinstance(result, str):
|
|
208
|
+
return StudioResponse(200, {"content-type": "text/plain; charset=utf-8"},
|
|
209
|
+
result.encode("utf-8"))
|
|
210
|
+
raise TypeError("plugin handler must return a dict, list, str, StudioResponse or None")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
#: Shared empty manager — avoids a conditional in the handler hot path.
|
|
214
|
+
EMPTY = PluginManager(())
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Pluggable rate limiting with an in-memory default.
|
|
2
|
+
|
|
3
|
+
``RateLimiter.check(key) -> None`` raises ``StudioError(429, ...)`` when the
|
|
4
|
+
caller exceeds the configured budget. The default is a fixed window, keyed by
|
|
5
|
+
client address; the host can pass any object with the same method via
|
|
6
|
+
``Studio(rate_limiter=...)``.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from typing import Dict, Tuple
|
|
13
|
+
|
|
14
|
+
from .http import StudioError
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class InMemoryRateLimiter:
|
|
18
|
+
def __init__(self, limit: int = 120, window: float = 60.0):
|
|
19
|
+
self.limit, self.window = limit, window
|
|
20
|
+
self._hits: Dict[str, Tuple[float, int]] = {}
|
|
21
|
+
self._lock = threading.Lock()
|
|
22
|
+
|
|
23
|
+
def check(self, key: str) -> None:
|
|
24
|
+
now = time.monotonic()
|
|
25
|
+
with self._lock:
|
|
26
|
+
start, count = self._hits.get(key, (now, 0))
|
|
27
|
+
if now - start >= self.window:
|
|
28
|
+
start, count = now, 0
|
|
29
|
+
count += 1
|
|
30
|
+
self._hits[key] = (start, count)
|
|
31
|
+
if count > self.limit:
|
|
32
|
+
raise StudioError(429, "rate_limited", "Too many requests")
|