khp-secure 0.1.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,593 @@
1
+ Metadata-Version: 2.4
2
+ Name: khp-secure
3
+ Version: 0.1.0
4
+ Summary: Session-based authentication library for Python applications
5
+ Author: KHP Studio
6
+ Project-URL: Homepage, https://github.com/KhaledWaledpro/khp-secure
7
+ Project-URL: Repository, https://github.com/KhaledWaledpro/khp-secure
8
+ Project-URL: Issues, https://github.com/KhaledWaledpro/khp-secure/issues
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Security
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ Requires-Dist: argon2-cffi>=23.1
17
+ Requires-Dist: fastapi>=0.115
18
+
19
+ # KHP Secure
20
+
21
+ **A Simple Session-Based Authentication Library for Python**
22
+
23
+ KHP Secure is a Python authentication library designed to simplify the implementation of secure session-based authentication in Python applications, with initial integration for FastAPI.
24
+
25
+ The library provides a simple interface for password hashing, session management, HTTP cookie handling, and endpoint protection.
26
+
27
+ ## Core Features
28
+
29
+ - Session-based authentication.
30
+ - Cryptographically secure random session tokens.
31
+ - Argon2id password hashing.
32
+ - HTTP Cookie management.
33
+ - Server-side session storage.
34
+ - FastAPI dependency-based endpoint protection.
35
+ - Configurable session lifetime.
36
+ - Simple login and logout functionality.
37
+
38
+ > **Important:** KHP Secure is currently an educational prototype. Its default session storage is in-memory. It is not recommended for production environments until persistent storage, shared session management, and security testing are implemented.
39
+
40
+ ---
41
+
42
+ # 1. Installation
43
+
44
+ Install the required dependencies:
45
+
46
+ ```bash
47
+ pip install fastapi argon2-cffi
48
+ ```
49
+
50
+ To run the FastAPI application, install Uvicorn:
51
+
52
+ ```bash
53
+ pip install uvicorn
54
+ ```
55
+
56
+ ---
57
+
58
+ # 2. Quick Start
59
+
60
+ Create a file named `main.py`:
61
+
62
+ ```python
63
+ from fastapi import FastAPI, Depends
64
+ from khp_secure import KHP, KHPConfig
65
+
66
+ app = FastAPI()
67
+
68
+ secure = KHP(
69
+ config=KHPConfig(
70
+ session_lifetime=3600,
71
+ cookie_secure=False
72
+ )
73
+ )
74
+ ```
75
+
76
+ ## Protect an Endpoint
77
+
78
+ You can protect an endpoint using the `required()` dependency:
79
+
80
+ ```python
81
+ @app.get("/profile")
82
+ async def profile(
83
+ user=Depends(secure.required())
84
+ ):
85
+ return {
86
+ "user": user
87
+ }
88
+ ```
89
+
90
+ The endpoint will only allow requests containing a valid authentication session.
91
+
92
+ ## Run the Application
93
+
94
+ ```bash
95
+ uvicorn main:app --reload
96
+ ```
97
+
98
+ ---
99
+
100
+ # 3. KHPConfig
101
+
102
+ `KHPConfig` is responsible for configuring session behavior and HTTP cookie settings.
103
+
104
+ ## Available Parameters
105
+
106
+ | Parameter | Description | Default |
107
+ |---|---|---|
108
+ | `session_lifetime` | Session lifetime in seconds | 3600 |
109
+ | `cookie_name` | Name of the authentication cookie | Defined by implementation |
110
+ | `cookie_httponly` | Prevents JavaScript from accessing the cookie | Defined by implementation |
111
+ | `cookie_secure` | Sends cookies only over HTTPS | Defined by implementation |
112
+ | `cookie_samesite` | Controls the SameSite cookie policy | Defined by implementation |
113
+
114
+ ## Example
115
+
116
+ ```python
117
+ from khp_secure import KHPConfig
118
+
119
+ config = KHPConfig(
120
+ session_lifetime=7200,
121
+ cookie_secure=False
122
+ )
123
+ ```
124
+
125
+ In this example:
126
+
127
+ - `session_lifetime=7200` means the session remains valid for two hours.
128
+ - `cookie_secure=False` allows cookies to work over HTTP during local development.
129
+
130
+ **Production recommendation:** Always use HTTPS and set `cookie_secure=True` in production environments.
131
+
132
+ ---
133
+
134
+ # 4. KHP
135
+
136
+ `KHP` is the main class of the library. It provides access to authentication, password management, and session management functionality.
137
+
138
+ ## Initialization
139
+
140
+ ```python
141
+ from khp_secure import KHP, KHPConfig
142
+
143
+ secure = KHP(
144
+ config=KHPConfig(
145
+ session_lifetime=3600,
146
+ cookie_secure=False
147
+ )
148
+ )
149
+ ```
150
+
151
+ It is recommended to create a single `KHP` instance and reuse it throughout your application.
152
+
153
+ ---
154
+
155
+ # 5. Password Management
156
+
157
+ KHP Secure provides two main methods for password management.
158
+
159
+ ## 5.1 hash_password()
160
+
161
+ Generates a secure password hash using Argon2id.
162
+
163
+ ### Syntax
164
+
165
+ ```python
166
+ secure.hash_password(password)
167
+ ```
168
+
169
+ ### Example
170
+
171
+ ```python
172
+ password_hash = secure.hash_password(
173
+ "my-secret-password"
174
+ )
175
+
176
+ print(password_hash)
177
+ ```
178
+
179
+ ### When to Use It
180
+
181
+ Use this method when:
182
+
183
+ - Registering a new user.
184
+ - Changing an existing user's password.
185
+ - Creating an initial administrator account.
186
+
187
+ **Security Note:** Never store plain-text passwords in your database. Store only the generated password hash.
188
+
189
+ ## 5.2 verify_password()
190
+
191
+ Verifies whether a provided password matches a previously generated password hash.
192
+
193
+ ### Syntax
194
+
195
+ ```python
196
+ secure.verify_password(password, password_hash)
197
+ ```
198
+
199
+ ### Example
200
+
201
+ ```python
202
+ password = "my-secret-password"
203
+
204
+ is_valid = secure.verify_password(
205
+ password,
206
+ password_hash
207
+ )
208
+
209
+ if is_valid:
210
+ print("Password is correct")
211
+ else:
212
+ print("Invalid password")
213
+ ```
214
+
215
+ ### When to Use It
216
+
217
+ Use this method during the login process to verify the user's credentials.
218
+
219
+ ---
220
+
221
+ # 6. Session Management
222
+
223
+ A session allows an application to identify an authenticated user without requiring the user to send their password with every request.
224
+
225
+ KHP Secure provides three main session management methods.
226
+
227
+ ## 6.1 login()
228
+
229
+ Creates a new authentication session and sends the session cookie to the client's browser.
230
+
231
+ ### Syntax
232
+
233
+ ```python
234
+ await secure.login(response, user_id)
235
+ ```
236
+
237
+ ### Example
238
+
239
+ ```python
240
+ from fastapi import Response
241
+
242
+ @app.post("/login")
243
+ async def login(response: Response):
244
+
245
+ user_id = 10
246
+
247
+ await secure.login(
248
+ response,
249
+ user_id
250
+ )
251
+
252
+ return {
253
+ "message": "Login successful"
254
+ }
255
+ ```
256
+
257
+ ### When to Use It
258
+
259
+ Call `login()` after successfully validating the user's credentials.
260
+
261
+ **Important:** This method does not automatically retrieve users or verify passwords. Your application is responsible for validating credentials before creating a session.
262
+
263
+ ## 6.2 required()
264
+
265
+ Creates a FastAPI dependency that validates the authentication session.
266
+
267
+ ### Syntax
268
+
269
+ ```python
270
+ secure.required()
271
+ ```
272
+
273
+ ### Example
274
+
275
+ ```python
276
+ from fastapi import Depends
277
+
278
+ @app.get("/dashboard")
279
+ async def dashboard(
280
+ user=Depends(secure.required())
281
+ ):
282
+ return {
283
+ "message": "Welcome",
284
+ "user": user
285
+ }
286
+ ```
287
+
288
+ ### Behavior
289
+
290
+ - If the session is valid, the authenticated user information is provided to the endpoint.
291
+ - If the session is missing or invalid, the library returns an HTTP 401 Unauthorized response.
292
+
293
+ ### When to Use It
294
+
295
+ Use `required()` whenever you need to protect an endpoint that should only be accessible to authenticated users.
296
+
297
+ Examples:
298
+
299
+ - User profiles.
300
+ - Dashboards.
301
+ - Account settings.
302
+ - Private resources.
303
+
304
+ ## 6.3 logout()
305
+
306
+ Terminates the current authentication session and handles the authentication cookie.
307
+
308
+ ### Syntax
309
+
310
+ ```python
311
+ await secure.logout(request, response)
312
+ ```
313
+
314
+ ### Example
315
+
316
+ ```python
317
+ from fastapi import Request, Response
318
+
319
+ @app.post("/logout")
320
+ async def logout(
321
+ request: Request,
322
+ response: Response
323
+ ):
324
+ await secure.logout(
325
+ request,
326
+ response
327
+ )
328
+
329
+ return {
330
+ "message": "Logged out"
331
+ }
332
+ ```
333
+
334
+ ### When to Use It
335
+
336
+ Call `logout()` when a user requests to terminate their authenticated session.
337
+
338
+ ---
339
+
340
+ # 7. SessionStore
341
+
342
+ KHP Secure includes a default `SessionStore` implementation that stores sessions in application memory.
343
+
344
+ ## Importing SessionStore
345
+
346
+ ```python
347
+ from khp_secure import SessionStore
348
+
349
+ store = SessionStore()
350
+ ```
351
+
352
+ ## Important Limitations
353
+
354
+ The current implementation uses in-memory storage.
355
+
356
+ This means:
357
+
358
+ 1. All stored sessions disappear when the application restarts.
359
+ 2. Sessions are not automatically shared between multiple application workers.
360
+ 3. The default implementation is not a persistent database storage solution.
361
+
362
+ The current `SessionStore` should not be considered a ready-to-use adapter for:
363
+
364
+ - PostgreSQL.
365
+ - MySQL.
366
+ - SQLite.
367
+ - Redis.
368
+ - Other external storage systems.
369
+
370
+ Persistent and shared session storage is a planned improvement.
371
+
372
+ ---
373
+
374
+ # 8. Complete Authentication Example
375
+
376
+ The following example demonstrates how to integrate KHP Secure into a simple FastAPI authentication system.
377
+
378
+ ```python
379
+ from fastapi import (
380
+ FastAPI,
381
+ Depends,
382
+ Request,
383
+ Response,
384
+ HTTPException
385
+ )
386
+
387
+ from khp_secure import KHP, KHPConfig
388
+
389
+ app = FastAPI()
390
+
391
+ secure = KHP(
392
+ config=KHPConfig(
393
+ session_lifetime=3600,
394
+ cookie_secure=False
395
+ )
396
+ )
397
+
398
+ # Demo users only.
399
+ # Replace this dictionary with a real database.
400
+
401
+ users = {
402
+ "admin": {
403
+ "id": 1,
404
+ "password": secure.hash_password("123456")
405
+ }
406
+ }
407
+
408
+
409
+ @app.post("/login")
410
+ async def login(
411
+ username: str,
412
+ password: str,
413
+ response: Response
414
+ ):
415
+
416
+ user = users.get(username)
417
+
418
+ if not user:
419
+ raise HTTPException(
420
+ status_code=401,
421
+ detail="Invalid credentials"
422
+ )
423
+
424
+ if not secure.verify_password(
425
+ password,
426
+ user["password"]
427
+ ):
428
+ raise HTTPException(
429
+ status_code=401,
430
+ detail="Invalid credentials"
431
+ )
432
+
433
+ await secure.login(
434
+ response,
435
+ user["id"]
436
+ )
437
+
438
+ return {
439
+ "message": "Login successful"
440
+ }
441
+
442
+
443
+ @app.get("/profile")
444
+ async def profile(
445
+ user=Depends(secure.required())
446
+ ):
447
+ return {
448
+ "user": user
449
+ }
450
+
451
+
452
+ @app.post("/logout")
453
+ async def logout(
454
+ request: Request,
455
+ response: Response
456
+ ):
457
+
458
+ await secure.logout(
459
+ request,
460
+ response
461
+ )
462
+
463
+ return {
464
+ "message": "Logout successful"
465
+ }
466
+ ```
467
+
468
+ ### Example Endpoints
469
+
470
+ | Method | Endpoint | Description |
471
+ |---|---|---|
472
+ | POST | `/login` | Authenticate a user |
473
+ | GET | `/profile` | Access the authenticated user's profile |
474
+ | POST | `/logout` | Terminate the current session |
475
+
476
+ > **Note:** This example is intended for demonstration purposes only. A real application should use a database, proper input validation, additional security protections, and appropriate error handling.
477
+
478
+ ---
479
+
480
+ # 9. Current API Reference
481
+
482
+ The following table summarizes the currently documented public API.
483
+
484
+ | Function / Class | Description |
485
+ |---|---|
486
+ | `KHP()` | Creates the main authentication manager |
487
+ | `KHPConfig()` | Configures authentication and cookie settings |
488
+ | `hash_password()` | Generates a password hash |
489
+ | `verify_password()` | Verifies a password against its hash |
490
+ | `login()` | Creates an authentication session |
491
+ | `logout()` | Terminates an authentication session |
492
+ | `required()` | Protects FastAPI endpoints |
493
+ | `SessionStore()` | Provides in-memory session storage |
494
+
495
+ ## Synchronous and Asynchronous Methods
496
+
497
+ KHP Secure currently uses both synchronous and asynchronous methods.
498
+
499
+ ### Asynchronous Methods
500
+
501
+ The following methods must be called using `await`:
502
+
503
+ ```python
504
+ await secure.login(response, user_id)
505
+
506
+ await secure.logout(request, response)
507
+ ```
508
+
509
+ ### Synchronous Methods
510
+
511
+ The following methods do not require `await`:
512
+
513
+ ```python
514
+ password_hash = secure.hash_password("password")
515
+
516
+ is_valid = secure.verify_password(
517
+ "password",
518
+ password_hash
519
+ )
520
+ ```
521
+
522
+ **Important:** `required()` is used to create a FastAPI dependency and is passed to `Depends()`.
523
+
524
+ ---
525
+
526
+ # 10. Security Considerations
527
+
528
+ Before using KHP Secure in a production environment, the following security improvements should be implemented and independently reviewed.
529
+
530
+ 1. **Persistent Session Storage:** Implement persistent storage to prevent sessions from disappearing after application restarts.
531
+ 2. **Shared Storage:** Support session sharing across multiple application workers and instances.
532
+ 3. **CSRF Protection:** Protect cookie-based authentication endpoints against Cross-Site Request Forgery.
533
+ 4. **Session Rotation:** Regenerate session identifiers after login and privilege changes.
534
+ 5. **HTTPS and Secure Cookies:** Enforce HTTPS and secure cookie settings in production.
535
+ 6. **Rate Limiting:** Limit repeated login attempts to reduce brute-force attacks.
536
+ 7. **Session Expiration:** Properly test session expiration and invalidation.
537
+ 8. **Cookie Handling:** Correctly handle invalid sessions and cookie deletion.
538
+ 9. **Password Security:** Review Argon2 parameters and password policies.
539
+ 10. **Security Testing:** Perform automated and independent security testing.
540
+
541
+ ---
542
+
543
+ # 11. Roadmap
544
+
545
+ The following features are planned for future versions. They are not currently available unless explicitly implemented in a released version.
546
+
547
+ - [ ] PostgreSQL Adapter
548
+ - [ ] MySQL Adapter
549
+ - [ ] SQLite Adapter
550
+ - [ ] Redis Adapter
551
+ - [ ] Synchronous API
552
+ - [ ] Flask Integration
553
+ - [ ] Django Integration
554
+ - [ ] CSRF Protection
555
+ - [ ] Roles and Permissions
556
+ - [ ] Session Rotation
557
+ - [ ] Remember Me
558
+ - [ ] Password Reset
559
+ - [ ] Automated Test Suite
560
+
561
+ ---
562
+
563
+ # 12. Project Status
564
+
565
+ **KHP Secure — Early Prototype**
566
+
567
+ KHP Secure currently provides a simple foundation for password hashing, session management, cookie-based authentication, and FastAPI endpoint protection.
568
+
569
+ The library is still under development and should not be considered production-ready.
570
+
571
+ ### Project Information
572
+
573
+ | Property | Value |
574
+ |---|---|
575
+ | Project Name | KHP Secure |
576
+ | Author | KHP Studio |
577
+ | Language | Python |
578
+ | Initial Framework Integration | FastAPI |
579
+ | Authentication Type | Session-Based |
580
+ | Password Hashing | Argon2id |
581
+ | Project Status | Early Prototype |
582
+
583
+ ---
584
+
585
+ # 13. Important Documentation Notice
586
+
587
+ This documentation describes the API and functionality available in the current documented version of KHP Secure.
588
+
589
+ Some configuration defaults and internal implementation details must be verified against the actual source code before treating this document as the definitive API specification.
590
+
591
+ For the latest implementation details, always refer to the source code of the corresponding release.
592
+
593
+ **KHP Secure — Simple Authentication. Secure Sessions. Python.**