Skip to content

[bug] Backend uses non-thread-safe global variables for location caching #33

@pragnyanramtha

Description

@pragnyanramtha

Bug Description

The backend uses global variables (LAST_IP_LAT, LAST_IP_LON, IP_FETCHED) with the global keyword for caching user location. This is not thread-safe in FastAPI's asynchronous environment.

Location

backend/routers/medicines.py (lines 10-27)

Current Code

LAST_IP_LAT = 18.5204
LAST_IP_LON = 73.8567
IP_FETCHED = False

def get_default_location():
    global LAST_IP_LAT, LAST_IP_LON, IP_FETCHED
    if IP_FETCHED:
        return LAST_IP_LAT, LAST_IP_LON
    try:
        # ... fetch location ...
        IP_FETCHED = True
        return LAST_IP_LAT, LAST_IP_LON
    except Exception:
        return 18.5204, 73.8567

Problem

FastAPI handles concurrent requests asynchronously. Global variables modified with global keyword can cause:

  • Race conditions
  • Inconsistent state between requests
  • Potential security issues (one user getting another user's location)

Suggested Fix

Use one of these approaches:

  1. FastAPI's app state: request.app.state.last_ip_lat
  2. functools.lru_cache for the location fetch function
  3. A proper caching solution (Redis, etc.)

Impact

  • Race conditions under concurrent requests
  • Potential data leakage between users
  • Unreliable location caching

Labels

bug, backend, security, help wanted

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions