auth-framework-py 1.0.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.
@@ -0,0 +1,45 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2024-08-26
9
+
10
+ ### Added
11
+ - Initial release of Auth & Authorization Framework
12
+ - Local authentication with PBKDF2 password hashing (100k iterations)
13
+ - API key authentication provider
14
+ - JWT token generation and verification (zero dependencies)
15
+ - Opaque token support with server-side storage
16
+ - Token refresh and revocation mechanisms
17
+ - RBAC (Role-Based Access Control) engine
18
+ - ABAC (Attribute-Based Access Control) with policy rules
19
+ - Session management with device tracking
20
+ - Multi-tenant support with tenant isolation
21
+ - Wildcard pattern matching in policy rules
22
+ - Context-aware policy decisions
23
+ - Comprehensive test suite (40 tests, 100% passing)
24
+ - Full documentation and examples
25
+
26
+ ### Security
27
+ - PBKDF2-SHA256 password hashing with 100,000 iterations
28
+ - HMAC-SHA256 token signatures
29
+ - Timing-safe password comparison
30
+ - Cryptographically secure random token generation
31
+ - Server-side token revocation list
32
+
33
+ ## [Unreleased]
34
+
35
+ ### Planned
36
+ - OAuth2/OIDC provider implementation
37
+ - SAML provider implementation
38
+ - Redis-backed session storage
39
+ - Database-backed token storage
40
+ - Rate limiting for authentication endpoints
41
+ - Two-factor authentication (2FA) support
42
+ - Passwordless authentication
43
+ - Social login providers (Google, GitHub, etc.)
44
+
45
+ [1.0.0]: https://github.com/parthivrawat/auth-framework/releases/tag/v1.0.0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Parthiv Rawat
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.
@@ -0,0 +1,7 @@
1
+ include README.md
2
+ include LICENSE
3
+ include CHANGELOG.md
4
+ include pyproject.toml
5
+ recursive-include auth_framework *.py
6
+ recursive-exclude * __pycache__
7
+ recursive-exclude * *.py[co]
@@ -0,0 +1,394 @@
1
+ Metadata-Version: 2.4
2
+ Name: auth-framework-py
3
+ Version: 1.0.0
4
+ Summary: A unified identity, session, token, and permission framework with pluggable providers
5
+ Author-email: Parthiv Rawat <parthiv05022000@gmail.com>
6
+ Maintainer-email: Parthiv Rawat <parthiv05022000@gmail.com>
7
+ License: MIT
8
+ Project-URL: Homepage, https://github.com/parthivrawat/auth-framework
9
+ Project-URL: Documentation, https://github.com/parthivrawat/auth-framework/tree/main/python#readme
10
+ Project-URL: Repository, https://github.com/parthivrawat/auth-framework
11
+ Project-URL: Bug Tracker, https://github.com/parthivrawat/auth-framework/issues
12
+ Project-URL: Changelog, https://github.com/parthivrawat/auth-framework/blob/main/python/CHANGELOG.md
13
+ Keywords: auth,authentication,authorization,jwt,oauth2,rbac,abac,security,session,token,policy,permissions
14
+ Classifier: Development Status :: 5 - Production/Stable
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Classifier: Topic :: Security
27
+ Classifier: Topic :: System :: Systems Administration :: Authentication/Directory
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: >=3.8
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
34
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
35
+ Requires-Dist: black>=23.0.0; extra == "dev"
36
+ Requires-Dist: mypy>=1.0.0; extra == "dev"
37
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # Auth & Authorization Framework (Python)
41
+
42
+ A unified identity, session, token, and permission framework with pluggable providers, strong defaults, and production-ready security.
43
+
44
+ ## Features
45
+
46
+ - ✅ **Multiple Authentication Methods**
47
+ - Username/password with secure password hashing (PBKDF2)
48
+ - OAuth2/OIDC support (pluggable)
49
+ - SAML support (pluggable)
50
+ - API key authentication
51
+
52
+ - ✅ **Token Management**
53
+ - JWT tokens (simple implementation, no external dependencies)
54
+ - Opaque tokens with server-side storage
55
+ - Refresh token support
56
+ - Token revocation
57
+
58
+ - ✅ **Authorization**
59
+ - Role-Based Access Control (RBAC)
60
+ - Attribute-Based Access Control (ABAC)
61
+ - Policy engine with wildcard matching
62
+ - Multi-tenant permission scoping
63
+
64
+ - ✅ **Session Management**
65
+ - Device and IP tracking
66
+ - Session expiry and renewal
67
+ - Multi-device support
68
+ - Session revocation
69
+
70
+ - ✅ **Security**
71
+ - Secure password hashing (PBKDF2 with salt)
72
+ - Token signature verification
73
+ - Audit logging support
74
+ - Zero dependencies for core functionality
75
+
76
+ ## Installation
77
+
78
+ ### From PyPI (Recommended)
79
+
80
+ ```bash
81
+ pip install auth-framework-py
82
+ ```
83
+
84
+ ### From Source
85
+
86
+ ```bash
87
+ git clone https://github.com/parthivrawat/auth-framework
88
+ cd auth-framework/python
89
+ pip install -e .
90
+ ```
91
+
92
+ ### Development Installation
93
+
94
+ ```bash
95
+ pip install -e ".[dev]"
96
+ ```
97
+
98
+ ## Quick Start
99
+
100
+ ### Basic Authentication
101
+
102
+ ```python
103
+ from auth_framework import Auth, LocalAuthProvider
104
+
105
+ # Initialize auth framework
106
+ auth = Auth()
107
+
108
+ # Add local authentication provider
109
+ provider = LocalAuthProvider()
110
+ auth.add_provider("local", provider)
111
+
112
+ # Register a user
113
+ user = provider.register_user(
114
+ username="alice",
115
+ password="secure_password",
116
+ email="alice@example.com",
117
+ roles={"admin", "user"}
118
+ )
119
+
120
+ # Login
121
+ result = auth.login("local", {
122
+ "username": "alice",
123
+ "password": "secure_password"
124
+ })
125
+
126
+ print(f"Access Token: {result['access_token']}")
127
+ print(f"Refresh Token: {result['refresh_token']}")
128
+ print(f"Session ID: {result['session_id']}")
129
+ ```
130
+
131
+ ### Token Verification
132
+
133
+ ```python
134
+ # Verify an access token
135
+ token = auth.verify_token(result['access_token'])
136
+
137
+ if token and not token.is_expired():
138
+ print(f"Token is valid for user: {token.user_id}")
139
+ else:
140
+ print("Token is invalid or expired")
141
+ ```
142
+
143
+ ### Permission Checking (RBAC)
144
+
145
+ ```python
146
+ from auth_framework import User
147
+
148
+ # Create a user with roles
149
+ user = User(
150
+ id="user123",
151
+ username="alice",
152
+ roles={"admin"}
153
+ )
154
+
155
+ # Add role permissions
156
+ auth.policy_engine.add_role_permission("admin", "read:*")
157
+ auth.policy_engine.add_role_permission("admin", "write:*")
158
+
159
+ # Check permissions
160
+ if auth.check_permission(user, "read", "document:123"):
161
+ print("User can read the document")
162
+
163
+ if auth.check_permission(user, "write", "document:123"):
164
+ print("User can write the document")
165
+ ```
166
+
167
+ ### Policy Rules (ABAC)
168
+
169
+ ```python
170
+ from auth_framework import PolicyRule
171
+
172
+ # Add a custom policy rule
173
+ auth.policy_engine.add_rule(PolicyRule(
174
+ subject="user:alice",
175
+ action="delete",
176
+ resource="document:*",
177
+ effect="allow",
178
+ conditions={"tenant": "tenant1"}
179
+ ))
180
+
181
+ # Check with context
182
+ context = {"tenant": "tenant1"}
183
+ if auth.check_permission(user, "delete", "document:123", context):
184
+ print("User can delete the document in tenant1")
185
+ ```
186
+
187
+ ### API Key Authentication
188
+
189
+ ```python
190
+ from auth_framework import APIKeyAuthProvider
191
+
192
+ # Add API key provider
193
+ api_provider = APIKeyAuthProvider()
194
+ auth.add_provider("api_key", api_provider)
195
+
196
+ # Create an API key for a user
197
+ api_key = api_provider.create_api_key(user)
198
+ print(f"API Key: {api_key}")
199
+
200
+ # Authenticate with API key
201
+ authenticated_user = auth.authenticate("api_key", {"api_key": api_key})
202
+ if authenticated_user:
203
+ print(f"Authenticated as: {authenticated_user.username}")
204
+ ```
205
+
206
+ ### Session Management
207
+
208
+ ```python
209
+ # Create a session
210
+ session = auth.session_manager.create_session(
211
+ user_id=user.id,
212
+ device_id="device123",
213
+ ip_address="192.168.1.1",
214
+ user_agent="Mozilla/5.0",
215
+ ttl=3600 # 1 hour
216
+ )
217
+
218
+ # Get session
219
+ active_session = auth.session_manager.get_session(session.id)
220
+ if active_session and not active_session.is_expired():
221
+ print(f"Session is active for user: {active_session.user_id}")
222
+
223
+ # Revoke session
224
+ auth.session_manager.revoke_session(session.id)
225
+
226
+ # Revoke all sessions for a user
227
+ auth.session_manager.revoke_user_sessions(user.id)
228
+ ```
229
+
230
+ ### Token Refresh
231
+
232
+ ```python
233
+ # Refresh an access token using refresh token
234
+ new_tokens = auth.refresh_token(result['refresh_token'])
235
+
236
+ if new_tokens:
237
+ print(f"New Access Token: {new_tokens['access_token']}")
238
+ ```
239
+
240
+ ### Opaque Tokens
241
+
242
+ ```python
243
+ from auth_framework import TokenType
244
+
245
+ # Use opaque tokens instead of JWT
246
+ auth = Auth(token_type=TokenType.OPAQUE)
247
+
248
+ # Rest of the code remains the same
249
+ # Opaque tokens are stored server-side and can be easily revoked
250
+ ```
251
+
252
+ ## Advanced Usage
253
+
254
+ ### Custom Password Hasher
255
+
256
+ ```python
257
+ from auth_framework import PasswordHasher
258
+
259
+ class CustomHasher(PasswordHasher):
260
+ def hash(self, password: str) -> str:
261
+ # Your custom hashing logic
262
+ pass
263
+
264
+ def verify(self, password: str, hashed: str) -> bool:
265
+ # Your custom verification logic
266
+ pass
267
+
268
+ # Use custom hasher
269
+ provider = LocalAuthProvider(password_hasher=CustomHasher())
270
+ ```
271
+
272
+ ### Custom Authentication Provider
273
+
274
+ ```python
275
+ from auth_framework import AuthProvider, User
276
+
277
+ class LDAPAuthProvider(AuthProvider):
278
+ def authenticate(self, credentials: dict) -> Optional[User]:
279
+ # Your LDAP authentication logic
280
+ username = credentials.get('username')
281
+ password = credentials.get('password')
282
+
283
+ # Authenticate against LDAP
284
+ # ...
285
+
286
+ return User(
287
+ id=ldap_user_id,
288
+ username=username,
289
+ roles=ldap_roles,
290
+ permissions=ldap_permissions
291
+ )
292
+
293
+ # Add custom provider
294
+ auth.add_provider("ldap", LDAPAuthProvider())
295
+ ```
296
+
297
+ ### Multi-Tenant Support
298
+
299
+ ```python
300
+ # Register users with tenant IDs
301
+ user1 = provider.register_user(
302
+ username="alice",
303
+ password="password",
304
+ tenant_id="tenant1"
305
+ )
306
+
307
+ user2 = provider.register_user(
308
+ username="bob",
309
+ password="password",
310
+ tenant_id="tenant2"
311
+ )
312
+
313
+ # Add tenant-scoped policy rules
314
+ auth.policy_engine.add_rule(PolicyRule(
315
+ subject="user:alice",
316
+ action="read",
317
+ resource="document:*",
318
+ effect="allow",
319
+ conditions={"tenant": "tenant1"}
320
+ ))
321
+
322
+ # Check with tenant context
323
+ context = {"tenant": "tenant1"}
324
+ can_read = auth.check_permission(user1, "read", "document:123", context)
325
+ ```
326
+
327
+ ## API Reference
328
+
329
+ ### Core Classes
330
+
331
+ - **Auth**: Main authentication and authorization framework
332
+ - **User**: Represents an authenticated user
333
+ - **Token**: Represents an authentication token
334
+ - **Session**: Represents a user session
335
+ - **PolicyRule**: Represents a policy rule for RBAC/ABAC
336
+
337
+ ### Providers
338
+
339
+ - **LocalAuthProvider**: Username/password authentication
340
+ - **APIKeyAuthProvider**: API key authentication
341
+ - **AuthProvider**: Abstract base class for custom providers
342
+
343
+ ### Token Generators
344
+
345
+ - **SimpleJWTGenerator**: JWT token generation (no external dependencies)
346
+ - **OpaqueTokenGenerator**: Opaque token generation with server-side storage
347
+
348
+ ### Utilities
349
+
350
+ - **PolicyEngine**: RBAC/ABAC policy engine
351
+ - **SessionManager**: Session management
352
+ - **PBKDF2Hasher**: Secure password hashing
353
+
354
+ ## Testing
355
+
356
+ Run the test suite:
357
+
358
+ ```bash
359
+ pytest test_auth_framework.py -v
360
+ ```
361
+
362
+ With coverage:
363
+
364
+ ```bash
365
+ pytest test_auth_framework.py -v --cov=auth_framework --cov-report=term-missing
366
+ ```
367
+
368
+ ## Security Considerations
369
+
370
+ 1. **Password Storage**: Passwords are hashed using PBKDF2 with 100,000 iterations and a random salt
371
+ 2. **Token Secrets**: Use a strong, random secret for JWT signing
372
+ 3. **Token Expiry**: Set appropriate TTLs for access and refresh tokens
373
+ 4. **Session Security**: Track device IDs and IP addresses for session validation
374
+ 5. **HTTPS**: Always use HTTPS in production to protect tokens in transit
375
+ 6. **Token Revocation**: Implement token revocation for logout and security events
376
+
377
+ ## Performance
378
+
379
+ - **Zero Dependencies**: Core functionality has no external dependencies
380
+ - **Efficient Token Verification**: JWT tokens are verified without database lookups
381
+ - **Session Cleanup**: Regularly cleanup expired sessions with `session_manager.cleanup_expired()`
382
+ - **Policy Caching**: Consider caching policy decisions for frequently accessed resources
383
+
384
+ ## License
385
+
386
+ MIT License - see LICENSE file for details
387
+
388
+ ## Contributing
389
+
390
+ Contributions are welcome! Please feel free to submit a Pull Request.
391
+
392
+ ## Support
393
+
394
+ For issues and questions, please open an issue on GitHub.