-
Notifications
You must be signed in to change notification settings - Fork 7
feat: remove jwt library and implement jwt manually #21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,61 @@ | ||||||||||||||||||||
|
|
||||||||||||||||||||
| import base64 | ||||||||||||||||||||
| import json | ||||||||||||||||||||
| import hmac | ||||||||||||||||||||
| import hashlib | ||||||||||||||||||||
| import time | ||||||||||||||||||||
|
|
||||||||||||||||||||
| def b64_encode(data: bytes) -> str: | ||||||||||||||||||||
| return base64.urlsafe_b64encode(data).rstrip(b"=").decode("utf-8") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| def b64_decode(data: str) -> bytes: | ||||||||||||||||||||
| padding = b"=" * (4 - (len(data) % 4)) | ||||||||||||||||||||
| return base64.urlsafe_b64decode(data.encode("utf-8") + padding) | ||||||||||||||||||||
|
Comment on lines
+11
to
+13
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fix Base64 padding (current code adds 4 "=" when none needed). When len%4==0 you still append four "=" causing decode errors. Compute missing padding modulo 4. Apply: -def b64_decode(data: str) -> bytes:
- padding = b"=" * (4 - (len(data) % 4))
- return base64.urlsafe_b64decode(data.encode("utf-8") + padding)
+def b64_decode(data: str) -> bytes:
+ # Add only the required padding (0..3)
+ missing = (-len(data)) % 4
+ if missing:
+ data += "=" * missing
+ return base64.urlsafe_b64decode(data.encode("utf-8"))📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||
|
|
||||||||||||||||||||
| def jwt_encode(payload: dict, secret: str, algorithm: str = "HS256") -> str: | ||||||||||||||||||||
| header = {"alg": algorithm, "typ": "JWT"} | ||||||||||||||||||||
|
|
||||||||||||||||||||
| encoded_header = b64_encode(json.dumps(header, separators=(",", ":")).encode("utf-8")) | ||||||||||||||||||||
| encoded_payload = b64_encode(json.dumps(payload, separators=(",", ":")).encode("utf-8")) | ||||||||||||||||||||
|
|
||||||||||||||||||||
| signing_input = f"{encoded_header}.{encoded_payload}".encode("utf-8") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if algorithm == "HS256": | ||||||||||||||||||||
| signature = hmac.new(secret.encode("utf-8"), signing_input, hashlib.sha256).digest() | ||||||||||||||||||||
| else: | ||||||||||||||||||||
| raise ValueError("Unsupported algorithm") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| encoded_signature = b64_encode(signature) | ||||||||||||||||||||
|
|
||||||||||||||||||||
| return f"{encoded_header}.{encoded_payload}.{encoded_signature}" | ||||||||||||||||||||
|
|
||||||||||||||||||||
| def jwt_decode(token: str, secret: str, algorithms: list[str] = ["HS256"]) -> dict: | ||||||||||||||||||||
| try: | ||||||||||||||||||||
| encoded_header, encoded_payload, encoded_signature = token.split(".") | ||||||||||||||||||||
| except ValueError: | ||||||||||||||||||||
| raise ValueError("Invalid token") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| header_data = json.loads(b64_decode(encoded_header)) | ||||||||||||||||||||
| alg = header_data.get("alg") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if not alg or alg not in algorithms: | ||||||||||||||||||||
| raise ValueError("Invalid algorithm") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| signing_input = f"{encoded_header}.{encoded_payload}".encode("utf-8") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if alg == "HS256": | ||||||||||||||||||||
| expected_signature = hmac.new(secret.encode("utf-8"), signing_input, hashlib.sha256).digest() | ||||||||||||||||||||
| else: | ||||||||||||||||||||
| raise ValueError("Unsupported algorithm") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| decoded_signature = b64_decode(encoded_signature) | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if not hmac.compare_digest(decoded_signature, expected_signature): | ||||||||||||||||||||
| raise ValueError("Invalid signature") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| payload = json.loads(b64_decode(encoded_payload)) | ||||||||||||||||||||
|
|
||||||||||||||||||||
| if "exp" in payload and payload["exp"] < time.time(): | ||||||||||||||||||||
| raise ValueError("Token has expired") | ||||||||||||||||||||
|
|
||||||||||||||||||||
| return payload | ||||||||||||||||||||
|
Comment on lines
+33
to
+61
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Normalize decode errors to ValueError to avoid 500s upstream. Base64/JSON errors currently leak as non‑ValueError; Apply: - try:
- encoded_header, encoded_payload, encoded_signature = token.split(".")
- except ValueError:
- raise ValueError("Invalid token")
+ try:
+ encoded_header, encoded_payload, encoded_signature = token.split(".")
+ except ValueError:
+ raise ValueError("Invalid token") from None
@@
- header_data = json.loads(b64_decode(encoded_header))
+ try:
+ header_data = json.loads(b64_decode(encoded_header))
+ except Exception:
+ raise ValueError("Invalid token") from None
@@
- decoded_signature = b64_decode(encoded_signature)
+ try:
+ decoded_signature = b64_decode(encoded_signature)
+ except Exception:
+ raise ValueError("Invalid token") from None
@@
- payload = json.loads(b64_decode(encoded_payload))
+ try:
+ payload = json.loads(b64_decode(encoded_payload))
+ except Exception:
+ raise ValueError("Invalid token") from None🧰 Tools🪛 Ruff (0.14.1)36-36: Within an (B904) 36-36: Avoid specifying long messages outside the exception class (TRY003) 42-42: Avoid specifying long messages outside the exception class (TRY003) 49-49: Avoid specifying long messages outside the exception class (TRY003) 54-54: Avoid specifying long messages outside the exception class (TRY003) 59-59: Avoid specifying long messages outside the exception class (TRY003) |
||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,5 @@ setuptools==68.2.0 | |
| aiohttp==3.9.5 | ||
| psycopg2-binary==2.9.9 | ||
|
|
||
| PyJWT==2.9.0 | ||
| pytest==8.2.2 | ||
| PyYAML>=5.1 | ||
| PyYAML>=5.1 | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🧩 Analysis chainLGTM; confirm tests don’t rely on PyJWT. PyJWT is removed project-wide; ensure no tests still import it. See fix proposed in tests/test_custom_snippet.py. Run to find stragglers: 🏁 Script executed: #!/bin/bash
rg -nP '^\s*import\s+jwt\b|jwt\.(encode|decode)\b|from\s+jwt\s+import' -g '!**/.venv/**' -SLength of output: 1747 Critical: Tests still import PyJWT despite removal from requirements.txt. The verification found multiple test files that still import and use PyJWT:
Removing PyJWT from requirements.txt will break these tests. Either update tests to not rely on PyJWT, or retain the dependency in requirements.txt. 🤖 Prompt for AI Agents |
||
| Original file line number | Diff line number | Diff line change | ||||||
|---|---|---|---|---|---|---|---|---|
|
|
@@ -9,7 +9,7 @@ | |||||||
| import jwt | ||||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove PyJWT usage in tests; use local jwt helper. PyJWT is no longer a dependency; this import will fail. Apply: -import jwt
+import time
+from lightapi.jwt_custom import jwt_encode📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||
| from starlette.testclient import TestClient | ||||||||
|
|
||||||||
| from examples.07_middleware_cors_auth import Company, CustomEndpoint, create_app | ||||||||
| from examples.middleware_cors_auth import Company, CustomEndpoint, create_app | ||||||||
| from lightapi.config import config | ||||||||
| from lightapi.core import Middleware, Response | ||||||||
| from lightapi.lightapi import LightApi | ||||||||
|
|
||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make typing Python 3.8‑compatible and remove mutable default.
list[str]breaks on 3.8 and default list violates B006; pipeline is failing. Use Optional[List[str]] and set default inside.Apply:
And inside
jwt_decodebefore usingalgorithms:Also applies to: 32-32
🤖 Prompt for AI Agents