swiftapi-kernel 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.

Potentially problematic release.


This version of swiftapi-kernel might be problematic. Click here for more details.

Files changed (187) hide show
  1. swiftapi/__init__.py +22 -0
  2. swiftapi/app/__init__.py +0 -0
  3. swiftapi/app/factory.py +200 -0
  4. swiftapi/app/lifespan.py +167 -0
  5. swiftapi/app/routers.py +58 -0
  6. swiftapi/cli/__init__.py +0 -0
  7. swiftapi/cli/admin.py +198 -0
  8. swiftapi/cli/appref.py +51 -0
  9. swiftapi/cli/audit.py +45 -0
  10. swiftapi/cli/db.py +185 -0
  11. swiftapi/cli/endpoint.py +169 -0
  12. swiftapi/cli/logs.py +100 -0
  13. swiftapi/cli/main.py +238 -0
  14. swiftapi/cli/new.py +113 -0
  15. swiftapi/cli/openapi.py +69 -0
  16. swiftapi/cli/resource.py +657 -0
  17. swiftapi/cli/scaffold.py +168 -0
  18. swiftapi/config/__init__.py +0 -0
  19. swiftapi/config/constants.py +51 -0
  20. swiftapi/config/environments.py +38 -0
  21. swiftapi/config/settings.py +764 -0
  22. swiftapi/core/__init__.py +0 -0
  23. swiftapi/core/admin/__init__.py +0 -0
  24. swiftapi/core/admin/accounts.py +385 -0
  25. swiftapi/core/admin/audit.py +203 -0
  26. swiftapi/core/admin/maintenance.py +53 -0
  27. swiftapi/core/admin/registry.py +53 -0
  28. swiftapi/core/admin/security.py +94 -0
  29. swiftapi/core/admin/session.py +154 -0
  30. swiftapi/core/admin/views.py +2428 -0
  31. swiftapi/core/cache/__init__.py +0 -0
  32. swiftapi/core/cache/base.py +29 -0
  33. swiftapi/core/cache/decorators.py +51 -0
  34. swiftapi/core/cache/factory.py +30 -0
  35. swiftapi/core/cache/keys.py +24 -0
  36. swiftapi/core/cache/memory.py +60 -0
  37. swiftapi/core/cache/null.py +28 -0
  38. swiftapi/core/cache/redis.py +50 -0
  39. swiftapi/core/container.py +209 -0
  40. swiftapi/core/db/__init__.py +0 -0
  41. swiftapi/core/db/base_model.py +122 -0
  42. swiftapi/core/db/crud.py +242 -0
  43. swiftapi/core/db/dialects/__init__.py +8 -0
  44. swiftapi/core/db/dialects/base.py +106 -0
  45. swiftapi/core/db/dialects/mysql.py +47 -0
  46. swiftapi/core/db/dialects/pg.py +51 -0
  47. swiftapi/core/db/dialects/registry.py +30 -0
  48. swiftapi/core/db/dialects/sqlite.py +47 -0
  49. swiftapi/core/db/engine.py +209 -0
  50. swiftapi/core/db/health.py +84 -0
  51. swiftapi/core/db/migrate/__init__.py +1 -0
  52. swiftapi/core/db/migrate/ddl.py +162 -0
  53. swiftapi/core/db/migrate/render.py +84 -0
  54. swiftapi/core/db/migrate/runner.py +159 -0
  55. swiftapi/core/db/migrate/schema.py +248 -0
  56. swiftapi/core/db/mixins.py +53 -0
  57. swiftapi/core/db/session.py +54 -0
  58. swiftapi/core/db/snapshot.py +33 -0
  59. swiftapi/core/db/tenant_model.py +43 -0
  60. swiftapi/core/db/tenant_router.py +114 -0
  61. swiftapi/core/db/types.py +109 -0
  62. swiftapi/core/db/unit_of_work.py +65 -0
  63. swiftapi/core/docs/__init__.py +0 -0
  64. swiftapi/core/docs/router.py +26 -0
  65. swiftapi/core/docs/tsgen.py +93 -0
  66. swiftapi/core/docs/ui.py +132 -0
  67. swiftapi/core/errors/__init__.py +0 -0
  68. swiftapi/core/errors/base.py +168 -0
  69. swiftapi/core/errors/codes.py +117 -0
  70. swiftapi/core/errors/handlers.py +155 -0
  71. swiftapi/core/errors/problem.py +58 -0
  72. swiftapi/core/errors/validation.py +11 -0
  73. swiftapi/core/framework_models.py +22 -0
  74. swiftapi/core/http/__init__.py +47 -0
  75. swiftapi/core/http/app.py +247 -0
  76. swiftapi/core/http/cors.py +100 -0
  77. swiftapi/core/http/idempotency.py +148 -0
  78. swiftapi/core/http/middleware/__init__.py +82 -0
  79. swiftapi/core/http/middleware/access_log.py +57 -0
  80. swiftapi/core/http/middleware/auth.py +105 -0
  81. swiftapi/core/http/middleware/body_limit.py +76 -0
  82. swiftapi/core/http/middleware/rate_limit.py +103 -0
  83. swiftapi/core/http/middleware/request_body.py +122 -0
  84. swiftapi/core/http/middleware/request_id.py +46 -0
  85. swiftapi/core/http/middleware/security_headers.py +46 -0
  86. swiftapi/core/http/middleware/tenant.py +93 -0
  87. swiftapi/core/http/middleware/timing.py +57 -0
  88. swiftapi/core/http/multipart.py +116 -0
  89. swiftapi/core/http/multipart_stream.py +216 -0
  90. swiftapi/core/http/openapi.py +148 -0
  91. swiftapi/core/http/pagination.py +55 -0
  92. swiftapi/core/http/params.py +302 -0
  93. swiftapi/core/http/request.py +145 -0
  94. swiftapi/core/http/responses.py +127 -0
  95. swiftapi/core/http/routing.py +200 -0
  96. swiftapi/core/http/types.py +86 -0
  97. swiftapi/core/http/uploads.py +222 -0
  98. swiftapi/core/messaging/__init__.py +0 -0
  99. swiftapi/core/messaging/base.py +33 -0
  100. swiftapi/core/messaging/consumer.py +57 -0
  101. swiftapi/core/messaging/factory.py +30 -0
  102. swiftapi/core/messaging/idempotency.py +61 -0
  103. swiftapi/core/messaging/inprocess.py +30 -0
  104. swiftapi/core/messaging/outbox.py +106 -0
  105. swiftapi/core/messaging/rabbitmq.py +186 -0
  106. swiftapi/core/messaging/relay.py +151 -0
  107. swiftapi/core/messaging/streams.py +141 -0
  108. swiftapi/core/observability/__init__.py +0 -0
  109. swiftapi/core/observability/archive.py +136 -0
  110. swiftapi/core/observability/context.py +102 -0
  111. swiftapi/core/observability/logging.py +192 -0
  112. swiftapi/core/observability/masking.py +74 -0
  113. swiftapi/core/observability/metrics.py +101 -0
  114. swiftapi/core/observability/volume.py +67 -0
  115. swiftapi/core/resilience/__init__.py +0 -0
  116. swiftapi/core/resilience/bulkhead.py +50 -0
  117. swiftapi/core/resilience/circuit_breaker.py +97 -0
  118. swiftapi/core/resilience/client.py +179 -0
  119. swiftapi/core/resilience/retry.py +59 -0
  120. swiftapi/core/security/__init__.py +0 -0
  121. swiftapi/core/security/jwt.py +78 -0
  122. swiftapi/core/security/principal.py +78 -0
  123. swiftapi/core/tenant/__init__.py +1 -0
  124. swiftapi/core/tenant/catalog.py +89 -0
  125. swiftapi/core/tenant/context.py +75 -0
  126. swiftapi/core/tenant/isolation.py +48 -0
  127. swiftapi/core/tenant/resolver.py +48 -0
  128. swiftapi/core/validation/__init__.py +0 -0
  129. swiftapi/core/validation/base.py +32 -0
  130. swiftapi/db.py +50 -0
  131. swiftapi/modules/__init__.py +0 -0
  132. swiftapi/modules/users/__init__.py +11 -0
  133. swiftapi/modules/users/api/__init__.py +0 -0
  134. swiftapi/modules/users/api/users.py +110 -0
  135. swiftapi/modules/users/crud/__init__.py +0 -0
  136. swiftapi/modules/users/crud/user.py +23 -0
  137. swiftapi/modules/users/errors.py +24 -0
  138. swiftapi/modules/users/mappers.py +19 -0
  139. swiftapi/modules/users/model/__init__.py +0 -0
  140. swiftapi/modules/users/model/user.py +37 -0
  141. swiftapi/modules/users/policies.py +19 -0
  142. swiftapi/modules/users/schema/__init__.py +0 -0
  143. swiftapi/modules/users/schema/user.py +40 -0
  144. swiftapi/modules/users/service/__init__.py +0 -0
  145. swiftapi/modules/users/service/user.py +107 -0
  146. swiftapi/py.typed +0 -0
  147. swiftapi/templates/__init__.py +0 -0
  148. swiftapi/templates/app_skeleton/README.md +17 -0
  149. swiftapi/templates/app_skeleton/__init__.py +1 -0
  150. swiftapi/templates/app_skeleton/api/__init__.py +23 -0
  151. swiftapi/templates/app_skeleton/api/health.py +12 -0
  152. swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
  153. swiftapi/templates/app_skeleton/model/__init__.py +1 -0
  154. swiftapi/templates/app_skeleton/router.py +16 -0
  155. swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
  156. swiftapi/templates/app_skeleton/service/__init__.py +1 -0
  157. swiftapi/templates/project/__init__.py +0 -0
  158. swiftapi/templates/project/api.py +135 -0
  159. swiftapi/templates/project/app.py +57 -0
  160. swiftapi/templates/project/endpoints/__init__.py +25 -0
  161. swiftapi/templates/project/events.py +43 -0
  162. swiftapi/templates/project/models.py +79 -0
  163. swiftapi/templates/project/resources/__init__.py +35 -0
  164. swiftapi/templates/project/schemas.py +45 -0
  165. swiftapi/templates/project/service.py +125 -0
  166. swiftapi/templates/project/settings.py +17 -0
  167. swiftapi/templates/project_skeleton/.env.example +5 -0
  168. swiftapi/templates/project_skeleton/.gitignore +6 -0
  169. swiftapi/templates/project_skeleton/README.md +25 -0
  170. swiftapi/templates/project_skeleton/__init__.py +1 -0
  171. swiftapi/templates/project_skeleton/app.py +26 -0
  172. swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
  173. swiftapi/templates/project_skeleton/common/__init__.py +4 -0
  174. swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
  175. swiftapi/templates/project_skeleton/conf/settings.py +73 -0
  176. swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
  177. swiftapi/templates/project_skeleton/models.py +12 -0
  178. swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
  179. swiftapi/templates/project_skeleton/router.py +46 -0
  180. swiftapi/templates/project_skeleton/script/start.sh +13 -0
  181. swiftapi/templates/project_skeleton/start.py +35 -0
  182. swiftapi/version.py +8 -0
  183. swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
  184. swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
  185. swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
  186. swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
  187. swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
