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
@@ -0,0 +1,148 @@
1
+ """HTTP 幂等:`Idempotency-Key` + 请求指纹 + 响应回放(架构文档 §10.4)。
2
+
3
+ 语义:
4
+ - 同 key + 同请求体 → 回放首次响应(`Idempotent-Replayed: true`),不重复执行;
5
+ - 同 key + 不同请求体 → 409 `IDEMPOTENCY_KEY_REUSED`;
6
+ - 记录与业务写入**同一个事务**,不会出现"业务成功但没记住 key"。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import json
13
+ from datetime import datetime
14
+ from typing import Any
15
+ from uuid import UUID, uuid4
16
+
17
+ from pydantic import BaseModel as PydanticModel
18
+ from sqlalchemy import Index, select
19
+ from sqlalchemy.exc import IntegrityError
20
+ from sqlalchemy.ext.asyncio import AsyncSession
21
+ from sqlalchemy.orm import Mapped, mapped_column
22
+
23
+ from swiftapi.core.db.types import JSONType, ShortText, TZDateTime, UUIDType
24
+ from swiftapi.core.errors.base import Conflict, InvalidArgument
25
+ from swiftapi.core.errors.codes import ErrorCode
26
+ from swiftapi.core.http.responses import JSONResponse, Response
27
+ from swiftapi.db import BaseModel
28
+
29
+ HEADER = "idempotency-key"
30
+ REPLAY_HEADER = "idempotent-replayed"
31
+ MAX_KEY_LENGTH = 128
32
+
33
+
34
+ class IdempotencyKey(BaseModel):
35
+ __tablename__ = "idempotency_key"
36
+ __module_schema__ = "platform"
37
+ # 平台级表,但需要记录租户维度(允许跨租户清理/审计)
38
+ __allow_tenant_column__ = True
39
+
40
+ id: Mapped[UUID] = mapped_column(UUIDType, primary_key=True, default=uuid4)
41
+ tenant_id: Mapped[UUID] = mapped_column(UUIDType, index=True)
42
+ key: Mapped[str] = mapped_column(ShortText(128))
43
+ endpoint: Mapped[str] = mapped_column(ShortText(200))
44
+ request_hash: Mapped[str] = mapped_column(ShortText(64))
45
+ status_code: Mapped[int] = mapped_column()
46
+ response_body: Mapped[dict[str, Any]] = mapped_column(JSONType)
47
+ created_at: Mapped[datetime] = mapped_column(TZDateTime)
48
+
49
+ __table_args__ = (
50
+ Index("uq_idempotency_key_scope", "tenant_id", "key", "endpoint", unique=True),
51
+ )
52
+
53
+
54
+ def hash_payload(payload: PydanticModel | dict[str, Any] | None) -> str:
55
+ if payload is None:
56
+ data: Any = {}
57
+ elif isinstance(payload, PydanticModel):
58
+ data = payload.model_dump(mode="json", exclude_unset=False)
59
+ else:
60
+ data = payload
61
+ canonical = json.dumps(data, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
62
+ return hashlib.sha256(canonical.encode()).hexdigest()
63
+
64
+
65
+ def _validate_key(key: str) -> None:
66
+ if not key or len(key) > MAX_KEY_LENGTH:
67
+ raise InvalidArgument(f"Idempotency-Key 长度必须在 1~{MAX_KEY_LENGTH} 之间")
68
+
69
+
70
+ async def load_replay(
71
+ session: AsyncSession,
72
+ *,
73
+ tenant_id: UUID,
74
+ key: str,
75
+ endpoint: str,
76
+ request_hash: str,
77
+ ) -> IdempotencyKey | None:
78
+ _validate_key(key)
79
+ record = (
80
+ await session.execute(
81
+ select(IdempotencyKey).where(
82
+ IdempotencyKey.tenant_id == tenant_id,
83
+ IdempotencyKey.key == key,
84
+ IdempotencyKey.endpoint == endpoint,
85
+ )
86
+ )
87
+ ).scalar_one_or_none()
88
+ if record is None:
89
+ return None
90
+ if record.request_hash != request_hash:
91
+ raise Conflict(
92
+ "相同的 Idempotency-Key 却带着不同的请求体",
93
+ code=ErrorCode.IDEMPOTENCY_KEY_REUSED,
94
+ )
95
+ return record
96
+
97
+
98
+ async def remember(
99
+ session: AsyncSession,
100
+ *,
101
+ tenant_id: UUID,
102
+ key: str,
103
+ endpoint: str,
104
+ request_hash: str,
105
+ status_code: int,
106
+ body: dict[str, Any],
107
+ ) -> None:
108
+ from datetime import UTC, datetime
109
+
110
+ _validate_key(key)
111
+ session.add(
112
+ IdempotencyKey(
113
+ tenant_id=tenant_id,
114
+ key=key,
115
+ endpoint=endpoint,
116
+ request_hash=request_hash,
117
+ status_code=status_code,
118
+ response_body=body,
119
+ created_at=datetime.now(UTC),
120
+ )
121
+ )
122
+ try:
123
+ await session.flush()
124
+ except IntegrityError as exc:
125
+ # 并发同 key:另一个请求已写入 → 让调用方重试(重试会命中回放)
126
+ raise Conflict(
127
+ "同一 Idempotency-Key 正在处理,请稍后重试",
128
+ code=ErrorCode.IDEMPOTENCY_IN_PROGRESS,
129
+ ) from exc
130
+
131
+
132
+ def replay_response(record: IdempotencyKey) -> Response:
133
+ return JSONResponse(
134
+ record.response_body,
135
+ status_code=record.status_code,
136
+ headers={REPLAY_HEADER: "true"},
137
+ )
138
+
139
+
140
+ __all__ = [
141
+ "HEADER",
142
+ "REPLAY_HEADER",
143
+ "IdempotencyKey",
144
+ "hash_payload",
145
+ "load_replay",
146
+ "remember",
147
+ "replay_response",
148
+ ]
@@ -0,0 +1,82 @@
1
+ """中间件装配:顺序即安全边界,不可随意调整(架构文档 §9.2)。
2
+
3
+ Starlette 的 `add_middleware` 后加者在外层,因此这里按"内 → 外"顺序添加:
4
+ access_log → timing → body_limit → security_headers → request_id
5
+
6
+ 为什么不直接用框架自带的 `max_body_size`:它在超限时返回 text/plain 的 413,
7
+ 破坏"所有错误都是 problem+json"的契约,故保留自研实现(见 body_limit.py)。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import TYPE_CHECKING
13
+
14
+ from swiftapi.config.environments import is_production
15
+ from swiftapi.config.settings import Settings
16
+ from swiftapi.core.admin.session import AdminSessionCodec
17
+ from swiftapi.core.http.cors import CORSMiddleware
18
+ from swiftapi.core.http.middleware.access_log import AccessLogMiddleware
19
+ from swiftapi.core.http.middleware.auth import AuthMiddleware
20
+ from swiftapi.core.http.middleware.body_limit import BodyLimitMiddleware
21
+ from swiftapi.core.http.middleware.rate_limit import RateLimitMiddleware
22
+ from swiftapi.core.http.middleware.request_body import RequestBodyLogMiddleware
23
+ from swiftapi.core.http.middleware.request_id import RequestIDMiddleware
24
+ from swiftapi.core.http.middleware.security_headers import SecurityHeadersMiddleware
25
+ from swiftapi.core.http.middleware.tenant import TenantMiddleware
26
+ from swiftapi.core.http.middleware.timing import TimingMiddleware
27
+
28
+ if TYPE_CHECKING: # pragma: no cover
29
+ from swiftapi.core.http.app import App
30
+
31
+ __all__ = [
32
+ "AccessLogMiddleware",
33
+ "AuthMiddleware",
34
+ "BodyLimitMiddleware",
35
+ "CORSMiddleware",
36
+ "RateLimitMiddleware",
37
+ "RequestBodyLogMiddleware",
38
+ "RequestIDMiddleware",
39
+ "SecurityHeadersMiddleware",
40
+ "TenantMiddleware",
41
+ "TimingMiddleware",
42
+ "install_default_middlewares",
43
+ ]
44
+
45
+
46
+ def install_default_middlewares(
47
+ app: App,
48
+ settings: Settings,
49
+ *,
50
+ tenant_resolver: object | None = None,
51
+ auth_verifier: object | None = None,
52
+ rate_limit_cache: object | None = None,
53
+ ) -> None:
54
+ if settings.observability.log_request_body:
55
+ app.add_middleware(RequestBodyLogMiddleware, settings=settings)
56
+ app.add_middleware(AccessLogMiddleware, enabled=settings.server.access_log)
57
+ app.add_middleware(TimingMiddleware)
58
+ app.add_middleware(BodyLimitMiddleware, max_bytes=settings.server.max_request_body_bytes)
59
+ app.add_middleware(SecurityHeadersMiddleware, hsts=is_production(settings))
60
+ if settings.security.cors_allow_origins:
61
+ app.add_middleware(
62
+ CORSMiddleware,
63
+ allow_origins=settings.security.cors_allow_origins,
64
+ allow_credentials=True,
65
+ )
66
+ if rate_limit_cache is not None:
67
+ app.add_middleware(
68
+ RateLimitMiddleware, settings=settings, cache=rate_limit_cache
69
+ )
70
+ if tenant_resolver is not None:
71
+ app.add_middleware(
72
+ TenantMiddleware, settings=settings, resolver=tenant_resolver
73
+ )
74
+ if auth_verifier is not None or settings.admin.enabled:
75
+ codec = AdminSessionCodec(settings) if settings.admin.enabled else None
76
+ app.add_middleware(
77
+ AuthMiddleware,
78
+ verifier=auth_verifier,
79
+ admin_codec=codec,
80
+ admin_path=settings.admin.path,
81
+ )
82
+ app.add_middleware(RequestIDMiddleware)
@@ -0,0 +1,57 @@
1
+ """结构化访问日志(纯 ASGI,最内层)。
2
+
3
+ 字段固定:method / path / route / status / duration_ms / trace_id / request_id。
4
+ trace_id 与 request_id 由 context 注入,这里不重复传参。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+
11
+ import structlog
12
+
13
+ from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
14
+
15
+ logger = structlog.get_logger("swiftapi.access")
16
+
17
+ _NOISY_PATHS = frozenset({"/livez", "/readyz", "/metrics", "/favicon.ico"})
18
+
19
+
20
+ class AccessLogMiddleware:
21
+ def __init__(self, app: ASGIApp, *, enabled: bool = True) -> None:
22
+ self.app = app
23
+ self.enabled = enabled
24
+
25
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
26
+ if not self.enabled or scope["type"] != "http":
27
+ await self.app(scope, receive, send)
28
+ return
29
+
30
+ started = time.perf_counter()
31
+ status = 500
32
+
33
+ async def send_capture(message: Message) -> None:
34
+ nonlocal status
35
+ if message["type"] == "http.response.start":
36
+ status = int(message["status"])
37
+ await send(message)
38
+
39
+ try:
40
+ await self.app(scope, receive, send_capture)
41
+ finally:
42
+ duration_ms = round((time.perf_counter() - started) * 1000, 3)
43
+ route = scope.get("route")
44
+ route_path = getattr(route, "path", None) or scope.get("path", "-")
45
+ path = scope.get("path", "-")
46
+ emit = logger.debug if path in _NOISY_PATHS and status < 400 else logger.info
47
+ if status >= 500:
48
+ emit = logger.error
49
+ emit(
50
+ "http.request",
51
+ method=scope.get("method", "-"),
52
+ path=path,
53
+ route=route_path,
54
+ status=status,
55
+ duration_ms=duration_ms,
56
+ client=(scope.get("client") or ("-", 0))[0],
57
+ )
@@ -0,0 +1,105 @@
1
+ """认证中间件:Bearer JWT / 后台会话 Cookie → Principal + tenant claim。
2
+
3
+ 顺序与安全边界:
4
+ - 带了 Bearer 但无效 → 直接 401,避免"坏令牌被当作匿名";
5
+ - 没带 Bearer 且路径在后台前缀下 → 尝试后台 Cookie;Cookie 无效不在这里报错,
6
+ 由后台路由决定是跳登录页还是 401(登录页本身必须可访问);
7
+ - 后台 Cookie 只对 `admin.path` 生效,不污染业务 API。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from swiftapi.core.admin.session import COOKIE_NAME, AdminSessionCodec
13
+ from swiftapi.core.errors.base import AppError
14
+ from swiftapi.core.errors.codes import ErrorCode
15
+ from swiftapi.core.errors.handlers import problem_response
16
+ from swiftapi.core.http.request import Request
17
+ from swiftapi.core.http.types import ASGIApp, Receive, Scope, Send
18
+ from swiftapi.core.security.jwt import JwtVerifier
19
+ from swiftapi.core.security.principal import Principal
20
+
21
+
22
+ class AuthMiddleware:
23
+ def __init__(
24
+ self,
25
+ app: ASGIApp,
26
+ *,
27
+ verifier: JwtVerifier | None,
28
+ admin_codec: AdminSessionCodec | None = None,
29
+ admin_path: str = "",
30
+ ) -> None:
31
+ self.app = app
32
+ self.verifier = verifier
33
+ self.admin_codec = admin_codec
34
+ self.admin_path = admin_path.rstrip("/")
35
+
36
+ def _is_admin_path(self, path: str) -> bool:
37
+ if not self.admin_path:
38
+ return False
39
+ return path == self.admin_path or path.startswith(f"{self.admin_path}/")
40
+
41
+ def _admin_claims(self, request: Request) -> None:
42
+ if self.admin_codec is None:
43
+ return
44
+ token = request.cookies.get(COOKIE_NAME)
45
+ if not token:
46
+ return
47
+ claims = self.admin_codec.verify(token)
48
+ if claims is None:
49
+ return
50
+ request.state["admin_claims"] = claims
51
+ request.state["principal"] = Principal(
52
+ subject=claims.user_id,
53
+ roles=frozenset({claims.role}),
54
+ tenants=frozenset({claims.tenant_slug}) if claims.tenant_slug else frozenset(),
55
+ )
56
+ if claims.tenant_slug:
57
+ request.state["tenant_claim"] = claims.tenant_slug
58
+
59
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
60
+ if scope["type"] != "http":
61
+ await self.app(scope, receive, send)
62
+ return
63
+
64
+ request = Request(scope, receive)
65
+ authorization = request.headers.get("authorization") or ""
66
+ if not authorization.lower().startswith("bearer "):
67
+ if self._is_admin_path(request.path):
68
+ self._admin_claims(request)
69
+ await self.app(scope, receive, send)
70
+ return
71
+
72
+ if self.verifier is None: # 未配置 JWT:只支持后台会话
73
+ await self.app(scope, receive, send)
74
+ return
75
+
76
+ token = authorization[7:].strip()
77
+ try:
78
+ claims = self.verifier.verify(token)
79
+ except AppError as exc:
80
+ response = problem_response(
81
+ exc.code,
82
+ detail=exc.detail,
83
+ instance=request.path,
84
+ status=exc.status,
85
+ )
86
+ await response(scope, receive, send)
87
+ return
88
+ except Exception: # 兜底:任何校验异常都按未认证处理
89
+ response = problem_response(
90
+ ErrorCode.UNAUTHENTICATED, detail="令牌无效", instance=request.path
91
+ )
92
+ await response(scope, receive, send)
93
+ return
94
+
95
+ request.state["principal"] = Principal(
96
+ subject=claims.subject,
97
+ roles=claims.roles,
98
+ tenants=claims.tenant_slugs,
99
+ )
100
+ if claims.tenant_slug:
101
+ request.state["tenant_claim"] = claims.tenant_slug
102
+ await self.app(scope, receive, send)
103
+
104
+
105
+ __all__ = ["AuthMiddleware"]
@@ -0,0 +1,76 @@
1
+ """请求体大小限制(纯 ASGI)。
2
+
3
+ 为什么不用框架内置的 `max_body_size`:Starlette 的 `RequestBodyLimitMiddleware`
4
+ 在超限时直接返回 `text/plain` 的 413,破坏"所有错误都是 problem+json"的契约。
5
+ 这里保留自研实现,换取错误格式一致。
6
+
7
+ 策略:
8
+ 1. 有 `Content-Length` 且超限 → 直接 413,不读 body;
9
+ 2. 无 `Content-Length`(chunked)→ 包装 receive 计数,超限抛 `PayloadTooLarge`,
10
+ 由本中间件捕获后写回 413(此时响应尚未开始,可安全写回)。
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from swiftapi.core.errors.base import PayloadTooLarge
16
+ from swiftapi.core.errors.codes import ErrorCode
17
+ from swiftapi.core.errors.problem import build_problem
18
+ from swiftapi.core.http.responses import JSONResponse
19
+ from swiftapi.core.http.types import ASGIApp, Headers, Message, Receive, Scope, Send
20
+
21
+ PROBLEM_MEDIA_TYPE = "application/problem+json"
22
+
23
+
24
+ def _too_large_response(limit: int, instance: str) -> JSONResponse:
25
+ payload = build_problem(
26
+ ErrorCode.PAYLOAD_TOO_LARGE,
27
+ detail=f"请求体超过上限 {limit} 字节",
28
+ instance=instance,
29
+ )
30
+ return JSONResponse(status_code=413, content=payload, media_type=PROBLEM_MEDIA_TYPE)
31
+
32
+
33
+ class BodyLimitMiddleware:
34
+ def __init__(self, app: ASGIApp, *, max_bytes: int) -> None:
35
+ self.app = app
36
+ self.max_bytes = max_bytes
37
+
38
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
39
+ if scope["type"] != "http":
40
+ await self.app(scope, receive, send)
41
+ return
42
+
43
+ declared = Headers.from_scope(scope).get("content-length")
44
+ if declared is not None:
45
+ try:
46
+ declared_size = int(declared)
47
+ except ValueError:
48
+ declared_size = 0
49
+ if declared_size > self.max_bytes:
50
+ await _too_large_response(self.max_bytes, scope["path"])(scope, receive, send)
51
+ return
52
+
53
+ received = 0
54
+ started = False
55
+
56
+ async def limited_receive() -> Message:
57
+ nonlocal received
58
+ message = await receive()
59
+ if message["type"] == "http.request":
60
+ received += len(message.get("body", b""))
61
+ if received > self.max_bytes:
62
+ raise PayloadTooLarge(f"请求体超过上限 {self.max_bytes} 字节")
63
+ return message
64
+
65
+ async def guarded_send(message: Message) -> None:
66
+ nonlocal started
67
+ if message["type"] == "http.response.start":
68
+ started = True
69
+ await send(message)
70
+
71
+ try:
72
+ await self.app(scope, limited_receive, guarded_send)
73
+ except PayloadTooLarge:
74
+ if started: # 响应已开始,无法再改状态码,交给上层兜底
75
+ raise
76
+ await _too_large_response(self.max_bytes, scope["path"])(scope, receive, send)
@@ -0,0 +1,103 @@
1
+ """限流:固定 1s 窗口计数(原子 incr),缓存不可用时回落进程内。
2
+
3
+ 为什么不是严格令牌桶:跨实例的精确令牌桶需要 Redis Lua 脚本;
4
+ P4 先用"每秒窗口计数"覆盖突发保护,语义在文档中写明(边界可能双倍放行)。
5
+ key 优先级:租户 > 用户 > IP —— 先限大客户整体,再限个人,最后限来源。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+
12
+ from swiftapi.config.settings import Settings
13
+ from swiftapi.core.cache.base import CacheBackend
14
+ from swiftapi.core.cache.null import NullCache
15
+ from swiftapi.core.errors.codes import ErrorCode
16
+ from swiftapi.core.errors.handlers import problem_response
17
+ from swiftapi.core.http.request import Request
18
+ from swiftapi.core.http.types import ASGIApp, Receive, Scope, Send
19
+ from swiftapi.core.observability.logging import get_logger
20
+ from swiftapi.core.security.principal import Principal
21
+
22
+ logger = get_logger("swiftapi.rate_limit")
23
+
24
+
25
+ class RateLimitMiddleware:
26
+ def __init__(self, app: ASGIApp, *, settings: Settings, cache: CacheBackend) -> None:
27
+ self.app = app
28
+ self.settings = settings
29
+ self.cache = cache
30
+ self._local: dict[str, tuple[int, int]] = {}
31
+ if isinstance(cache, NullCache) and settings.server.workers > 1:
32
+ # 进程内计数在多 worker 下会被放大 N 倍(N = worker 数)
33
+ logger.warning(
34
+ "rate_limit.per_process_counter",
35
+ workers=settings.server.workers,
36
+ hint="多进程部署请启用共享缓存(cache.backend=redis),否则实际配额 = rps × workers",
37
+ )
38
+
39
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
40
+ if scope["type"] != "http" or not self.settings.security.rate_limit.enabled:
41
+ await self.app(scope, receive, send)
42
+ return
43
+
44
+ request = Request(scope, receive)
45
+ identity, limit = self._identity_and_limit(request)
46
+ if limit <= 0:
47
+ await self.app(scope, receive, send)
48
+ return
49
+
50
+ window = int(time.time())
51
+ key = f"rl:{identity}:{window}"
52
+ count = await self._increment(key, window)
53
+ if count > limit:
54
+ response = problem_response(
55
+ ErrorCode.RATE_LIMITED,
56
+ detail=f"超出配额 {limit}/s({identity})",
57
+ instance=request.path,
58
+ headers={"Retry-After": "1"},
59
+ )
60
+ await response(scope, receive, send)
61
+ return
62
+
63
+ await self.app(scope, receive, send)
64
+
65
+ def _identity_and_limit(self, request: Request) -> tuple[str, int]:
66
+ limits = self.settings.security.rate_limit
67
+ # 只信任已解析的租户(中间件顺序保证 tenant 已就绪);
68
+ # 绝不能直接读 X-Tenant-Id —— 攻击者换头就是一个新桶。
69
+ context = request.state.get("tenant")
70
+ tenant_slug = getattr(context, "slug", None) or request.state.get("tenant_claim")
71
+ if tenant_slug:
72
+ return f"t:{tenant_slug}", limits.tenant_rps
73
+
74
+ principal = request.state.get("principal")
75
+ if isinstance(principal, Principal):
76
+ return f"u:{principal.subject}", limits.user_rps
77
+
78
+ client = request.client
79
+ return f"ip:{client[0] if client else 'unknown'}", limits.ip_rps
80
+
81
+ async def _increment(self, key: str, window: int) -> int:
82
+ if isinstance(self.cache, NullCache):
83
+ # 缓存关闭时不能调 NullCache.incr(它恒返回 1,限流会静默失效)
84
+ return self._local_increment(key, window)
85
+ try:
86
+ return await self.cache.incr(key, ttl_s=2)
87
+ except Exception:
88
+ # 缓存不可用:降级为进程内计数(宁有限流也不放行洪水)
89
+ return self._local_increment(key, window)
90
+
91
+ def _local_increment(self, key: str, window: int) -> int:
92
+ current_window, count = self._local.get(key, (window, 0))
93
+ if current_window != window:
94
+ count = 0
95
+ count += 1
96
+ self._local[key] = (window, count)
97
+ if len(self._local) > 10_000:
98
+ # 粗暴但安全的兜底:内存不能被键撑爆
99
+ self._local.clear()
100
+ return count
101
+
102
+
103
+ __all__ = ["RateLimitMiddleware"]
@@ -0,0 +1,122 @@
1
+ """请求体采样日志(默认关):按比例采样,落盘前脱敏。
2
+
3
+ 为什么要单独一层:请求体只能读一次。这里用 `receive` 旁路复制(不消费、不改写),
4
+ 业务读不到影响;超过上限只保留前缀,避免大包撑爆日志。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import random
10
+ import time
11
+
12
+ import orjson
13
+
14
+ from swiftapi.config.settings import Settings
15
+ from swiftapi.core.http.types import ASGIApp, Message, Receive, Scope, Send
16
+ from swiftapi.core.observability.logging import get_logger
17
+ from swiftapi.core.observability.masking import mask_text, mask_value
18
+
19
+ logger = get_logger("swiftapi.body")
20
+
21
+ SILENT_PATHS = frozenset({"/livez", "/readyz", "/metrics", "/openapi.json"})
22
+
23
+
24
+ class RequestBodyLogMiddleware:
25
+ def __init__(self, app: ASGIApp, *, settings: Settings) -> None:
26
+ self.app = app
27
+ self.enabled = settings.observability.log_request_body
28
+ self.ratio = settings.observability.log_request_body_sample_ratio
29
+ self.max_chars = settings.observability.log_request_body_max_chars
30
+ # 预算是集群口径:均摊到副本,至少保留 1 条/分钟(否则等于关闭)
31
+ self.cluster_budget = settings.observability.log_request_body_max_per_minute
32
+ self.replicas = settings.observability.log_request_body_replicas
33
+ self.max_per_minute = (
34
+ 0 if self.cluster_budget <= 0 else max(1, self.cluster_budget // self.replicas)
35
+ )
36
+ self.extra_keys = frozenset(key.lower() for key in settings.observability.log_mask_keys)
37
+ # 错峰:多副本不要在同一秒一起重置窗口
38
+ self._window_started = time.monotonic() - random.uniform(0, 60)
39
+ self._window_count = 0
40
+ self._budget_warned = False
41
+
42
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
43
+ if scope["type"] != "http" or not self.enabled:
44
+ await self.app(scope, receive, send)
45
+ return
46
+
47
+ path = str(scope.get("path", ""))
48
+ if path in SILENT_PATHS or random.random() >= self.ratio:
49
+ await self.app(scope, receive, send)
50
+ return
51
+
52
+ # 采样预算:高 QPS 下按分钟限流,避免日志把磁盘打满
53
+ if not self._take_budget():
54
+ await self.app(scope, receive, send)
55
+ return
56
+
57
+ chunks: list[bytes] = []
58
+ budget = self.max_chars * 4 # 粗略上限:UTF-8 中文按 3~4 字节/字
59
+ captured = 0
60
+ truncated = False
61
+
62
+ async def tee() -> Message:
63
+ nonlocal captured, truncated
64
+ message = await receive()
65
+ if message["type"] == "http.request":
66
+ body = message.get("body", b"")
67
+ room = budget - captured
68
+ if room > 0:
69
+ chunks.append(body[:room])
70
+ captured += min(len(body), room)
71
+ if len(body) > max(room, 0):
72
+ truncated = True
73
+ return message
74
+
75
+ await self.app(scope, tee, send)
76
+
77
+ raw = b"".join(chunks)
78
+ if not raw:
79
+ return
80
+ try:
81
+ parsed = orjson.loads(raw)
82
+ payload: object = mask_value(parsed, extra_keys=self.extra_keys)
83
+ except orjson.JSONDecodeError:
84
+ payload = mask_text(raw.decode("utf-8", errors="replace"))[: self.max_chars]
85
+
86
+ logger.info(
87
+ "http.body",
88
+ method=scope.get("method"),
89
+ path=path,
90
+ content_type=dict(scope.get("headers") or []).get(b"content-type", b"").decode("latin-1"),
91
+ body=payload,
92
+ truncated=truncated,
93
+ )
94
+
95
+ def _take_budget(self) -> bool:
96
+ """每分钟最多 `log_request_body_max_per_minute` 条;0 表示不限。"""
97
+ if self.max_per_minute <= 0:
98
+ return True
99
+
100
+ now = time.monotonic()
101
+ if now - self._window_started >= 60:
102
+ self._window_started = now
103
+ self._window_count = 0
104
+ self._budget_warned = False
105
+
106
+ if self._window_count >= self.max_per_minute:
107
+ if not self._budget_warned:
108
+ logger.warning(
109
+ "http.body.budget_exceeded",
110
+ limit_per_minute=self.max_per_minute,
111
+ cluster_budget=self.cluster_budget,
112
+ replicas=self.replicas,
113
+ hint="调大 log_request_body_max_per_minute 或降低采样比例",
114
+ )
115
+ self._budget_warned = True
116
+ return False
117
+
118
+ self._window_count += 1
119
+ return True
120
+
121
+
122
+ __all__ = ["SILENT_PATHS", "RequestBodyLogMiddleware"]