implemented the rate limiting#307
Open
Qoder-Undefined wants to merge 4 commits into
Open
Conversation
Contributor
|
hi @Qoder-Undefined , The payment auth changes look good, but the auth rate-limiting implementation introduced a circular import. auth.py is importing limiter from app.main, while main.py imports the API router, which eventually imports auth.py. This causes pytest to fail during startup with ImportError: cannot import name 'limiter' from partially initialized module 'app.main'. Please move the limiter configuration into a separate module (e.g. app/core/rate_limit.py) and import it from there in both main.py and auth.py. That will break the circular dependency and allow the test suite to load correctly |
Contributor
|
@Qoder-Undefined , please look in to ci , its failing |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
HIGH —implemented the Backend Security Hardening (Rate Limiting + Auth Guards + Stub Endpoints)
Description
Layer: Backend — auth.py, payments.py, artisan.py
Effort: Large (6–8h)
Three related security gaps consolidated into one hardening pass.
A. Rate Limiting on Auth Endpoints
Problem
The following endpoints have no throttling:
POST /auth/login
POST /auth/register
POST /auth/refresh
Brute-force attacks and registration spam are currently unmitigated.
Required Changes
Install and Configure SlowAPI
Install slowapi
Configure rate limiting in main.py
Add slowapi to requirements.txt
Endpoint Limits
Endpoint Limit
/auth/login 5 requests/minute/IP
/auth/register 3 requests/hour/IP
/auth/refresh 10 requests/minute/IP
Error Handling
When limits are exceeded:
Return HTTP 429 Too Many Requests
Include a Retry-After header
B. Payment Release/Refund Missing Authentication
Problem
The following endpoints have no authentication dependency:
POST /payments/release
POST /payments/refund
Any unauthenticated caller can currently trigger fund release or refund operations.
By comparison:
POST /payments/prepare
POST /payments/submit
already correctly use:
Depends(require_client)
Required Changes
Release Endpoint
Add:
Depends(require_admin)
to:
release()
Refund Endpoint
Add:
Depends(require_admin)
to:
refund()
Audit Logging
Log the authenticated admin user who performed:
Release actions
Refund actions
Example:
logger.info(
"Admin %s triggered refund for payment %s",
admin_user.id,
payment_id
)
C. Stub Endpoints Return Fake Success
Problem
Several artisan endpoints currently return placeholder responses without performing actual database operations.
Endpoint Problem
DELETE /artisans/{id} Returns success but never deletes from DB
PUT /artisans/availability Accepts raw dict, echoes input, no DB write
GET /artisans/my-portfolio Always returns [] with TODO
POST /artisans/portfolio/add Returns "simulation", nothing stored
Required Changes
DELETE /artisans/{id}
Implement actual database deletion.
Requirements:
Verify artisan exists
Delete record from database
Return 404 if not found
Return 403 if caller lacks permission
Example:
artisan = db.query(Artisan).filter(
Artisan.id == artisan_id
).first()
if not artisan:
raise HTTPException(404, "Artisan not found")
db.delete(artisan)
db.commit()
PUT /artisans/availability
Replace raw dict payload with a Pydantic schema.
Example:
class AvailabilityUpdate(BaseModel):
is_available: bool
Requirements:
Persist update to database
Return updated artisan record
Return 404 when artisan not found
GET /artisans/my-portfolio
Replace TODO implementation.
Requirements:
Query actual portfolio records
Return authenticated artisan's portfolio entries
Return empty list only when no records exist
Example:
portfolio_items = (
db.query(Portfolio)
.filter(Portfolio.artisan_id == current_user.id)
.all()
)
POST /artisans/portfolio/add
Replace simulation response.
Requirements:
Create actual Portfolio record
Validate request with Pydantic schema
Persist to database
Return created object
Example:
class PortfolioCreate(BaseModel):
title: str
description: str
image_url: str
Acceptance Criteria
15 rapid login attempts trigger HTTP 429
Unauthenticated /payments/release returns HTTP 401
Unauthenticated /payments/refund returns HTTP 401
DELETE /artisans/{id} actually deletes from DB
Deletion verified by subsequent GET request
PUT /artisans/availability updates is_available in DB
Portfolio endpoints create real records
Portfolio endpoints read real records
All existing tests pass
New tests added and passing
Verification
Rate Limiting Tests
backend/app/tests/test_rate_limiting.py
Test cases:
Login throttling
Registration throttling
Refresh token throttling
Retry-After header validation
Payment Authentication Tests
backend/app/tests/test_payment_auth_guards.py
Test cases:
Unauthenticated release → 401
Unauthenticated refund → 401
Admin release → 200
Admin refund → 200
Stub Endpoint Tests
backend/app/tests/test_stub_endpoints.py
Test cases:
Delete artisan persists deletion
Availability updates database value
Portfolio creation persists data
Portfolio retrieval returns stored records
Definition of Done
pytest
passes successfully.
cargo clippy -- -D warnings
(or equivalent backend linting configuration)
passes cleanly with zero warnings.
Security hardening is verified and all acceptance criteria are met.
closes #291