File without changes
File without changes
@@ -0,0 +1,385 @@
1
+ """后台账号:口令哈希、角色、登录与锁定(架构文档 §22.9)。
2
+
3
+ 设计取舍:
4
+ - 口令用标准库 `scrypt`,不引第三方依赖;编码串自带参数,换参数不需要迁移;
5
+ - 角色只有三种,权限沿用 `Principal` 的权限模型(与 API 同一套判定);
6
+ - 账号状态、失败次数、锁定时间都落库,多进程/重启后仍然有效。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import base64
12
+ import hashlib
13
+ import hmac
14
+ import secrets
15
+ from dataclasses import dataclass
16
+ from datetime import UTC, datetime, timedelta
17
+ from enum import StrEnum
18
+ from uuid import UUID, uuid4
19
+
20
+ from sqlalchemy import select
21
+ from sqlalchemy.ext.asyncio import AsyncSession
22
+ from sqlalchemy.orm import Mapped, mapped_column
23
+
24
+ from swiftapi.core.security.principal import register_role
25
+ from swiftapi.db import BaseModel, ShortText, TimestampMixin, TZDateTime, UUIDType
26
+
27
+ # scrypt 参数:N=2^14 在 2026 年的服务器上约 40~60ms,足够挡住离线爆破
28
+ _SCRYPT_N = 2**14
29
+ _SCRYPT_R = 8
30
+ _SCRYPT_P = 1
31
+ _SCRYPT_DKLEN = 32
32
+ _PASSWORD_MIN = 8
33
+ _PASSWORD_MAX = 128
34
+
35
+
36
+ class AdminRole(StrEnum):
37
+ ADMIN = "admin"
38
+ OPERATOR = "admin_operator"
39
+ VIEWER = "admin_viewer"
40
+
41
+ @property
42
+ def label(self) -> str:
43
+ return {
44
+ AdminRole.ADMIN: "管理员",
45
+ AdminRole.OPERATOR: "运营",
46
+ AdminRole.VIEWER: "只读",
47
+ }[self]
48
+
49
+ @property
50
+ def permissions(self) -> frozenset[str]:
51
+ return _ROLE_PERMISSIONS[self]
52
+
53
+
54
+ _ROLE_PERMISSIONS: dict[AdminRole, frozenset[str]] = {
55
+ AdminRole.ADMIN: frozenset(
56
+ {
57
+ "admin:view",
58
+ "admin:create",
59
+ "admin:edit",
60
+ "admin:export",
61
+ "admin:manage",
62
+ "admin:dangerous",
63
+ }
64
+ ),
65
+ AdminRole.OPERATOR: frozenset({"admin:view", "admin:create", "admin:edit", "admin:export"}),
66
+ AdminRole.VIEWER: frozenset({"admin:view"}),
67
+ }
68
+
69
+ # 与 API 的角色体系共用一张表:这里注册后台专用角色(进程内一次)
70
+ for _role in (AdminRole.OPERATOR, AdminRole.VIEWER):
71
+ register_role(_role.value, _ROLE_PERMISSIONS[_role])
72
+
73
+
74
+ class AdminStatus(StrEnum):
75
+ ACTIVE = "active"
76
+ DISABLED = "disabled"
77
+
78
+
79
+ class AdminUser(BaseModel, TimestampMixin):
80
+ """后台账号。平台级表:跨租户,`tenant_slug` 只做登录后的租户归属。"""
81
+
82
+ __tablename__ = "admin_user"
83
+ __module_schema__ = "platform"
84
+
85
+ id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True, default=uuid4)
86
+ username: Mapped[str] = mapped_column(ShortText(64), unique=True, index=True)
87
+ password_hash: Mapped[str] = mapped_column(ShortText(255))
88
+ role: Mapped[str] = mapped_column(ShortText(32), default=AdminRole.ADMIN.value)
89
+ status: Mapped[str] = mapped_column(ShortText(16), default=AdminStatus.ACTIVE.value, index=True)
90
+ tenant_slug: Mapped[str | None] = mapped_column(ShortText(64), nullable=True, default=None)
91
+ last_login_at: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True, default=None)
92
+ failed_attempts: Mapped[int] = mapped_column(default=0)
93
+ locked_until: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True, default=None)
94
+ # 会话代次:改密/停用 +1,已签发的 Cookie 立即失效
95
+ session_epoch: Mapped[int] = mapped_column(default=0)
96
+
97
+ @property
98
+ def role_enum(self) -> AdminRole:
99
+ try:
100
+ return AdminRole(self.role)
101
+ except ValueError:
102
+ return AdminRole.VIEWER
103
+
104
+ @property
105
+ def is_active(self) -> bool:
106
+ return self.status == AdminStatus.ACTIVE.value
107
+
108
+ def is_locked(self, now: datetime | None = None) -> bool:
109
+ moment = now or datetime.now(UTC)
110
+ return self.locked_until is not None and self.locked_until > moment
111
+
112
+
113
+ # ---------------- 口令 ----------------
114
+
115
+
116
+ def _b64encode(raw: bytes) -> str:
117
+ return base64.urlsafe_b64encode(raw).decode().rstrip("=")
118
+
119
+
120
+ def _b64decode(text: str) -> bytes:
121
+ return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))
122
+
123
+
124
+ def hash_password(password: str) -> str:
125
+ """`scrypt$N$r$p$salt$hash`:参数随密文走,未来调参不影响老账号。"""
126
+ if not isinstance(password, str) or not password:
127
+ raise ValueError("口令不能为空")
128
+ salt = secrets.token_bytes(16)
129
+ digest = hashlib.scrypt(
130
+ password.encode("utf-8"),
131
+ salt=salt,
132
+ n=_SCRYPT_N,
133
+ r=_SCRYPT_R,
134
+ p=_SCRYPT_P,
135
+ dklen=_SCRYPT_DKLEN,
136
+ )
137
+ return f"scrypt${_SCRYPT_N}${_SCRYPT_R}${_SCRYPT_P}${_b64encode(salt)}${_b64encode(digest)}"
138
+
139
+
140
+ def verify_password(password: str, encoded: str) -> bool:
141
+ try:
142
+ scheme, n, r, p, salt, expected = encoded.split("$")
143
+ if scheme != "scrypt":
144
+ return False
145
+ digest = hashlib.scrypt(
146
+ (password or "").encode("utf-8"),
147
+ salt=_b64decode(salt),
148
+ n=int(n),
149
+ r=int(r),
150
+ p=int(p),
151
+ dklen=len(_b64decode(expected)),
152
+ )
153
+ return hmac.compare_digest(digest, _b64decode(expected))
154
+ except (ValueError, TypeError):
155
+ return False
156
+
157
+
158
+ # 未知账号也跑一次同成本校验,避免用响应时间枚举用户名
159
+ _DUMMY_HASH = hash_password(secrets.token_urlsafe(16))
160
+
161
+
162
+ def validate_password(password: str) -> str | None:
163
+ if len(password) < _PASSWORD_MIN:
164
+ return f"口令至少 {_PASSWORD_MIN} 位"
165
+ if len(password) > _PASSWORD_MAX:
166
+ return f"口令最长 {_PASSWORD_MAX} 位"
167
+ return None
168
+
169
+
170
+ # ---------------- 账号操作 ----------------
171
+
172
+
173
+ def normalize_username(username: str) -> str:
174
+ return (username or "").strip()
175
+
176
+
177
+ @dataclass(frozen=True, slots=True)
178
+ class AuthResult:
179
+ user: AdminUser | None = None
180
+ error: str | None = None # invalid / locked / disabled
181
+
182
+ @property
183
+ def ok(self) -> bool:
184
+ return self.user is not None
185
+
186
+
187
+ async def get_user_by_username(session: AsyncSession, username: str) -> AdminUser | None:
188
+ stmt = select(AdminUser).where(AdminUser.username == normalize_username(username))
189
+ return (await session.execute(stmt)).scalar_one_or_none()
190
+
191
+
192
+ async def authenticate(
193
+ session: AsyncSession,
194
+ username: str,
195
+ password: str,
196
+ *,
197
+ max_attempts: int = 5,
198
+ lockout_s: int = 900,
199
+ now: datetime | None = None,
200
+ ) -> AuthResult:
201
+ """校验口令并维护失败计数。
202
+
203
+ 失败原因对外只回 "invalid",锁定单独回 "locked"(提示等待,不暴露是否存在)。
204
+ """
205
+ moment = now or datetime.now(UTC)
206
+ user = await get_user_by_username(session, username)
207
+ if user is None:
208
+ verify_password(password, _DUMMY_HASH)
209
+ return AuthResult(error="invalid")
210
+
211
+ if user.is_locked(moment):
212
+ return AuthResult(error="locked")
213
+ if not user.is_active:
214
+ return AuthResult(error="disabled")
215
+
216
+ if not verify_password(password, user.password_hash):
217
+ user.failed_attempts = int(user.failed_attempts or 0) + 1
218
+ if lockout_s > 0 and user.failed_attempts >= max_attempts:
219
+ user.locked_until = moment + timedelta(seconds=lockout_s)
220
+ user.failed_attempts = 0
221
+ await session.flush()
222
+ return AuthResult(error="locked" if user.locked_until else "invalid")
223
+
224
+ user.failed_attempts = 0
225
+ user.locked_until = None
226
+ user.last_login_at = moment
227
+ await session.flush()
228
+ return AuthResult(user=user)
229
+
230
+
231
+ class LoginThrottle(BaseModel):
232
+ """按来源 IP 的登录节流(IP 只存哈希,不落原文)。"""
233
+
234
+ __tablename__ = "admin_login_throttle"
235
+ __module_schema__ = "platform"
236
+
237
+ ip_hash: Mapped[str] = mapped_column(ShortText(64), primary_key=True)
238
+ window_started: Mapped[datetime] = mapped_column(TZDateTime)
239
+ attempts: Mapped[int] = mapped_column(default=0)
240
+ blocked_until: Mapped[datetime | None] = mapped_column(TZDateTime, nullable=True, default=None)
241
+
242
+
243
+ def hash_ip(ip: str, secret: str) -> str:
244
+ return hashlib.sha256(f"{secret}:{ip}".encode()).hexdigest()[:32]
245
+
246
+
247
+ async def check_ip_throttle(
248
+ session: AsyncSession,
249
+ *,
250
+ ip_hash: str,
251
+ max_attempts: int,
252
+ window_s: int,
253
+ block_s: int,
254
+ now: datetime | None = None,
255
+ ) -> bool:
256
+ """返回 True 表示放行;False 表示该 IP 已被封禁(不再校验口令)。"""
257
+ moment = now or datetime.now(UTC)
258
+ row = await session.get(LoginThrottle, ip_hash)
259
+ if row is None:
260
+ return True
261
+ if row.blocked_until is not None and row.blocked_until > moment:
262
+ return False
263
+ if (moment - row.window_started).total_seconds() > window_s:
264
+ row.window_started = moment
265
+ row.attempts = 0
266
+ row.blocked_until = None
267
+ await session.flush()
268
+ return row.attempts < max_attempts
269
+
270
+
271
+ async def note_login_failure(
272
+ session: AsyncSession,
273
+ *,
274
+ ip_hash: str,
275
+ max_attempts: int,
276
+ window_s: int,
277
+ block_s: int,
278
+ now: datetime | None = None,
279
+ ) -> None:
280
+ moment = now or datetime.now(UTC)
281
+ row = await session.get(LoginThrottle, ip_hash)
282
+ if row is None:
283
+ row = LoginThrottle(ip_hash=ip_hash, window_started=moment, attempts=0)
284
+ session.add(row)
285
+ elif (moment - row.window_started).total_seconds() > window_s:
286
+ row.window_started = moment
287
+ row.attempts = 0
288
+ row.blocked_until = None
289
+ row.attempts = int(row.attempts or 0) + 1
290
+ if block_s > 0 and row.attempts >= max_attempts:
291
+ row.blocked_until = moment + timedelta(seconds=block_s)
292
+ await session.flush()
293
+
294
+
295
+ async def get_ip_attempts(session: AsyncSession, *, ip_hash: str) -> int:
296
+ row = await session.get(LoginThrottle, ip_hash)
297
+ return int(row.attempts) if row is not None else 0
298
+
299
+
300
+ async def prune_login_throttle(
301
+ session: AsyncSession,
302
+ *,
303
+ older_than_s: int = 86_400,
304
+ dry_run: bool = False,
305
+ now: datetime | None = None,
306
+ ) -> int:
307
+ """删除长期未活动的节流行(封禁已结束且窗口早于 `older_than_s`)。"""
308
+ moment = now or datetime.now(UTC)
309
+ cutoff = moment - timedelta(seconds=older_than_s)
310
+ rows = list((await session.execute(select(LoginThrottle))).scalars())
311
+ removed = 0
312
+ for row in rows:
313
+ blocked = row.blocked_until is not None and row.blocked_until > moment
314
+ if not blocked and row.window_started < cutoff:
315
+ if not dry_run:
316
+ await session.delete(row)
317
+ removed += 1
318
+ await session.flush()
319
+ return removed
320
+
321
+
322
+ async def reset_login_throttle(session: AsyncSession, *, ip_hash: str) -> None:
323
+ row = await session.get(LoginThrottle, ip_hash)
324
+ if row is not None:
325
+ row.attempts = 0
326
+ row.blocked_until = None
327
+ await session.flush()
328
+
329
+
330
+ async def create_user(
331
+ session: AsyncSession,
332
+ *,
333
+ username: str,
334
+ password: str,
335
+ role: AdminRole = AdminRole.ADMIN,
336
+ tenant_slug: str | None = None,
337
+ ) -> AdminUser:
338
+ name = normalize_username(username)
339
+ if not name:
340
+ raise ValueError("用户名不能为空")
341
+ if len(name) > 64:
342
+ raise ValueError("用户名最长 64 位")
343
+ problem = validate_password(password)
344
+ if problem:
345
+ raise ValueError(problem)
346
+ if await get_user_by_username(session, name) is not None:
347
+ raise ValueError(f"用户名已存在: {name}")
348
+
349
+ user = AdminUser(
350
+ id=uuid4(),
351
+ username=name,
352
+ password_hash=hash_password(password),
353
+ role=AdminRole(role).value,
354
+ status=AdminStatus.ACTIVE.value,
355
+ tenant_slug=tenant_slug or None,
356
+ )
357
+ session.add(user)
358
+ await session.flush()
359
+ return user
360
+
361
+
362
+ async def set_password(session: AsyncSession, user: AdminUser, password: str) -> None:
363
+ problem = validate_password(password)
364
+ if problem:
365
+ raise ValueError(problem)
366
+ user.password_hash = hash_password(password)
367
+ user.failed_attempts = 0
368
+ user.locked_until = None
369
+ user.session_epoch = int(user.session_epoch or 0) + 1
370
+ await session.flush()
371
+
372
+
373
+ __all__ = [
374
+ "AdminRole",
375
+ "AdminStatus",
376
+ "AdminUser",
377
+ "AuthResult",
378
+ "authenticate",
379
+ "create_user",
380
+ "hash_password",
381
+ "normalize_username",
382
+ "set_password",
383
+ "validate_password",
384
+ "verify_password",
385
+ ]
@@ -0,0 +1,203 @@
1
+ """后台审计:所有写操作留 before/after diff(架构文档 §22.7)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import dataclass
8
+ from datetime import date, datetime, time
9
+ from decimal import Decimal
10
+ from enum import Enum
11
+ from typing import Any
12
+ from uuid import UUID
13
+
14
+ from sqlalchemy import Index, Integer, func, select
15
+ from sqlalchemy.exc import IntegrityError, OperationalError
16
+ from sqlalchemy.ext.asyncio import AsyncSession
17
+ from sqlalchemy.orm import Mapped, mapped_column
18
+
19
+ from swiftapi.core.db.types import JSONType, ShortText, TZDateTime, UUIDType
20
+ from swiftapi.core.observability.logging import get_logger
21
+ from swiftapi.db import BaseModel
22
+
23
+ logger = get_logger("swiftapi.audit")
24
+ GENESIS = "0" * 64
25
+
26
+
27
+ class AdminAudit(BaseModel):
28
+ __tablename__ = "admin_audit"
29
+ __module_schema__ = "platform"
30
+
31
+ id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True)
32
+ actor_id: Mapped[str] = mapped_column(ShortText(64), index=True)
33
+ action: Mapped[str] = mapped_column(ShortText(32))
34
+ model: Mapped[str] = mapped_column(ShortText(64), index=True)
35
+ object_id: Mapped[str] = mapped_column(ShortText(64))
36
+ changes: Mapped[dict[str, Any]] = mapped_column(JSONType)
37
+ trace_id: Mapped[str | None] = mapped_column(ShortText(64), default=None)
38
+ # 哈希链:篡改/删除任意一行都会断链(DBA 改库也能被发现)
39
+ seq: Mapped[int] = mapped_column(Integer, default=0, index=True)
40
+ prev_hash: Mapped[str] = mapped_column(ShortText(64), default=GENESIS)
41
+ hash: Mapped[str] = mapped_column(ShortText(64), default="")
42
+ created_at: Mapped[datetime] = mapped_column(
43
+ TZDateTime, server_default=func.now(), nullable=False
44
+ )
45
+
46
+ # 并发写也不能出现重号:唯一索引 + record() 的 savepoint 重试
47
+ __table_args__ = (Index("uq_admin_audit_seq", "seq", unique=True),)
48
+
49
+
50
+ def _jsonable(value: Any) -> Any:
51
+ """把 diff 值收敛成 JSON 可序列化类型(UUID/时间/枚举/Decimal 等)。"""
52
+ if value is None or isinstance(value, (str, int, float, bool)):
53
+ return value
54
+ if isinstance(value, (UUID, datetime, date, time, Decimal)):
55
+ return str(value)
56
+ if isinstance(value, Enum):
57
+ return _jsonable(value.value)
58
+ if isinstance(value, dict):
59
+ return {str(key): _jsonable(item) for key, item in value.items()}
60
+ if isinstance(value, (list, tuple, set, frozenset)):
61
+ return [_jsonable(item) for item in value]
62
+ if isinstance(value, bytes):
63
+ return value.hex()
64
+ return str(value)
65
+
66
+
67
+ def diff_changes(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
68
+ changes: dict[str, Any] = {}
69
+ for key, new_value in after.items():
70
+ old_value = before.get(key)
71
+ if str(old_value) != str(new_value):
72
+ changes[key] = {"before": _jsonable(old_value), "after": _jsonable(new_value)}
73
+ return changes
74
+
75
+
76
+ def _digest(prev_hash: str, payload: dict[str, Any]) -> str:
77
+ canonical = json.dumps(
78
+ payload, ensure_ascii=False, sort_keys=True, separators=(",", ":"), default=str
79
+ )
80
+ return hashlib.sha256((prev_hash + canonical).encode()).hexdigest()
81
+
82
+
83
+ async def last_hash(session: AsyncSession) -> str:
84
+ stmt = select(AdminAudit.hash).order_by(AdminAudit.seq.desc()).limit(1)
85
+ value = (await session.execute(stmt)).scalar_one_or_none()
86
+ return value or GENESIS
87
+
88
+
89
+ async def _next_seq(session: AsyncSession) -> int:
90
+ value = (await session.execute(select(func.max(AdminAudit.seq)))).scalar()
91
+ return int(value or 0) + 1
92
+
93
+
94
+ async def record(
95
+ session: AsyncSession,
96
+ *,
97
+ actor_id: str,
98
+ action: str,
99
+ model: str,
100
+ object_id: str,
101
+ changes: dict[str, Any],
102
+ trace_id: str | None = None,
103
+ ) -> None:
104
+ from uuid import uuid4
105
+
106
+ entry_id = uuid4()
107
+ prev = ""
108
+ next_seq = 0
109
+ payload: dict[str, Any] = {}
110
+ digest = ""
111
+ for attempt in range(5):
112
+ try:
113
+ # savepoint:撞唯一索引时只回滚这一次插入,不污染外层事务
114
+ async with session.begin_nested():
115
+ prev = await last_hash(session)
116
+ next_seq = await _next_seq(session)
117
+ payload = {
118
+ "id": str(entry_id),
119
+ "actor_id": actor_id,
120
+ "action": action,
121
+ "model": model,
122
+ "object_id": object_id,
123
+ "changes": changes,
124
+ "trace_id": trace_id,
125
+ "seq": next_seq,
126
+ }
127
+ digest = _digest(prev, payload)
128
+ session.add(
129
+ AdminAudit(
130
+ id=entry_id,
131
+ actor_id=actor_id,
132
+ action=action,
133
+ model=model,
134
+ object_id=object_id,
135
+ changes=changes,
136
+ trace_id=trace_id,
137
+ seq=next_seq,
138
+ prev_hash=prev,
139
+ hash=digest,
140
+ )
141
+ )
142
+ await session.flush()
143
+ break
144
+ except IntegrityError:
145
+ if attempt == 4:
146
+ raise
147
+ continue
148
+ except OperationalError:
149
+ # SQLite 并发写会报 "database is locked",此时事务状态不可靠:
150
+ # 直接上抛,由请求级重试处理(生产用 PG,不会走到这里)
151
+ raise
152
+
153
+ # 同时写一条结构化日志:外部日志管道是"防 DBA 改库"的唯一边界
154
+ logger.info("audit.write", **payload, prev_hash=prev, hash=digest)
155
+
156
+
157
+ @dataclass(frozen=True, slots=True)
158
+ class ChainVerification:
159
+ ok: bool
160
+ checked: int
161
+ broken_at: str | None = None
162
+ reason: str = ""
163
+
164
+
165
+ async def verify_chain(session: AsyncSession) -> ChainVerification:
166
+ """逐行重算哈希链;任何改动/删除都会让 `prev_hash` 对不上。"""
167
+ stmt = select(AdminAudit).order_by(AdminAudit.seq.asc())
168
+ rows = list((await session.execute(stmt)).scalars())
169
+
170
+ prev = GENESIS
171
+ last_seq = 0
172
+ for index, row in enumerate(rows):
173
+ if row.seq <= last_seq:
174
+ return ChainVerification(False, index + 1, str(row.id), "seq 非单调递增(可能重号)")
175
+ payload = {
176
+ "id": str(row.id),
177
+ "actor_id": row.actor_id,
178
+ "action": row.action,
179
+ "model": row.model,
180
+ "object_id": row.object_id,
181
+ "changes": row.changes,
182
+ "trace_id": row.trace_id,
183
+ "seq": row.seq,
184
+ }
185
+ if row.prev_hash != prev:
186
+ return ChainVerification(False, index + 1, str(row.id), "prev_hash 与上一行不连续")
187
+ if row.hash != _digest(prev, payload):
188
+ return ChainVerification(False, index + 1, str(row.id), "内容与 hash 不匹配")
189
+ prev = row.hash
190
+ last_seq = row.seq
191
+
192
+ return ChainVerification(True, len(rows))
193
+
194
+
195
+ __all__ = [
196
+ "GENESIS",
197
+ "AdminAudit",
198
+ "ChainVerification",
199
+ "diff_changes",
200
+ "last_hash",
201
+ "record",
202
+ "verify_chain",
203
+ ]
@@ -0,0 +1,53 @@
1
+ """后台维护任务:定时清理登录节流表。
2
+
3
+ 为什么放进程内而不是只给 cron:
4
+ - 部署面更小(容器/无 cron 的环境也能跑);
5
+ - 多副本下每个副本各跑一次也无害——删除是幂等的(条件是"封禁已结束 + 窗口过期")。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+
12
+ from sqlalchemy.exc import OperationalError
13
+
14
+ from swiftapi.config.settings import Settings
15
+ from swiftapi.core.admin.accounts import prune_login_throttle
16
+ from swiftapi.core.db.engine import Database
17
+ from swiftapi.core.observability.logging import get_logger
18
+
19
+ logger = get_logger("swiftapi.admin")
20
+
21
+
22
+ async def prune_throttle_once(database: Database, settings: Settings) -> int:
23
+ try:
24
+ async with database.session_factory() as session:
25
+ removed = await prune_login_throttle(
26
+ session, older_than_s=settings.admin.throttle_retention_s
27
+ )
28
+ await session.commit()
29
+ except OperationalError as exc:
30
+ if "no such table" in str(exc).lower():
31
+ # 还没跑迁移:这不是故障,别把 SQL 打到 warning 里吓人
32
+ logger.info(
33
+ "admin.throttle_table_missing",
34
+ hint="执行 swiftapi db upgrade 建表后即可自动清理",
35
+ )
36
+ else:
37
+ logger.warning("admin.throttle_prune_failed", error=str(exc))
38
+ return 0
39
+ except Exception as exc: # 维护任务失败不能影响服务
40
+ logger.warning("admin.throttle_prune_failed", error=str(exc))
41
+ return 0
42
+ if removed:
43
+ logger.info("admin.throttle_pruned", removed=removed)
44
+ return removed
45
+
46
+
47
+ async def throttle_prune_loop(database: Database, settings: Settings) -> None:
48
+ while True:
49
+ await asyncio.sleep(settings.admin.throttle_prune_interval_s)
50
+ await prune_throttle_once(database, settings)
51
+
52
+
53
+ __all__ = ["prune_throttle_once", "throttle_prune_loop"]
@@ -0,0 +1,53 @@
1
+ """后台注册表:显式注册,不做自动扫描(与路由注册同一原则)。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel as PydanticModel
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class AdminModel:
13
+ slug: str
14
+ model: type[Any]
15
+ form_schema: type[PydanticModel] | None
16
+ list_fields: tuple[str, ...] = () # 空 = 展示模型的全部列
17
+ search_field: str | None = None
18
+ can_create: bool = True
19
+ can_edit: bool = True
20
+ title: str | None = None
21
+ # 新建用的字段白名单;不配置时复用 form_schema(只读字段/运营字段可以分开)
22
+ create_schema: type[PydanticModel] | None = None
23
+
24
+ @property
25
+ def label(self) -> str:
26
+ return self.title or self.slug
27
+
28
+ @property
29
+ def create_form_schema(self) -> type[PydanticModel] | None:
30
+ return self.create_schema or self.form_schema
31
+
32
+ @property
33
+ def table_name(self) -> str:
34
+ return str(getattr(self.model, "__tablename__", self.model.__name__.lower()))
35
+
36
+
37
+ class AdminRegistry:
38
+ def __init__(self) -> None:
39
+ self._items: dict[str, AdminModel] = {}
40
+
41
+ def register(self, item: AdminModel) -> None:
42
+ if item.slug in self._items:
43
+ raise ValueError(f"后台模型重复注册: {item.slug}")
44
+ self._items[item.slug] = item
45
+
46
+ def get(self, slug: str) -> AdminModel | None:
47
+ return self._items.get(slug)
48
+
49
+ def all(self) -> list[AdminModel]:
50
+ return list(self._items.values())
51
+
52
+
53
+ __all__ = ["AdminModel", "AdminRegistry"]