fastapi-sdk 0.12.18__tar.gz → 0.13.0__tar.gz

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.
Files changed (34) hide show
  1. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/PKG-INFO +2 -2
  2. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/README.md +1 -1
  3. fastapi_sdk-0.13.0/fastapi_sdk/middleware/secure.py +147 -0
  4. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/exception_handler.py +4 -2
  5. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk.egg-info/PKG-INFO +2 -2
  6. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/pyproject.toml +1 -1
  7. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/tests/test_exception_handlers.py +17 -1
  8. fastapi_sdk-0.12.18/fastapi_sdk/middleware/secure.py +0 -64
  9. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/LICENSE +0 -0
  10. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/__init__.py +0 -0
  11. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/controllers/__init__.py +0 -0
  12. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/controllers/mixin.py +0 -0
  13. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/controllers/model.py +0 -0
  14. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/controllers/route.py +0 -0
  15. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/middleware/auth.py +0 -0
  16. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/security/oauth.py +0 -0
  17. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/security/permissions.py +0 -0
  18. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/security/webhook.py +0 -0
  19. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/claims.py +0 -0
  20. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/constants.py +0 -0
  21. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/dependencies.py +0 -0
  22. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/model.py +0 -0
  23. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/response.py +0 -0
  24. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/schema.py +0 -0
  25. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/utils/test.py +0 -0
  26. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/webhook/generator.py +0 -0
  27. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/webhook/handler.py +0 -0
  28. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk/webhook/route.py +0 -0
  29. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk.egg-info/SOURCES.txt +0 -0
  30. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk.egg-info/dependency_links.txt +0 -0
  31. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk.egg-info/requires.txt +0 -0
  32. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/fastapi_sdk.egg-info/top_level.txt +0 -0
  33. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/setup.cfg +0 -0
  34. {fastapi_sdk-0.12.18 → fastapi_sdk-0.13.0}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-sdk
3
- Version: 0.12.18
3
+ Version: 0.13.0
4
4
  Summary: Utilities for FastAPI projects.
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -57,7 +57,7 @@ A powerful SDK for building FastAPI applications with built-in authentication, a
57
57
 
58
58
  ### Auth & security
59
59
 
60
- - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, and claims helpers
60
+ - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, claims helpers, HTTPS enforcement and security headers
61
61
  - [Auth Middleware Errors](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/auth_middleware_errors.md) — Authentication error codes and response shapes
62
62
  - [Custom Permissions](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/custom_permissions.md) — Layered token + business-logic permission checks
63
63
  - [Encryption Key Mixin](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/encryption_key_mixin.md) — Encrypted secret keys for shareable/public resource access
@@ -38,7 +38,7 @@ A powerful SDK for building FastAPI applications with built-in authentication, a
38
38
 
39
39
  ### Auth & security
40
40
 
41
- - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, and claims helpers
41
+ - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, claims helpers, HTTPS enforcement and security headers
42
42
  - [Auth Middleware Errors](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/auth_middleware_errors.md) — Authentication error codes and response shapes
43
43
  - [Custom Permissions](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/custom_permissions.md) — Layered token + business-logic permission checks
44
44
  - [Encryption Key Mixin](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/encryption_key_mixin.md) — Encrypted secret keys for shareable/public resource access
