fastapi-docshield 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.
@@ -0,0 +1,18 @@
1
+ """
2
+ FastAPI DocShield - A simple package to protect FastAPI documentation endpoints with authentication.
3
+
4
+ This package provides an easy way to secure FastAPI's built-in documentation endpoints
5
+ (/docs, /redoc, /openapi.json) with HTTP Basic Authentication.
6
+
7
+ Author: George Khananaev
8
+ License: MIT License
9
+ Copyright (c) 2025 George Khananaev
10
+ """
11
+
12
+ from .docshield import DocShield
13
+
14
+ __version__ = "0.1.0"
15
+ __author__ = "George Khananaev"
16
+ __license__ = "MIT"
17
+ __copyright__ = "Copyright (c) 2025 George Khananaev"
18
+ __all__ = ["DocShield"]
@@ -0,0 +1,187 @@
1
+ """
2
+ FastAPI DocShield - A simple module to protect FastAPI documentation endpoints with HTTP Basic Auth.
3
+
4
+ Author: George Khananaev
5
+ License: MIT
6
+ Copyright (c) 2025 George Khananaev
7
+ """
8
+
9
+ from typing import Dict, Optional, Tuple
10
+ from fastapi import FastAPI, HTTPException, status, Request, Depends
11
+ from fastapi.security.utils import get_authorization_scheme_param
12
+ from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
13
+ from fastapi.security import HTTPBasic, HTTPBasicCredentials
14
+ import secrets
15
+ import base64
16
+
17
+
18
+ class DocShield:
19
+ """
20
+ DocShield provides authentication protection for FastAPI's built-in documentation endpoints.
21
+
22
+ This class allows you to easily secure both /docs (Swagger UI) and /redoc endpoints
23
+ with HTTP Basic Authentication.
24
+
25
+ Author: George Khananaev
26
+ License: MIT License
27
+ """
28
+
29
+ def __init__(
30
+ self,
31
+ app: FastAPI,
32
+ credentials: Dict[str, str],
33
+ docs_url: str = "/docs",
34
+ redoc_url: str = "/redoc",
35
+ openapi_url: str = "/openapi.json",
36
+ swagger_js_url: Optional[str] = None,
37
+ swagger_css_url: Optional[str] = None,
38
+ redoc_js_url: Optional[str] = None,
39
+ ):
40
+ """
41
+ Initialize DocShield with the given FastAPI application and credentials.
42
+
43
+ Args:
44
+ app: The FastAPI application instance to protect
45
+ credentials: Dictionary of username:password pairs for authentication
46
+ docs_url: URL path for Swagger UI documentation
47
+ redoc_url: URL path for ReDoc documentation
48
+ openapi_url: URL path for OpenAPI JSON schema
49
+ swagger_js_url: Custom Swagger UI JavaScript URL (optional)
50
+ swagger_css_url: Custom Swagger UI CSS URL (optional)
51
+ redoc_js_url: Custom ReDoc JavaScript URL (optional)
52
+ """
53
+ # Initialize security scheme
54
+ self.security = HTTPBasic()
55
+ self.app = app
56
+ self.credentials = credentials
57
+ self.docs_url = docs_url
58
+ self.redoc_url = redoc_url
59
+ self.openapi_url = openapi_url
60
+
61
+ # Store original endpoints
62
+ self.original_docs_url = app.docs_url
63
+ self.original_redoc_url = app.redoc_url
64
+ self.original_openapi_url = app.openapi_url
65
+
66
+ # Remove existing documentation routes
67
+ self._remove_existing_docs_routes()
68
+
69
+ # Disable built-in docs
70
+ app.docs_url = None
71
+ app.redoc_url = None
72
+ app.openapi_url = None
73
+
74
+ # Set up protected documentation routes
75
+ self._setup_routes(
76
+ swagger_js_url=swagger_js_url,
77
+ swagger_css_url=swagger_css_url,
78
+ redoc_js_url=redoc_js_url
79
+ )
80
+
81
+ def _remove_existing_docs_routes(self) -> None:
82
+ """
83
+ Remove the existing documentation routes from the FastAPI app.
84
+ This ensures the default routes don't conflict with our secured ones.
85
+ """
86
+ # Since FastAPI.routes is a property with no setter, we have to use the underlying router
87
+ # Get all non-documentation routes
88
+ routes_to_keep = []
89
+
90
+ # Identify and filter out documentation routes
91
+ for route in self.app.routes:
92
+ path = getattr(route, "path", "")
93
+
94
+ # Skip documentation routes
95
+ if (path == self.docs_url or
96
+ path == self.redoc_url or
97
+ path == self.openapi_url or
98
+ path.startswith(f"{self.docs_url}/") or # Docs static files
99
+ path == "/openapi.json"):
100
+ continue
101
+
102
+ routes_to_keep.append(route)
103
+
104
+ # Use a different approach - set up a fresh router and add all non-docs routes
105
+ # We can access the router directly
106
+ self.app.router.routes = routes_to_keep
107
+
108
+ def _verify_credentials(self, credentials: HTTPBasicCredentials) -> str:
109
+ """
110
+ Verify HTTP Basic Auth credentials against our credentials dictionary.
111
+
112
+ Args:
113
+ credentials: The credentials provided by HTTPBasic
114
+
115
+ Returns:
116
+ The authenticated username if credentials are valid
117
+
118
+ Raises:
119
+ HTTPException: If authentication fails
120
+ """
121
+ username = credentials.username
122
+ password = credentials.password
123
+
124
+ # Check if username exists and password is correct
125
+ if username in self.credentials:
126
+ is_correct_password = secrets.compare_digest(
127
+ password,
128
+ self.credentials[username],
129
+ )
130
+ if is_correct_password:
131
+ return username
132
+
133
+ # If credentials are invalid, raise an exception
134
+ raise HTTPException(
135
+ status_code=status.HTTP_401_UNAUTHORIZED,
136
+ detail="Incorrect username or password",
137
+ headers={"WWW-Authenticate": "Basic"},
138
+ )
139
+
140
+ def _setup_routes(
141
+ self,
142
+ swagger_js_url: Optional[str],
143
+ swagger_css_url: Optional[str],
144
+ redoc_js_url: Optional[str],
145
+ ) -> None:
146
+ """
147
+ Set up all protected documentation endpoints.
148
+
149
+ Args:
150
+ swagger_js_url: Custom Swagger UI JavaScript URL
151
+ swagger_css_url: Custom Swagger UI CSS URL
152
+ redoc_js_url: Custom ReDoc JavaScript URL
153
+ """
154
+ # Set up OpenAPI JSON endpoint
155
+ @self.app.get(self.openapi_url, include_in_schema=False)
156
+ async def get_openapi(credentials: HTTPBasicCredentials = Depends(self.security)):
157
+ self._verify_credentials(credentials)
158
+ # Because we set app.openapi_url to None, we need to restore it temporarily
159
+ old_openapi_url = self.app.openapi_url
160
+ self.app.openapi_url = self.openapi_url
161
+ openapi_schema = self.app.openapi()
162
+ self.app.openapi_url = old_openapi_url
163
+ return openapi_schema
164
+
165
+ # Set up Swagger UI endpoint if the original app had it
166
+ if self.original_docs_url is not None:
167
+ @self.app.get(self.docs_url, include_in_schema=False)
168
+ async def get_docs(credentials: HTTPBasicCredentials = Depends(self.security)):
169
+ self._verify_credentials(credentials)
170
+ return get_swagger_ui_html(
171
+ openapi_url=self.openapi_url,
172
+ title=self.app.title + " - Swagger UI",
173
+ oauth2_redirect_url=None,
174
+ swagger_js_url=swagger_js_url,
175
+ swagger_css_url=swagger_css_url,
176
+ )
177
+
178
+ # Set up ReDoc endpoint if the original app had it
179
+ if self.original_redoc_url is not None:
180
+ @self.app.get(self.redoc_url, include_in_schema=False)
181
+ async def get_redoc(credentials: HTTPBasicCredentials = Depends(self.security)):
182
+ self._verify_credentials(credentials)
183
+ return get_redoc_html(
184
+ openapi_url=self.openapi_url,
185
+ title=self.app.title + " - ReDoc",
186
+ redoc_js_url=redoc_js_url,
187
+ )
@@ -0,0 +1,146 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastapi-docshield
3
+ Version: 0.1.0
4
+ Summary: A simple FastAPI integration to protect documentation endpoints with authentication
5
+ Project-URL: Homepage, https://github.com/georgekhananaev/fastapi-docshield
6
+ Project-URL: Bug Tracker, https://github.com/georgekhananaev/fastapi-docshield/issues
7
+ Project-URL: Documentation, https://github.com/georgekhananaev/fastapi-docshield#readme
8
+ Project-URL: Source Code, https://github.com/georgekhananaev/fastapi-docshield
9
+ Author-email: George Khananaev <georgekhananaev@gmail.com>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2025 George Khananaev
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE
32
+ Keywords: authentication,documentation,fastapi,security
33
+ Classifier: Development Status :: 4 - Beta
34
+ Classifier: Intended Audience :: Developers
35
+ Classifier: License :: OSI Approved :: MIT License
36
+ Classifier: Operating System :: OS Independent
37
+ Classifier: Programming Language :: Python :: 3
38
+ Classifier: Programming Language :: Python :: 3.7
39
+ Classifier: Programming Language :: Python :: 3.8
40
+ Classifier: Programming Language :: Python :: 3.9
41
+ Classifier: Programming Language :: Python :: 3.10
42
+ Classifier: Programming Language :: Python :: 3.11
43
+ Classifier: Programming Language :: Python :: 3.12
44
+ Classifier: Programming Language :: Python :: 3.13
45
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
46
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
47
+ Requires-Python: >=3.7
48
+ Requires-Dist: fastapi>=0.68.0
49
+ Requires-Dist: requests>=2.31.0
50
+ Requires-Dist: uvicorn>=0.22.0
51
+ Provides-Extra: dev
52
+ Requires-Dist: httpx>=0.23.0; extra == 'dev'
53
+ Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
54
+ Requires-Dist: pytest>=7.0.0; extra == 'dev'
55
+ Requires-Dist: requests>=2.28.0; extra == 'dev'
56
+ Requires-Dist: uvicorn>=0.18.0; extra == 'dev'
57
+ Description-Content-Type: text/markdown
58
+
59
+ # FastAPI DocShield
60
+
61
+ A simple FastAPI integration to protect documentation endpoints with HTTP Basic Authentication.
62
+
63
+ [![PyPI version](https://badge.fury.io/py/fastapi-docshield.svg)](https://badge.fury.io/py/fastapi-docshield)
64
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
65
+ [![Python Versions](https://img.shields.io/badge/python-3.7%20%7C%203.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/georgekhananaev/fastapi-docshield)
66
+ [![Tests Status](https://img.shields.io/badge/tests-passing-brightgreen)](https://github.com/georgekhananaev/fastapi-docshield)
67
+ [![UV Compatible](https://img.shields.io/badge/uv-compatible-blueviolet)](https://github.com/astral-sh/uv)
68
+
69
+ ## About
70
+
71
+ Protect FastAPI's `/docs`, `/redoc`, and `/openapi.json` endpoints with HTTP Basic Authentication.
72
+
73
+ ## Installation
74
+
75
+ ### From PyPI
76
+
77
+ ```bash
78
+ # Install with pip
79
+ pip install fastapi-docshield
80
+
81
+ # Or with uv
82
+ uv pip install fastapi-docshield
83
+ ```
84
+
85
+ ### From Source
86
+
87
+ ```bash
88
+ git clone https://github.com/georgekhananaev/fastapi-docshield.git
89
+ cd fastapi-docshield
90
+ pip install -e .
91
+ ```
92
+
93
+ ## Quick Usage
94
+
95
+ ```python
96
+ from fastapi import FastAPI
97
+ from fastapi_docshield import DocShield
98
+
99
+ app = FastAPI()
100
+
101
+ @app.get("/")
102
+ def read_root():
103
+ return {"Hello": "World"}
104
+
105
+ # Add protection to docs
106
+ DocShield(
107
+ app=app,
108
+ credentials={"admin": "password123"}
109
+ )
110
+ ```
111
+
112
+ ## Running Demo
113
+
114
+ ```bash
115
+ # Run the demo app
116
+ python demo.py
117
+
118
+ # Visit http://localhost:8000/docs
119
+ # Username: admin
120
+ # Password: password123
121
+ ```
122
+
123
+ ## Running Tests
124
+
125
+ ```bash
126
+ # Install test dependencies
127
+ pip install pytest httpx
128
+
129
+ # Run all tests
130
+ pytest
131
+
132
+ # Run with coverage
133
+ pytest --cov=fastapi_docshield
134
+ ```
135
+
136
+ ## Features
137
+
138
+ - Protect Swagger UI, ReDoc, and OpenAPI JSON endpoints
139
+ - Customizable endpoint URLs
140
+ - Multiple username/password combinations
141
+ - Tested on Python 3.7-3.13
142
+ - Compatible with uv package manager
143
+
144
+ ## License
145
+
146
+ MIT License - Copyright (c) 2025 George Khananaev
@@ -0,0 +1,6 @@
1
+ fastapi_docshield/__init__.py,sha256=P6LJ59UMEhvHpMql_TxL-t6Tejw-C9JGNTskS50aasw,529
2
+ fastapi_docshield/docshield.py,sha256=44bod9gBHMsdaEWDZK4A7VPjytMXCornicVihwX0RIE,7153
3
+ fastapi_docshield-0.1.0.dist-info/METADATA,sha256=9NOAdtIb8HCU194kRfIz405qMqM_7u5HnEl9H3DA9qM,4987
4
+ fastapi_docshield-0.1.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ fastapi_docshield-0.1.0.dist-info/licenses/LICENSE,sha256=C7RfUMBXNY0vWCc5HGdnBoWZNwDerPOlev46BY0GYtw,1072
6
+ fastapi_docshield-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 George Khananaev
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.