devadmin 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.
- devadmin/__init__.py +19 -0
- devadmin/__main__.py +5 -0
- devadmin/adapters/__init__.py +0 -0
- devadmin/adapters/base.py +175 -0
- devadmin/adapters/tortoise/__init__.py +81 -0
- devadmin/adapters/tortoise/introspect.py +209 -0
- devadmin/adapters/tortoise/models.py +34 -0
- devadmin/adapters/tortoise/queries.py +330 -0
- devadmin/adapters/tortoise/related.py +215 -0
- devadmin/adapters/tortoise/store.py +156 -0
- devadmin/auth/__init__.py +16 -0
- devadmin/auth/csrf.py +18 -0
- devadmin/auth/ip.py +28 -0
- devadmin/auth/login.py +149 -0
- devadmin/auth/session.py +94 -0
- devadmin/cli.py +314 -0
- devadmin/config.py +34 -0
- devadmin/core/__init__.py +0 -0
- devadmin/core/binding.py +609 -0
- devadmin/core/forms.py +475 -0
- devadmin/core/listing.py +400 -0
- devadmin/core/options.py +99 -0
- devadmin/core/paths.py +39 -0
- devadmin/core/site.py +288 -0
- devadmin/core/values.py +122 -0
- devadmin/history/__init__.py +38 -0
- devadmin/history/diff.py +109 -0
- devadmin/history/encoding.py +120 -0
- devadmin/history/records.py +40 -0
- devadmin/history/render.py +129 -0
- devadmin/history/service.py +256 -0
- devadmin/web/__init__.py +0 -0
- devadmin/web/app.py +106 -0
- devadmin/web/deps.py +275 -0
- devadmin/web/guard.py +178 -0
- devadmin/web/static/autocomplete.js +231 -0
- devadmin/web/static/devadmin.css +1645 -0
- devadmin/web/static/devadmin.js +129 -0
- devadmin/web/static/htmx.min.js +1 -0
- devadmin/web/static/icons/check.svg +1 -0
- devadmin/web/static/icons/clock.svg +1 -0
- devadmin/web/static/icons/cross.svg +1 -0
- devadmin/web/static/icons/down.svg +1 -0
- devadmin/web/static/icons/eye.svg +1 -0
- devadmin/web/static/icons/lock.svg +1 -0
- devadmin/web/static/icons/pencil.svg +1 -0
- devadmin/web/static/icons/plus.svg +1 -0
- devadmin/web/static/icons/right.svg +1 -0
- devadmin/web/static/icons/trash.svg +1 -0
- devadmin/web/static/icons/up.svg +1 -0
- devadmin/web/templates/_field.html +35 -0
- devadmin/web/templates/_history.html +19 -0
- devadmin/web/templates/_pagination.html +8 -0
- devadmin/web/templates/action_confirm.html +26 -0
- devadmin/web/templates/base.html +63 -0
- devadmin/web/templates/delete.html +62 -0
- devadmin/web/templates/error.html +9 -0
- devadmin/web/templates/form.html +34 -0
- devadmin/web/templates/history.html +59 -0
- devadmin/web/templates/index.html +49 -0
- devadmin/web/templates/list.html +88 -0
- devadmin/web/templates/login.html +15 -0
- devadmin/web/templates/recent.html +25 -0
- devadmin/web/views_auth.py +146 -0
- devadmin/web/views_delete.py +774 -0
- devadmin/web/views_form.py +551 -0
- devadmin/web/views_history.py +261 -0
- devadmin/web/views_list.py +246 -0
- devadmin-0.1.0.dist-info/METADATA +702 -0
- devadmin-0.1.0.dist-info/RECORD +73 -0
- devadmin-0.1.0.dist-info/WHEEL +4 -0
- devadmin-0.1.0.dist-info/entry_points.txt +3 -0
- devadmin-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from devadmin.auth.csrf import check_csrf
|
|
2
|
+
from devadmin.auth.ip import ip_allowed
|
|
3
|
+
from devadmin.auth.login import authenticate, load_actor
|
|
4
|
+
from devadmin.auth.session import SESSION_COOKIE, Session, SessionSigner, new_session, password_fingerprint
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"SESSION_COOKIE",
|
|
8
|
+
"Session",
|
|
9
|
+
"SessionSigner",
|
|
10
|
+
"authenticate",
|
|
11
|
+
"check_csrf",
|
|
12
|
+
"ip_allowed",
|
|
13
|
+
"load_actor",
|
|
14
|
+
"new_session",
|
|
15
|
+
"password_fingerprint",
|
|
16
|
+
]
|
devadmin/auth/csrf.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import hmac
|
|
2
|
+
|
|
3
|
+
from devadmin.auth.session import Session
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _matches(expected: bytes, value: object) -> bool:
|
|
7
|
+
if not isinstance(value, str) or not value:
|
|
8
|
+
return False
|
|
9
|
+
return hmac.compare_digest(expected, value.encode("utf-8", "surrogatepass"))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def check_csrf(session: Session, form_value: str | None, header_value: str | None) -> bool:
|
|
13
|
+
if not isinstance(session.csrf, str) or not session.csrf:
|
|
14
|
+
return False
|
|
15
|
+
expected = session.csrf.encode("utf-8")
|
|
16
|
+
form_ok = _matches(expected, form_value)
|
|
17
|
+
header_ok = _matches(expected, header_value)
|
|
18
|
+
return form_ok or header_ok
|
devadmin/auth/ip.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import ipaddress
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _networks(allowed: list[str]) -> list[ipaddress.IPv4Network | ipaddress.IPv6Network]:
|
|
5
|
+
networks = []
|
|
6
|
+
for entry in allowed:
|
|
7
|
+
if not isinstance(entry, str):
|
|
8
|
+
continue
|
|
9
|
+
try:
|
|
10
|
+
networks.append(ipaddress.ip_network(entry, strict=False))
|
|
11
|
+
except ValueError:
|
|
12
|
+
continue
|
|
13
|
+
return networks
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def ip_allowed(allowed: list[str], address: str) -> bool:
|
|
17
|
+
if not allowed:
|
|
18
|
+
return True
|
|
19
|
+
if not isinstance(address, str):
|
|
20
|
+
return False
|
|
21
|
+
try:
|
|
22
|
+
parsed = ipaddress.ip_address(address)
|
|
23
|
+
except ValueError:
|
|
24
|
+
return False
|
|
25
|
+
candidates = [parsed]
|
|
26
|
+
if isinstance(parsed, ipaddress.IPv6Address) and parsed.ipv4_mapped is not None:
|
|
27
|
+
candidates.append(parsed.ipv4_mapped)
|
|
28
|
+
return any(candidate in network for network in _networks(allowed) for candidate in candidates)
|
devadmin/auth/login.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import inspect
|
|
3
|
+
import logging
|
|
4
|
+
from time import monotonic
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from devadmin.adapters.base import Filter, Query
|
|
8
|
+
from devadmin.auth.session import Session, password_fingerprint, same_fingerprint
|
|
9
|
+
from devadmin.config import AdminConfig
|
|
10
|
+
|
|
11
|
+
MAX_LOGIN_LENGTH = 320
|
|
12
|
+
MAX_PASSWORD_LENGTH = 4096
|
|
13
|
+
DUMMY_HASH_RETRY_SECONDS = 60
|
|
14
|
+
_DUMMY_HASH_SAMPLE = 50
|
|
15
|
+
_DUMMY_HASH = "_devadmin_dummy_hash"
|
|
16
|
+
_DUMMY_HASH_MISS_UNTIL = "_devadmin_dummy_hash_miss_until"
|
|
17
|
+
|
|
18
|
+
logger = logging.getLogger("devadmin")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def user_model(config: AdminConfig) -> Any:
|
|
22
|
+
for info in config.adapter.list_models():
|
|
23
|
+
if info.key == config.user_model:
|
|
24
|
+
return info.model
|
|
25
|
+
raise LookupError(f"unknown user model {config.user_model!r}")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
_user_model = user_model
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _may_enter(config: AdminConfig, model: Any, user: Any) -> bool:
|
|
32
|
+
if getattr(user, config.access_flag) is not True:
|
|
33
|
+
return False
|
|
34
|
+
if any(field.name == "is_active" for field in config.adapter.describe(model)):
|
|
35
|
+
return getattr(user, "is_active") is True
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def filter_query(*filters: Filter) -> Query:
|
|
40
|
+
return Query(filters=list(filters), search=[], ordering=[], joins=[])
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
_query = filter_query
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _close_abandoned(future: asyncio.Future) -> None:
|
|
47
|
+
if future.cancelled() or future.exception() is not None:
|
|
48
|
+
return
|
|
49
|
+
result = future.result()
|
|
50
|
+
if inspect.iscoroutine(result):
|
|
51
|
+
result.close()
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def _call_in_thread(verify: Any, password: str, stored_hash: Any) -> Any:
|
|
55
|
+
call = asyncio.ensure_future(asyncio.to_thread(verify, password, stored_hash))
|
|
56
|
+
try:
|
|
57
|
+
return await asyncio.shield(call)
|
|
58
|
+
except asyncio.CancelledError:
|
|
59
|
+
call.add_done_callback(_close_abandoned)
|
|
60
|
+
raise
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
async def _verify(config: AdminConfig, password: str, stored_hash: Any) -> bool:
|
|
64
|
+
verify = config.verify_password
|
|
65
|
+
try:
|
|
66
|
+
if inspect.iscoroutinefunction(verify):
|
|
67
|
+
result = await verify(password, stored_hash)
|
|
68
|
+
else:
|
|
69
|
+
result = await _call_in_thread(verify, password, stored_hash)
|
|
70
|
+
if inspect.isawaitable(result):
|
|
71
|
+
result = await result
|
|
72
|
+
except Exception as exc:
|
|
73
|
+
logger.warning("verify_password raised %s", type(exc).__name__)
|
|
74
|
+
return False
|
|
75
|
+
return result is True
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
async def _find_user(config: AdminConfig, model: Any, login: str) -> Any | None:
|
|
79
|
+
field = next(field for field in config.adapter.describe(model) if field.name == config.login_field)
|
|
80
|
+
if field.max_length is not None and len(login) > field.max_length:
|
|
81
|
+
return None
|
|
82
|
+
try:
|
|
83
|
+
exact = await config.adapter.query(model, _query(Filter(config.login_field, "eq", login)), 0, 2)
|
|
84
|
+
except Exception:
|
|
85
|
+
exact = []
|
|
86
|
+
if exact:
|
|
87
|
+
return exact[0] if len(exact) == 1 else None
|
|
88
|
+
folded = await config.adapter.query(model, _query(Filter(config.login_field, "iexact", login)), 0, 2)
|
|
89
|
+
return folded[0] if len(folded) == 1 else None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
async def _dummy_hash(config: AdminConfig, model: Any) -> Any | None:
|
|
93
|
+
remembered = getattr(config, _DUMMY_HASH, None)
|
|
94
|
+
if remembered:
|
|
95
|
+
return remembered
|
|
96
|
+
if monotonic() < getattr(config, _DUMMY_HASH_MISS_UNTIL, float("-inf")):
|
|
97
|
+
return None
|
|
98
|
+
rows = await config.adapter.query(
|
|
99
|
+
model, _query(Filter(config.password_field, "isnull", False)), 0, _DUMMY_HASH_SAMPLE
|
|
100
|
+
)
|
|
101
|
+
for row in rows:
|
|
102
|
+
stored_hash = getattr(row, config.password_field)
|
|
103
|
+
if stored_hash:
|
|
104
|
+
setattr(config, _DUMMY_HASH, stored_hash)
|
|
105
|
+
return stored_hash
|
|
106
|
+
setattr(config, _DUMMY_HASH_MISS_UNTIL, monotonic() + DUMMY_HASH_RETRY_SECONDS)
|
|
107
|
+
return None
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def authenticate(config: AdminConfig, login: str, password: str) -> Any | None:
|
|
111
|
+
if not isinstance(login, str) or not isinstance(password, str):
|
|
112
|
+
return None
|
|
113
|
+
login = login.strip()
|
|
114
|
+
if not login or not password:
|
|
115
|
+
return None
|
|
116
|
+
if "\x00" in login or len(login) > MAX_LOGIN_LENGTH or len(password) > MAX_PASSWORD_LENGTH:
|
|
117
|
+
return None
|
|
118
|
+
model = _user_model(config)
|
|
119
|
+
user = await _find_user(config, model, login)
|
|
120
|
+
if user is None:
|
|
121
|
+
dummy_hash = await _dummy_hash(config, model)
|
|
122
|
+
if dummy_hash:
|
|
123
|
+
await _verify(config, password, dummy_hash)
|
|
124
|
+
return None
|
|
125
|
+
stored_hash = getattr(user, config.password_field)
|
|
126
|
+
if not stored_hash:
|
|
127
|
+
return None
|
|
128
|
+
verified = await _verify(config, password, stored_hash)
|
|
129
|
+
setattr(config, _DUMMY_HASH, stored_hash)
|
|
130
|
+
if not verified or not _may_enter(config, model, user):
|
|
131
|
+
return None
|
|
132
|
+
return user
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def load_actor(config: AdminConfig, session: Session) -> Any | None:
|
|
136
|
+
model = _user_model(config)
|
|
137
|
+
if not isinstance(session.user_pk, str):
|
|
138
|
+
return None
|
|
139
|
+
try:
|
|
140
|
+
pk = config.adapter.parse_pk(model, session.user_pk)
|
|
141
|
+
except ValueError:
|
|
142
|
+
return None
|
|
143
|
+
user = await config.adapter.get(model, pk)
|
|
144
|
+
if user is None or not _may_enter(config, model, user):
|
|
145
|
+
return None
|
|
146
|
+
expected = password_fingerprint(config.secret_key, getattr(user, config.password_field))
|
|
147
|
+
if not same_fingerprint(expected, session.pwd):
|
|
148
|
+
return None
|
|
149
|
+
return user
|
devadmin/auth/session.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import re
|
|
4
|
+
import secrets
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from itsdangerous import BadData, URLSafeTimedSerializer
|
|
10
|
+
|
|
11
|
+
SESSION_COOKIE = "devadmin_session"
|
|
12
|
+
CLOCK_SKEW_SECONDS = 60
|
|
13
|
+
_SALT = "devadmin.session"
|
|
14
|
+
_CSRF = re.compile(r"[0-9a-f]{64}")
|
|
15
|
+
_PWD = re.compile(r"[0-9a-f]{32}")
|
|
16
|
+
_PWD_LABEL = b"devadmin.session.pwd\x00"
|
|
17
|
+
_KEYS = {"user_pk", "issued_at", "csrf", "pwd"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class Session:
|
|
22
|
+
user_pk: str
|
|
23
|
+
issued_at: int
|
|
24
|
+
csrf: str
|
|
25
|
+
pwd: str
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def new_session(user_pk: Any, pwd: str) -> Session:
|
|
29
|
+
return Session(user_pk=str(user_pk), issued_at=int(time.time()), csrf=secrets.token_hex(32), pwd=pwd)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def password_fingerprint(secret_key: str, password_hash: Any) -> str | None:
|
|
33
|
+
if isinstance(password_hash, str):
|
|
34
|
+
data = password_hash.encode("utf-8", "surrogatepass")
|
|
35
|
+
elif isinstance(password_hash, bytes):
|
|
36
|
+
data = password_hash
|
|
37
|
+
else:
|
|
38
|
+
return None
|
|
39
|
+
if not data:
|
|
40
|
+
return None
|
|
41
|
+
key = secret_key.encode("utf-8", "surrogatepass")
|
|
42
|
+
return hmac.new(key, _PWD_LABEL + data, hashlib.sha256).hexdigest()[:32]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def same_fingerprint(expected: str | None, given: Any) -> bool:
|
|
46
|
+
if expected is None or not isinstance(given, str) or not _PWD.fullmatch(given):
|
|
47
|
+
return False
|
|
48
|
+
return hmac.compare_digest(expected.encode(), given.encode())
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class SessionSigner:
|
|
52
|
+
def __init__(self, secret_key: str, max_age: int) -> None:
|
|
53
|
+
if not isinstance(secret_key, str) or len(secret_key) < 16:
|
|
54
|
+
raise ValueError("secret_key must be a string of at least 16 characters")
|
|
55
|
+
self.max_age = max_age
|
|
56
|
+
self._serializer = URLSafeTimedSerializer(
|
|
57
|
+
secret_key, salt=_SALT, signer_kwargs={"digest_method": hashlib.sha256}
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def dumps(self, session: Session) -> str:
|
|
61
|
+
return self._serializer.dumps(
|
|
62
|
+
{"user_pk": session.user_pk, "issued_at": session.issued_at, "csrf": session.csrf, "pwd": session.pwd}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def loads(self, value: str) -> Session | None:
|
|
66
|
+
if not isinstance(value, str) or not value:
|
|
67
|
+
return None
|
|
68
|
+
try:
|
|
69
|
+
payload, signed_at = self._serializer.loads(value, max_age=None, return_timestamp=True)
|
|
70
|
+
except (BadData, UnicodeError):
|
|
71
|
+
return None
|
|
72
|
+
session = _session_from(payload)
|
|
73
|
+
if session is None or not self._fresh(int(signed_at.timestamp()), session.issued_at):
|
|
74
|
+
return None
|
|
75
|
+
return session
|
|
76
|
+
|
|
77
|
+
def _fresh(self, *moments: int) -> bool:
|
|
78
|
+
now = int(time.time())
|
|
79
|
+
return all(now - self.max_age <= moment <= now + CLOCK_SKEW_SECONDS for moment in moments)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _session_from(payload: Any) -> Session | None:
|
|
83
|
+
if not isinstance(payload, dict) or payload.keys() != _KEYS:
|
|
84
|
+
return None
|
|
85
|
+
user_pk, issued_at, csrf, pwd = payload["user_pk"], payload["issued_at"], payload["csrf"], payload["pwd"]
|
|
86
|
+
if type(user_pk) is not str or not user_pk:
|
|
87
|
+
return None
|
|
88
|
+
if type(issued_at) is not int:
|
|
89
|
+
return None
|
|
90
|
+
if type(csrf) is not str or not _CSRF.fullmatch(csrf):
|
|
91
|
+
return None
|
|
92
|
+
if type(pwd) is not str or not _PWD.fullmatch(pwd):
|
|
93
|
+
return None
|
|
94
|
+
return Session(user_pk=user_pk, issued_at=issued_at, csrf=csrf, pwd=pwd)
|
devadmin/cli.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import asyncio
|
|
3
|
+
import importlib
|
|
4
|
+
import inspect
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import traceback
|
|
9
|
+
from collections.abc import Callable
|
|
10
|
+
from datetime import UTC, datetime, timedelta
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from devadmin.adapters.base import Filter
|
|
14
|
+
from devadmin.auth.login import filter_query, user_model
|
|
15
|
+
from devadmin.config import AdminConfig
|
|
16
|
+
from devadmin.core.options import ConfigError
|
|
17
|
+
from devadmin.core.site import Site
|
|
18
|
+
from devadmin.history.service import History
|
|
19
|
+
|
|
20
|
+
CONFIRM_BELOW_DAYS = 30
|
|
21
|
+
SHOWN_LOGIN_LENGTH = 80
|
|
22
|
+
INTERRUPTED_EXIT_CODE = 130
|
|
23
|
+
FOLDED_SUFFIX = " (matched case-insensitively)"
|
|
24
|
+
_DAYS = re.compile(r"[0-9]+d")
|
|
25
|
+
_LINE_BREAKS = re.compile(r"\s*[\r\n\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]+\s*")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class CommandError(Exception):
|
|
29
|
+
pass
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _one_line(text: str) -> str:
|
|
33
|
+
return _LINE_BREAKS.sub(" ", text.strip())
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _shown(login: str) -> str:
|
|
37
|
+
login = _one_line(login)
|
|
38
|
+
return login if len(login) <= SHOWN_LOGIN_LENGTH else login[:SHOWN_LOGIN_LENGTH] + "…"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _plural(count: int, noun: str) -> str:
|
|
42
|
+
return f"{count} {noun}" if count == 1 else f"{count} {noun}s"
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _describe(exc: BaseException) -> str:
|
|
46
|
+
return f"{type(exc).__name__}: {_one_line(str(exc))}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _error(message: str) -> None:
|
|
50
|
+
print(f"error: {message}", file=sys.stderr)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _report(prefix: str, exc: BaseException, show_traceback: bool) -> None:
|
|
54
|
+
if show_traceback:
|
|
55
|
+
traceback.print_exception(exc, file=sys.stderr)
|
|
56
|
+
_error(prefix + _describe(exc))
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _config_ref(text: str) -> str:
|
|
60
|
+
module, _, attribute = text.partition(":")
|
|
61
|
+
if not module or not attribute or ":" in attribute:
|
|
62
|
+
raise argparse.ArgumentTypeError(f"expected module:attribute, got {text!r}")
|
|
63
|
+
return text
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _login(text: str) -> str:
|
|
67
|
+
login = text.strip()
|
|
68
|
+
if not login:
|
|
69
|
+
raise argparse.ArgumentTypeError("the login must not be empty")
|
|
70
|
+
return login
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _older_than(text: str) -> timedelta:
|
|
74
|
+
if not _DAYS.fullmatch(text) or int(text[:-1]) < 1:
|
|
75
|
+
raise argparse.ArgumentTypeError(f"expected a positive number of days such as 365d, got {text!r}")
|
|
76
|
+
days = int(text[:-1])
|
|
77
|
+
if days > (datetime.now(UTC) - datetime.min.replace(tzinfo=UTC)).days:
|
|
78
|
+
raise argparse.ArgumentTypeError(f"{text!r} is too large")
|
|
79
|
+
return timedelta(days=days)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _parser() -> tuple[argparse.ArgumentParser, argparse.ArgumentParser]:
|
|
83
|
+
parser = argparse.ArgumentParser(prog="devadmin", description="Manage devadmin access and change history.")
|
|
84
|
+
commands = parser.add_subparsers(dest="command", required=True, metavar="command")
|
|
85
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
86
|
+
common.add_argument(
|
|
87
|
+
"--config",
|
|
88
|
+
required=True,
|
|
89
|
+
type=_config_ref,
|
|
90
|
+
metavar="module:attr",
|
|
91
|
+
help="an AdminConfig, or a callable returning one, importable from the current directory",
|
|
92
|
+
)
|
|
93
|
+
common.add_argument("--traceback", action="store_true", help="print the full traceback of an unexpected error")
|
|
94
|
+
for name, help_text in (
|
|
95
|
+
("grant", "give a user access to the panel"),
|
|
96
|
+
("revoke", "take panel access away from a user"),
|
|
97
|
+
):
|
|
98
|
+
command = commands.add_parser(name, parents=[common], help=help_text, description=help_text)
|
|
99
|
+
command.add_argument("login", type=_login, help="the value of the user's login field")
|
|
100
|
+
if name == "grant":
|
|
101
|
+
command.add_argument(
|
|
102
|
+
"--ignore-case",
|
|
103
|
+
action="store_true",
|
|
104
|
+
help="accept a single user whose login differs from the typed one only in case",
|
|
105
|
+
)
|
|
106
|
+
purge = commands.add_parser(
|
|
107
|
+
"purge-history",
|
|
108
|
+
parents=[common],
|
|
109
|
+
help="delete change history older than a number of days",
|
|
110
|
+
description="delete change history older than a number of days",
|
|
111
|
+
)
|
|
112
|
+
purge.add_argument("--older-than", required=True, type=_older_than, metavar="Nd", help="for example 365d")
|
|
113
|
+
purge.add_argument("--yes", action="store_true", help=f"confirm a cutoff under {CONFIRM_BELOW_DAYS} days")
|
|
114
|
+
return parser, purge
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
async def _call(function: Callable[[], Any]) -> Any:
|
|
118
|
+
result = function()
|
|
119
|
+
if inspect.isawaitable(result):
|
|
120
|
+
result = await result
|
|
121
|
+
return result
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
async def _load_config(ref: str) -> AdminConfig:
|
|
125
|
+
module_name, _, attribute = ref.partition(":")
|
|
126
|
+
cwd = os.getcwd()
|
|
127
|
+
if sys.path[:1] != [cwd]:
|
|
128
|
+
sys.path.insert(0, cwd)
|
|
129
|
+
try:
|
|
130
|
+
module = importlib.import_module(module_name)
|
|
131
|
+
except Exception as exc:
|
|
132
|
+
raise CommandError(f"--config {ref}: cannot import {module_name}: {_describe(exc)}") from exc
|
|
133
|
+
try:
|
|
134
|
+
target = getattr(module, attribute)
|
|
135
|
+
except AttributeError:
|
|
136
|
+
raise CommandError(f"--config {ref}: {module_name} has no attribute {attribute!r}") from None
|
|
137
|
+
if isinstance(target, AdminConfig):
|
|
138
|
+
return target
|
|
139
|
+
if not callable(target):
|
|
140
|
+
raise CommandError(
|
|
141
|
+
f"--config {ref}: {attribute} is {type(target).__name__}, not an AdminConfig or a callable returning one"
|
|
142
|
+
)
|
|
143
|
+
try:
|
|
144
|
+
result = await _call(target)
|
|
145
|
+
except Exception as exc:
|
|
146
|
+
raise CommandError(f"--config {ref}: calling {attribute} raised {_describe(exc)}") from exc
|
|
147
|
+
if not isinstance(result, AdminConfig):
|
|
148
|
+
raise CommandError(f"--config {ref}: {attribute}() returned {type(result).__name__}, not an AdminConfig")
|
|
149
|
+
return result
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _ambiguous(config: AdminConfig, login: str, count: int, how: str) -> str:
|
|
153
|
+
return f"Login {_shown(login)} is ambiguous: {count} users match {config.login_field}{how}; nothing was changed"
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
async def _exact_rows(config: AdminConfig, model: Any, query: Any) -> list[Any]:
|
|
157
|
+
try:
|
|
158
|
+
async with config.adapter.atomic():
|
|
159
|
+
return await config.adapter.query(model, query, 0, 2)
|
|
160
|
+
except Exception:
|
|
161
|
+
return []
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
async def _one_user(
|
|
165
|
+
config: AdminConfig, model: Any, login: str, ignore_case: bool
|
|
166
|
+
) -> tuple[Any | None, bool, str]:
|
|
167
|
+
missing = f"No user with {config.login_field} = {_shown(login)}"
|
|
168
|
+
if not login:
|
|
169
|
+
return None, False, missing
|
|
170
|
+
exact = filter_query(Filter(config.login_field, "eq", login))
|
|
171
|
+
rows = await _exact_rows(config, model, exact)
|
|
172
|
+
if len(rows) == 1:
|
|
173
|
+
return rows[0], False, ""
|
|
174
|
+
if rows:
|
|
175
|
+
return None, False, _ambiguous(config, login, await config.adapter.count(model, exact), "")
|
|
176
|
+
folded = filter_query(Filter(config.login_field, "iexact", login))
|
|
177
|
+
rows = await config.adapter.query(model, folded, 0, 2)
|
|
178
|
+
if not rows:
|
|
179
|
+
return None, False, missing
|
|
180
|
+
if len(rows) > 1:
|
|
181
|
+
count = await config.adapter.count(model, folded)
|
|
182
|
+
return None, False, _ambiguous(config, login, count, " case-insensitively")
|
|
183
|
+
if getattr(rows[0], config.login_field) == login:
|
|
184
|
+
return rows[0], False, ""
|
|
185
|
+
if not ignore_case:
|
|
186
|
+
stored = _one_line(str(getattr(rows[0], config.login_field)))
|
|
187
|
+
return None, False, (
|
|
188
|
+
f"{missing}; did you mean {stored}? Re-run with that exact value, or pass --ignore-case."
|
|
189
|
+
)
|
|
190
|
+
return rows[0], True, ""
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _login_warnings(config: AdminConfig, model: Any, user: Any, stored: str) -> list[str]:
|
|
194
|
+
warnings = []
|
|
195
|
+
has_active = any(field.name == "is_active" for field in config.adapter.describe(model))
|
|
196
|
+
if has_active and getattr(user, "is_active") is not True:
|
|
197
|
+
warnings.append(f"{stored} is inactive and cannot log in until it is activated")
|
|
198
|
+
if not getattr(user, config.password_field):
|
|
199
|
+
warnings.append(f"{stored} has no password and cannot log in to the panel with one")
|
|
200
|
+
return warnings
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
async def run_grant(config: AdminConfig, login: str, value: bool, *, ignore_case: bool = False) -> bool:
|
|
204
|
+
site = Site(config)
|
|
205
|
+
site.build()
|
|
206
|
+
adapter = config.adapter
|
|
207
|
+
history = History(adapter, sensitive_for=site.sensitive_fields)
|
|
208
|
+
model = user_model(config)
|
|
209
|
+
flag = config.access_flag
|
|
210
|
+
async with adapter.atomic():
|
|
211
|
+
user, folded, problem = await _one_user(config, model, login.strip(), ignore_case or not value)
|
|
212
|
+
changed = user is not None and getattr(user, flag) is not value
|
|
213
|
+
if changed:
|
|
214
|
+
summary = "grant via CLI" if value else "revoke via CLI"
|
|
215
|
+
async with history.action(actor=None, kind="custom", source="code", summary=summary) as collector:
|
|
216
|
+
before = history.snapshot(user)
|
|
217
|
+
await adapter.update(user, {flag: value})
|
|
218
|
+
await collector.record_update(user, before=before)
|
|
219
|
+
if user is None:
|
|
220
|
+
_error(problem)
|
|
221
|
+
return False
|
|
222
|
+
stored = _one_line(str(getattr(user, config.login_field)))
|
|
223
|
+
suffix = FOLDED_SUFFIX if folded else ""
|
|
224
|
+
if not changed:
|
|
225
|
+
print(f"{stored} already has {flag} = {value}{suffix}")
|
|
226
|
+
elif value:
|
|
227
|
+
print(f"Granted {flag} to {stored}{suffix}")
|
|
228
|
+
else:
|
|
229
|
+
print(f"Revoked {flag} from {stored}{suffix}")
|
|
230
|
+
if value:
|
|
231
|
+
for warning in _login_warnings(config, model, user, stored):
|
|
232
|
+
print(f"warning: {warning}", file=sys.stderr)
|
|
233
|
+
return True
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
async def run_purge(config: AdminConfig, older_than: timedelta) -> int:
|
|
237
|
+
removed = await config.adapter.history.purge(older_than=datetime.now(UTC) - older_than)
|
|
238
|
+
print(f"Removed {_plural(removed, 'history action')} older than {_plural(older_than.days, 'day')}")
|
|
239
|
+
return removed
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
async def _work(config: AdminConfig, args: argparse.Namespace) -> int:
|
|
243
|
+
try:
|
|
244
|
+
if args.command == "purge-history":
|
|
245
|
+
await run_purge(config, args.older_than)
|
|
246
|
+
return 0
|
|
247
|
+
if args.command == "grant":
|
|
248
|
+
granted = await run_grant(config, args.login, True, ignore_case=args.ignore_case)
|
|
249
|
+
else:
|
|
250
|
+
granted = await run_grant(config, args.login, False)
|
|
251
|
+
return 0 if granted else 1
|
|
252
|
+
except ConfigError as exc:
|
|
253
|
+
for line in str(exc).splitlines():
|
|
254
|
+
_error(line)
|
|
255
|
+
except Exception as exc:
|
|
256
|
+
_report("", exc, args.traceback)
|
|
257
|
+
return 1
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
async def _shutdown(config: AdminConfig, args: argparse.Namespace, code: int) -> int:
|
|
261
|
+
if config.shutdown is None:
|
|
262
|
+
return code
|
|
263
|
+
try:
|
|
264
|
+
await _call(config.shutdown)
|
|
265
|
+
except Exception as exc:
|
|
266
|
+
if code == 0:
|
|
267
|
+
_report("the command completed and its result above stands, but shutdown failed: ", exc, args.traceback)
|
|
268
|
+
else:
|
|
269
|
+
_report("shutdown failed: ", exc, args.traceback)
|
|
270
|
+
return 1
|
|
271
|
+
return code
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
async def _command(args: argparse.Namespace) -> int:
|
|
275
|
+
try:
|
|
276
|
+
config = await _load_config(args.config)
|
|
277
|
+
except CommandError as exc:
|
|
278
|
+
if args.traceback and exc.__cause__ is not None:
|
|
279
|
+
traceback.print_exception(exc.__cause__, file=sys.stderr)
|
|
280
|
+
_error(str(exc))
|
|
281
|
+
return 1
|
|
282
|
+
for hook in ("startup", "shutdown"):
|
|
283
|
+
if getattr(config, hook) is not None and not callable(getattr(config, hook)):
|
|
284
|
+
_error(f"AdminConfig.{hook}: must be a callable or None")
|
|
285
|
+
return 1
|
|
286
|
+
if config.startup is not None:
|
|
287
|
+
try:
|
|
288
|
+
await _call(config.startup)
|
|
289
|
+
except Exception as exc:
|
|
290
|
+
_report("startup failed: ", exc, args.traceback)
|
|
291
|
+
return 1
|
|
292
|
+
code = 1
|
|
293
|
+
try:
|
|
294
|
+
code = await _work(config, args)
|
|
295
|
+
finally:
|
|
296
|
+
code = await _shutdown(config, args, code)
|
|
297
|
+
return code
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def main(argv: list[str] | None = None) -> int:
|
|
301
|
+
parser, purge = _parser()
|
|
302
|
+
try:
|
|
303
|
+
args = parser.parse_args(argv)
|
|
304
|
+
if args.command == "purge-history" and args.older_than < timedelta(days=CONFIRM_BELOW_DAYS) and not args.yes:
|
|
305
|
+
purge.error(
|
|
306
|
+
f"--older-than under {CONFIRM_BELOW_DAYS}d deletes recent history; add --yes to confirm"
|
|
307
|
+
)
|
|
308
|
+
except SystemExit as exc:
|
|
309
|
+
return exc.code if isinstance(exc.code, int) else (0 if exc.code is None else 2)
|
|
310
|
+
try:
|
|
311
|
+
return asyncio.run(_command(args))
|
|
312
|
+
except KeyboardInterrupt:
|
|
313
|
+
_error("interrupted; check the result with the panel or re-run the command")
|
|
314
|
+
return INTERRUPTED_EXIT_CODE
|
devadmin/config.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
from collections.abc import Awaitable, Callable
|
|
2
|
+
from dataclasses import dataclass, field
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
if TYPE_CHECKING:
|
|
6
|
+
from starlette.requests import Request
|
|
7
|
+
|
|
8
|
+
from devadmin.adapters.base import Adapter
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass
|
|
12
|
+
class AdminConfig:
|
|
13
|
+
adapter: "Adapter"
|
|
14
|
+
user_model: str
|
|
15
|
+
login_field: str
|
|
16
|
+
password_field: str
|
|
17
|
+
verify_password: Callable[[str, str], bool]
|
|
18
|
+
secret_key: str
|
|
19
|
+
access_flag: str = "is_superuser"
|
|
20
|
+
title: str = "devadmin"
|
|
21
|
+
allowed_ips: list[str] = field(default_factory=list)
|
|
22
|
+
client_ip: "Callable[[Request], str] | None" = None
|
|
23
|
+
login_rate_limiter: "Callable[[Request, str], Awaitable[bool]] | None" = None
|
|
24
|
+
admin_modules: list[str] = field(default_factory=list)
|
|
25
|
+
read_only_models: list[str] = field(default_factory=list)
|
|
26
|
+
exclude_models: list[str] = field(default_factory=list)
|
|
27
|
+
groups: dict[str, list[str]] | None = None
|
|
28
|
+
sensitive_patterns: tuple[str, ...] = ("password", "secret", "token", "hash")
|
|
29
|
+
session_seconds: int = 28800
|
|
30
|
+
secure_cookies: bool = True
|
|
31
|
+
exact_count_threshold: int = 100_000
|
|
32
|
+
max_cascade_rows: int = 1000
|
|
33
|
+
startup: Callable[[], Awaitable[None]] | None = None
|
|
34
|
+
shutdown: Callable[[], Awaitable[None]] | None = None
|
|
File without changes
|