@@ -0,0 +1,147 @@
1
+ """Secure middlewares: HTTPS enforcement and security headers.
2
+
3
+ This middleware provides environment-aware HTTPS enforcement with support for
4
+ X-Forwarded-Proto headers (useful when behind proxies/load balancers).
5
+
6
+ Note: FastAPI provides HTTPSRedirectMiddleware, but it:
7
+ - Always enforces HTTPS (no environment-based conditional)
8
+ - Doesn't check X-Forwarded-Proto header (won't work behind proxies)
9
+ - Uses ASGI app wrapper pattern (not BaseHTTPMiddleware), so cannot be inherited
10
+
11
+ This custom middleware uses BaseHTTPMiddleware (the standard Starlette pattern)
12
+ and addresses both limitations above.
13
+
14
+ See: https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
15
+ """
16
+
17
+ from collections.abc import Mapping, Sequence
18
+
19
+ from starlette.datastructures import MutableHeaders
20
+ from starlette.middleware.base import BaseHTTPMiddleware
21
+ from starlette.requests import Request
22
+ from starlette.responses import RedirectResponse
23
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
24
+
25
+ DEFAULT_SECURITY_HEADERS: dict[str, str] = {
26
+ "Strict-Transport-Security": "max-age=63072000; includeSubDomains",
27
+ "X-Content-Type-Options": "nosniff",
28
+ "X-Frame-Options": "DENY",
29
+ "Referrer-Policy": "no-referrer",
30
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
31
+ "Cache-Control": "no-store",
32
+ }
33
+
34
+
35
+ class EnforceHTTPSMiddleware(BaseHTTPMiddleware):
36
+ """
37
+ Middleware to enforce HTTPS in production environments.
38
+
39
+ Unlike FastAPI's built-in HTTPSRedirectMiddleware, this middleware:
40
+ - Only enforces HTTPS in production (allows HTTP in development)
41
+ - Checks X-Forwarded-Proto header for proxy/load balancer compatibility
42
+ - Works correctly when deployed behind reverse proxies (nginx, AWS ALB, etc.)
43
+
44
+ See: https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
45
+ """
46
+
47
+ def __init__(self, app, env: str = "development"):
48
+ """Initialize the middleware.
49
+
50
+ Args:
51
+ app: The FastAPI application
52
+ env: The environment name (default: "development")
53
+ - "production": Enforces HTTPS
54
+ - Other values: No HTTPS enforcement
55
+ """
56
+ super().__init__(app)
57
+ self.env = env
58
+
59
+ async def dispatch(self, request: Request, call_next):
60
+ """Dispatch request with HTTPS enforcement in production.
61
+
62
+ Args:
63
+ request: The incoming request
64
+ call_next: The next middleware/handler in the chain
65
+
66
+ Returns:
67
+ RedirectResponse if HTTP in production, otherwise proceeds normally
68
+ """
69
+ # Only enforce HTTPS in production
70
+ if self.env == "production":
71
+ # Check X-Forwarded-Proto header first (for proxy/load balancer scenarios)
72
+ # Fall back to request URL scheme if header is not present
73
+ proto = request.headers.get("x-forwarded-proto", request.url.scheme)
74
+ if proto != "https":
75
+ url = request.url.replace(scheme="https")
76
+ return RedirectResponse(url=str(url), status_code=307)
77
+ return await call_next(request)
78
+
79
+
80
+ class SecurityHeadersMiddleware:
81
+ """
82
+ Middleware adding best-practice security headers to every HTTP response.
83
+
84
+ It is a pure ASGI middleware (not BaseHTTPMiddleware), so it also covers
85
+ streaming responses and responses returned by other middlewares. Register
86
+ it last so it runs outermost.
87
+
88
+ A header the response already has is never overwritten, so a route can set
89
+ its own Cache-Control or Content-Security-Policy.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ app: ASGIApp,
95
+ headers: Mapping[str, str | None] | None = None,
96
+ csp_exempt_paths: Sequence[str] = ("/docs", "/redoc"),
97
+ csp_exempt_content_types: Sequence[str] = (),
98
+ ):
99
+ """Initialize the middleware.
100
+
101
+ Args:
102
+ app: The ASGI application
103
+ headers: Headers merged over DEFAULT_SECURITY_HEADERS; a value of
104
+ None removes that default
105
+ csp_exempt_paths: Path prefixes that get no Content-Security-Policy
106
+ (Swagger UI and ReDoc load scripts from a CDN)
107
+ csp_exempt_content_types: Response content types that get no
108
+ Content-Security-Policy, matched as a prefix and ignoring
109
+ parameters such as charset, e.g. ("application/pdf",)
110
+ """
111
+ self.app = app
112
+ merged: dict[str, str | None] = dict(DEFAULT_SECURITY_HEADERS)
113
+ for name, value in (headers or {}).items():
114
+ # Match defaults case-insensitively so overrides replace them
115
+ existing = next((k for k in merged if k.lower() == name.lower()), name)
116
+ merged[existing] = value
117
+ self.headers = [(k, v) for k, v in merged.items() if v is not None]
118
+ self.csp_exempt_paths = tuple(csp_exempt_paths)
119
+ self.csp_exempt_content_types = tuple(
120
+ t.lower() for t in csp_exempt_content_types
121
+ )
122
+
123
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
124
+ if scope["type"] != "http":
125
+ await self.app(scope, receive, send)
126
+ return
127
+
128
+ path = scope.get("path", "")
129
+ path_exempt = any(path.startswith(prefix) for prefix in self.csp_exempt_paths)
130
+
131
+ async def send_with_headers(message: Message) -> None:
132
+ if message["type"] == "http.response.start":
133
+ headers = MutableHeaders(scope=message)
134
+ content_type = (
135
+ headers.get("content-type", "").split(";")[0].strip().lower()
136
+ )
137
+ skip_csp = path_exempt or any(
138
+ content_type.startswith(t) for t in self.csp_exempt_content_types
139
+ )
140
+ for name, value in self.headers:
141
+ if skip_csp and name.lower() == "content-security-policy":
142
+ continue
143
+ if name not in headers:
144
+ headers.append(name, value)
145
+ await send(message)
146
+
147
+ await self.app(scope, receive, send_with_headers)
@@ -4,11 +4,11 @@ import json
4
4
  import logging
5
5
  from typing import Any, Awaitable, Callable, Iterable, Optional
6
6
 
7
- from fastapi import FastAPI, HTTPException, Request, UploadFile
7
+ from fastapi import FastAPI, HTTPException, Request
8
8
  from fastapi.exceptions import RequestValidationError
9
9
  from fastapi.responses import JSONResponse
10
10
  from pydantic import ValidationError
11
- from starlette.datastructures import FormData
11
+ from starlette.datastructures import FormData, UploadFile
12
12
  from starlette.exceptions import HTTPException as StarletteHTTPException
13
13
 
14
14
  from fastapi_sdk.utils.constants import ErrorCode
@@ -104,6 +104,8 @@ def _serialize_body(body: Any) -> Any:
104
104
 
105
105
  Form bodies become a dict (repeated keys become lists, files become their
106
106
  filename) and raw bytes are decoded, so the payload can be echoed back.
107
+ Files are matched on Starlette's ``UploadFile``: the form parser creates
108
+ that class, and ``fastapi.UploadFile`` is only a subclass of it.
107
109
  """
