refactor: common configuration and authentication modularization - #92
Conversation
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 39 minutes and 55 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (5)
📝 Walkthrough개요JWT 인증 및 구성 관리를 중앙화하기 위해 새로운 변경사항
코드 리뷰 예상 소요시간🎯 3 (중간) | ⏱️ ~20분 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@core/auth.py`:
- Around line 24-27: The code decodes settings.secret_key into signing_key
(padded_key, signing_key) and calls jwt.decode, but a non-base64 SECRET_KEY will
raise binascii.Error; catch binascii.Error around the base64.urlsafe_b64decode
call and convert it to a consistent authentication configuration error (e.g.,
raise a clear AuthConfigError or ValueError used by your auth flow) so the
failure is handled uniformly by the jwt.decode path; ensure the exception
message includes the problematic settings.secret_key reference and that
jwt.decode is only called when signing_key is successfully derived.
In `@core/settings.py`:
- Around line 38-48: The resolved_dept_map_path should treat a relative
dept_map_path as relative to the repo root instead of the current working
directory: update the resolved_dept_map_path property to check if dept_map_path
is provided and whether Path(self.dept_map_path).is_absolute(); if absolute,
expanduser()/resolve() as now, but if relative, join it with self.repo_root
(e.g. self.repo_root / self.dept_map_path) before resolving. Reference the
properties repo_root, resolved_dept_map_path, dept_map_path and root_base_path
when making the change.
In `@image_analysis/timetable_analysis.py`:
- Around line 16-17: After reading settings with get_settings() and assigning
SPRING_TIMETABLE_URL, validate that SPRING_TIMETABLE_URL is set
(non-empty/non-None) and fail fast if not; update timetable_analysis.py to check
the value right after SPRING_TIMETABLE_URL is assigned and raise a clear error
(e.g., ValueError or RuntimeError) or return a rejected response so the task is
not enqueued when the URL is missing, referencing get_settings and
SPRING_TIMETABLE_URL so the check is easy to locate.
In `@LLM/OSS/Open_AI_OSS.py`:
- Around line 98-99: Validate that settings.oss_api_key and settings.oss_model
are present before creating client or assigning OSS_MODEL: check both are not
None/empty at module initialization and raise a clear, descriptive exception
(e.g., ValueError) if missing, then only create client = OpenAI(...) and set
OSS_MODEL afterwards; also ensure call_oss() continues to use OSS_MODEL so it
won't encounter a late failure. This makes failures immediate and the error
message explicit rather than letting OpenAI SDK or call_oss() fail later.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: f5d3da37-2f82-4a46-acb3-0c1b5990f487
📒 Files selected for processing (7)
LLM/OSS/Open_AI_OSS.pycore/__init__.pycore/auth.pycore/settings.pyimage_analysis/timetable_analysis.pytext_filtering/text_filtering.pytext_filtering/text_filtering_rule.py
| try: | ||
| padded_key = settings.secret_key + "=" * (-len(settings.secret_key) % 4) | ||
| signing_key = base64.urlsafe_b64decode(padded_key) | ||
| payload = jwt.decode(token, signing_key, algorithms=[settings.algorithm]) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# 설명: Python base64 디코딩이 잘못된 설정값에서 예외를 낼 수 있음을 확인합니다.
python - <<'PY'
import base64
for value in ["abcde", "not-a-valid-base64!"]:
padded = value + "=" * (-len(value) % 4)
try:
decoded = base64.urlsafe_b64decode(padded)
print(value, "=>", decoded)
except Exception as exc:
print(value, "=>", type(exc).__name__, str(exc))
PYRepository: dongsooop/AI
Length of output: 216
🏁 Script executed:
# First, let's inspect the actual core/auth.py file
head -50 core/auth.py | cat -nRepository: dongsooop/AI
Length of output: 1637
🏁 Script executed:
# Let's also verify the exact exception type raised by base64.urlsafe_b64decode
python - <<'PY'
import base64
import binascii
# Test exact exception types
for value in ["abcde", "not-a-valid-base64!"]:
padded = value + "=" * (-len(value) % 4)
try:
decoded = base64.urlsafe_b64decode(padded)
except Exception as exc:
print(f"Value: {value}")
print(f" Exception type: {type(exc).__name__}")
print(f" Exception module: {type(exc).__module__}")
print(f" Is binascii.Error: {isinstance(exc, binascii.Error)}")
print(f" Is ValueError: {isinstance(exc, ValueError)}")
print(f" Full repr: {repr(exc)}")
print()
PYRepository: dongsooop/AI
Length of output: 460
잘못된 base64 시크릿을 명시적으로 처리하세요.
SECRET_KEY가 base64 형식이 아닌 경우 25-26줄에서 binascii.Error 예외가 그대로 전파됩니다. 인증 설정 오류로 일관되게 처리해야 합니다.
🐛 제안 수정
import base64
+import binascii
from fastapi import HTTPException, Request
@@
try:
padded_key = settings.secret_key + "=" * (-len(settings.secret_key) % 4)
signing_key = base64.urlsafe_b64decode(padded_key)
payload = jwt.decode(token, signing_key, algorithms=[settings.algorithm])
username = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token: no subject")
return username
+ except (binascii.Error, ValueError) as exc:
+ raise HTTPException(status_code=500, detail="Server auth configuration invalid") from exc
except ExpiredSignatureError as exc:
raise HTTPException(status_code=401, detail="Token has expired") from exc🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@core/auth.py` around lines 24 - 27, The code decodes settings.secret_key into
signing_key (padded_key, signing_key) and calls jwt.decode, but a non-base64
SECRET_KEY will raise binascii.Error; catch binascii.Error around the
base64.urlsafe_b64decode call and convert it to a consistent authentication
configuration error (e.g., raise a clear AuthConfigError or ValueError used by
your auth flow) so the failure is handled uniformly by the jwt.decode path;
ensure the exception message includes the problematic settings.secret_key
reference and that jwt.decode is only called when signing_key is successfully
derived.
관련 이슈
Close #91
🎯 배경
🔍 주요 내용
core/settings.py,core/auth.py구축하여 환경 변수 및 검증 통합