108
110
  if isinstance(body, FormData):
109
111
  result: dict[str, Any] = {}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-sdk
3
- Version: 0.12.18
3
+ Version: 0.13.0
4
4
  Summary: Utilities for FastAPI projects.
5
5
  Requires-Python: >=3.12
6
6
  Description-Content-Type: text/markdown
@@ -57,7 +57,7 @@ A powerful SDK for building FastAPI applications with built-in authentication, a
57
57
 
58
58
  ### Auth & security
59
59
 
60
- - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, and claims helpers
60
+ - [Middlewares](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/middlewares.md) — JWT auth middleware setup, public routes, claims helpers, HTTPS enforcement and security headers
61
61
  - [Auth Middleware Errors](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/auth_middleware_errors.md) — Authentication error codes and response shapes
62
62
  - [Custom Permissions](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/custom_permissions.md) — Layered token + business-logic permission checks
63
63
  - [Encryption Key Mixin](https://github.com/Studio-Piot/fastapi-sdk/blob/main/docs/encryption_key_mixin.md) — Encrypted secret keys for shareable/public resource access
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "fastapi-sdk"
7
- version = "0.12.18"
7
+ version = "0.13.0"
8
8
  description = "Utilities for FastAPI projects."
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.12"
@@ -1,7 +1,7 @@
1
1
  """Tests for exception handlers."""
2
2
 
3
3
  import pytest
4
- from fastapi import FastAPI, Form, HTTPException
4
+ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
5
5
  from fastapi.testclient import TestClient
6
6
  from pydantic import BaseModel, Field
7
7
  from starlette.exceptions import HTTPException as StarletteHTTPException
@@ -346,6 +346,10 @@ def http_error_client():
346
346
  detail=[{"msg": "Name is required.", "code": "MISSING_REQUIRED", "loc": ["name"]}],
347
347
  )
348
348
 
349
+ @test_app.post("/upload/")
350
+ async def upload(file: UploadFile = File(...), alt: str = Form("")):
351
+ raise HTTPException(status_code=400, detail="Image is too small.")
352
+
349
353
  @test_app.post("/raise-starlette/")
350
354
  async def raise_starlette():
351
355
  raise StarletteHTTPException(status_code=409, detail="Slug taken")
@@ -399,3 +403,15 @@ def test_starlette_http_exception_on_write_echoes_payload(http_error_client):
399
403
 
400
404
  assert response.status_code == 409
401
405
  assert response.json()["data"] == ERROR_PAYLOAD
406
+
407
+
408
+ def test_http_exception_on_upload_echoes_filename(http_error_client):
409
+ """Test that a failed upload echoes the filename, not the file object."""
410
+ response = http_error_client.post(
411
+ "/upload/",
412
+ files={"file": ("icon.png", b"\x89PNG", "image/png")},
413
+ data={"alt": "Icon"},
414
+ )
415
+
416
+ assert response.status_code == 400
417
+ assert response.json()["data"] == {"file": "icon.png", "alt": "Icon"}
@@ -1,64 +0,0 @@
1
- """Secure middleware for enforcing HTTPS in production environments.
2
-
3
- This middleware provides environment-aware HTTPS enforcement with support for
4
- X-Forwarded-Proto headers (useful when behind proxies/load balancers).
5
-
6
- Note: FastAPI provides HTTPSRedirectMiddleware, but it:
7
- - Always enforces HTTPS (no environment-based conditional)
8
- - Doesn't check X-Forwarded-Proto header (won't work behind proxies)
9
- - Uses ASGI app wrapper pattern (not BaseHTTPMiddleware), so cannot be inherited
10
-
11
- This custom middleware uses BaseHTTPMiddleware (the standard Starlette pattern)
12
- and addresses both limitations above.
13
-
14
- See: https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
15
- """
16
-
17
- from starlette.middleware.base import BaseHTTPMiddleware
18
- from starlette.requests import Request
19
- from starlette.responses import RedirectResponse
20
-
21
-
22
- class EnforceHTTPSMiddleware(BaseHTTPMiddleware):
23
- """
24
- Middleware to enforce HTTPS in production environments.
25
-
26
- Unlike FastAPI's built-in HTTPSRedirectMiddleware, this middleware:
27
- - Only enforces HTTPS in production (allows HTTP in development)
28
- - Checks X-Forwarded-Proto header for proxy/load balancer compatibility
29
- - Works correctly when deployed behind reverse proxies (nginx, AWS ALB, etc.)
30
-
31
- See: https://fastapi.tiangolo.com/advanced/middleware/#httpsredirectmiddleware
32
- """
33
-
34
- def __init__(self, app, env: str = "development"):
35
- """Initialize the middleware.
36
-
37
- Args:
38
- app: The FastAPI application
39
- env: The environment name (default: "development")
40
- - "production": Enforces HTTPS
41
- - Other values: No HTTPS enforcement
42
- """
43
- super().__init__(app)
44
- self.env = env
45
-
46
- async def dispatch(self, request: Request, call_next):
47
- """Dispatch request with HTTPS enforcement in production.
48
-
49
- Args:
50
- request: The incoming request
51
- call_next: The next middleware/handler in the chain
52
-
53
- Returns:
54
- RedirectResponse if HTTP in production, otherwise proceeds normally
55
- """
56
- # Only enforce HTTPS in production
57
- if self.env == "production":
58
- # Check X-Forwarded-Proto header first (for proxy/load balancer scenarios)
59
- # Fall back to request URL scheme if header is not present
60
- proto = request.headers.get("x-forwarded-proto", request.url.scheme)
61
- if proto != "https":
62
- url = request.url.replace(scheme="https")
63
- return RedirectResponse(url=str(url), status_code=307)
64
- return await call_next(request)
File without changes
File without changes