diff --git a/.github/workflows/audit-checks.yml b/.github/workflows/audit-checks.yml new file mode 100644 index 0000000..c9aa558 --- /dev/null +++ b/.github/workflows/audit-checks.yml @@ -0,0 +1,14 @@ +name: Audit repair checks +on: [push, pull_request] +permissions: + contents: read +jobs: + offline-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + - run: pip install -r requirements-test.txt + - run: pytest -q diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8f0bcc6 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ + +.env +.env.* +!.env.example +__pycache__/ +*.pyc diff --git a/AUDIT_FIXES.md b/AUDIT_FIXES.md new file mode 100644 index 0000000..89172ff --- /dev/null +++ b/AUDIT_FIXES.md @@ -0,0 +1,17 @@ +# Server-side access controls + +Repair branch: `fix/internship-audit-20261010`. Changes are scoped to audit findings; no deployment or live provider action is included. + +## Changed + +Added server-issued JWT sessions, bcrypt account verification, doctor/nurse roles and patient-to-record binding. Browser-supplied roles/password constants no longer authorize access. Patient reads are scoped to the configured identity, and clinical writes/audits require the appropriate role. Groq calls are awaited; missing configuration does not create a fabricated successful report. Tracked environment and bytecode files were removed and safe environment examples added. + +## Verification + +`pytest -q; cd frontend && npm ci && npm run build` + +Commands are entry points, not a claim that every live integration was executed. See the repair bundle for actual results. + +## Setup and remaining evidence + +Backend: copy backend/.env.example into backend/.env; use CAREFLOW_JWT_SECRET with 32+ random characters and CAREFLOW_USERS_JSON containing username, password_hash, role and patient_id for patient accounts. Generate bcrypt hashes offline (never store plaintext passwords). Start backend from its directory with uvicorn main:app; the active frontend is frontend/, not the historical backend/frontend scaffold. Frontend uses NEXT_PUBLIC_API_URL. Seed patients only with SEED_SYNTHETIC_PATIENTS=true. Previously committed credentials remain in Git history: rotate them before reuse. Real Mongo/provider integration, clinical output validation and medical accuracy remain unverified. This is a synthetic-data prototype, not a validated clinical system. diff --git a/README.md b/README.md index 7274ae9..138fbc1 100644 Binary files a/README.md and b/README.md differ diff --git a/backend/.env b/backend/.env deleted file mode 100644 index 185c075..0000000 --- a/backend/.env +++ /dev/null @@ -1,9 +0,0 @@ -# MONGODB_URL=mongodb+srv://arvindkumar197g_db_user:hXuHhv4pzeyMvmHb@cluster0.gefpku0.mongodb.net/?appName=Cluster0 -# GROQ_API_KEY=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 - -# MONGO_URL=mongodb+srv://arvindkumar197g_db_user:hXuHhv4pzeyMvmHb@cluster0.gefpku0.mongodb.net/careflow_db?retryWrites=true&w=majority -# GROQ_API_KEY=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 - -MONGO_URL=mongodb+srv://arvindkumar197g_db_user:hXuHhv4pzeyMvmHb@cluster0.gefpku0.mongodb.net/careflow?retryWrites=true&w=majority -GROQ_API_KEY=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 -PORT=8000 \ No newline at end of file diff --git a/backend/.env.example b/backend/.env.example new file mode 100644 index 0000000..6a95211 --- /dev/null +++ b/backend/.env.example @@ -0,0 +1,8 @@ +MONGO_URL=mongodb://localhost:27017 +GROQ_API_KEY= +# Generate a unique secret; do not use this file's comments as credentials. +CAREFLOW_JWT_SECRET= +# JSON array of username, bcrypt password_hash, role and optional bound patient_id. +CAREFLOW_USERS_JSON=[] +FRONTEND_ORIGIN=http://localhost:3000 +SEED_SYNTHETIC_PATIENTS=false diff --git a/backend/__pycache__/ai_service.cpython-314.pyc b/backend/__pycache__/ai_service.cpython-314.pyc deleted file mode 100644 index 6328450..0000000 Binary files a/backend/__pycache__/ai_service.cpython-314.pyc and /dev/null differ diff --git a/backend/__pycache__/main.cpython-314.pyc b/backend/__pycache__/main.cpython-314.pyc deleted file mode 100644 index 8e01244..0000000 Binary files a/backend/__pycache__/main.cpython-314.pyc and /dev/null differ diff --git a/backend/auth.py b/backend/auth.py new file mode 100644 index 0000000..34a8585 --- /dev/null +++ b/backend/auth.py @@ -0,0 +1,76 @@ +"""Server-verified accounts for this single-instance synthetic-data demo.""" +import json +import os +from datetime import datetime, timedelta, timezone +from typing import Literal + +import bcrypt +import jwt +from fastapi import Depends, HTTPException +from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials +from pydantic import BaseModel, Field + +bearer = HTTPBearer() + + +class Account(BaseModel): + username: str + password_hash: str + role: Literal["doctor", "nurse", "patient"] + patient_id: str | None = None + + +class LoginRequest(BaseModel): + username: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=1, max_length=72) + + +def signing_key(): + value = os.getenv("CAREFLOW_JWT_SECRET", "") + if len(value) < 32: + raise HTTPException(503, "Authentication has not been configured") + return value + + +def accounts(): + try: + result = {row.username: row for row in (Account.model_validate(item) for item in json.loads(os.getenv("CAREFLOW_USERS_JSON", "[]")))} + except (ValueError, TypeError): + raise HTTPException(503, "Authentication configuration is invalid") + if any(row.role == "patient" and not row.patient_id for row in result.values()): + raise HTTPException(503, "Patient accounts require a patient_id binding") + return result + + +def login(payload: LoginRequest): + key = signing_key() + account = accounts().get(payload.username) + try: + valid = account is not None and bcrypt.checkpw(payload.password.encode(), account.password_hash.encode()) + except ValueError: + valid = False + if not valid: + raise HTTPException(401, "Invalid credentials") + token = jwt.encode({"sub": account.username, "exp": datetime.now(timezone.utc) + timedelta(hours=1)}, key, algorithm="HS256") + return {"access_token": token, "role": account.role, "patient_id": account.patient_id} + + +def current_account(credentials: HTTPAuthorizationCredentials = Depends(bearer)): + try: + claims = jwt.decode(credentials.credentials, signing_key(), algorithms=["HS256"], options={"require": ["exp", "sub"]}) + except jwt.InvalidTokenError: + raise HTTPException(401, "Invalid or expired session") + account = accounts().get(claims["sub"]) + if account is None: + raise HTTPException(401, "Account no longer active") + return account + + +def require_role(account, *roles): + if account.role not in roles: + raise HTTPException(403, "Access denied for this role") + + +def require_patient_access(account, patient_id): + if account.role == "patient" and account.patient_id != patient_id: + raise HTTPException(403, "Access denied to this patient") diff --git a/backend/main.py b/backend/main.py index 0642425..cbfa8eb 100644 --- a/backend/main.py +++ b/backend/main.py @@ -2,24 +2,25 @@ import json from datetime import datetime from typing import List -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Depends from pydantic import BaseModel from fastapi.middleware.cors import CORSMiddleware from dotenv import load_dotenv from motor.motor_asyncio import AsyncIOMotorClient from bson import ObjectId -from groq import Groq +from groq import AsyncGroq from faker import Faker # 1. Setup & Environment load_dotenv() +from auth import Account, LoginRequest, current_account, login, require_role, require_patient_access app = FastAPI() fake = Faker() # CORS logic - Taaki frontend connect ho sake app.add_middleware( CORSMiddleware, - allow_origins=["*"], + allow_origins=[os.getenv("FRONTEND_ORIGIN", "http://localhost:3000")], allow_methods=["*"], allow_headers=["*"], ) @@ -32,7 +33,7 @@ db = client.careflow tasks_collection = db.get_collection("tasks") patients_collection = db.get_collection("patients") -groq_client = Groq(api_key=GROQ_API_KEY) +groq_client = AsyncGroq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None # 2. Models class AnalysisRequest(BaseModel): @@ -57,18 +58,26 @@ async def seed_patients(): @app.on_event("startup") async def startup_event(): - await seed_patients() + if os.getenv("SEED_SYNTHETIC_PATIENTS", "false").lower() == "true": + await seed_patients() + +@app.post("/api/auth/login") +def authenticate(request: LoginRequest): + return login(request) # 4. API ENDPOINTS (Step 2) # A. Get All Patients (Real Database se) @app.get("/api/patients") -async def get_patients(): +async def get_patients(account: Account = Depends(current_account)): patients = [] - cursor = patients_collection.find({}).limit(50) + query = {"$or": [{"id": account.patient_id}]} if account.role == "patient" else {} + if account.role == "patient" and ObjectId.is_valid(account.patient_id): + query["$or"].append({"_id": ObjectId(account.patient_id)}) + cursor = patients_collection.find(query).limit(50) async for doc in cursor: patients.append({ - "id": str(doc["_id"]), # MongoDB ID ko string banana zaroori hai + "id": doc.get("id") or str(doc["_id"]), # MongoDB ID ko string banana zaroori hai "name": doc["name"], "status": doc["status"], "diagnosis": doc["diagnosis"], @@ -78,7 +87,8 @@ async def get_patients(): # B. Get Tasks for Specific Patient @app.get("/api/tasks/{patient_id}") -async def get_tasks(patient_id: str): +async def get_tasks(patient_id: str, account: Account = Depends(current_account)): + require_patient_access(account, patient_id) tasks = [] cursor = tasks_collection.find({"patient_id": patient_id}).sort("created_at", -1) async for doc in cursor: @@ -119,7 +129,10 @@ async def get_tasks(patient_id: str): @app.post("/api/analyze/{patient_id}") -async def analyze(patient_id: str, request: AnalysisRequest): +async def analyze(patient_id: str, request: AnalysisRequest, account: Account = Depends(current_account)): + require_role(account, "doctor") + if groq_client is None: + raise HTTPException(503, "AI provider is not configured") try: # Prompt ko aur strict kar diya taaki AI faltu bakwas na kare #prompt = f"Return ONLY a JSON object with a key 'tasks' containing a list of objects. Each object must have 'task' and 'category'. Note: {request.note}" @@ -136,7 +149,7 @@ async def analyze(patient_id: str, request: AnalysisRequest): The JSON must be complete. Format strictly as JSON: {{"tasks": [{{"task": "Exact text from note", "category": "Medication/Test/Vital"}}]}} Doctor's Note: {request.note} """ - completion = groq_client.chat.completion = groq_client.chat.completions.create( + completion = await groq_client.chat.completions.create( messages=[{"role": "user", "content": prompt}], model="llama-3.1-8b-instant", response_format={"type": "json_object"}, @@ -144,7 +157,6 @@ async def analyze(patient_id: str, request: AnalysisRequest): max_tokens=3072 # Taaki lamba list hone par bhi response pura aaye ) raw_content = completion.choices[0].message.content - print(f"🤖 AI Response: {raw_content}") # Terminal mein check karo ye kya aa raha hai res = json.loads(raw_content) @@ -168,12 +180,14 @@ async def analyze(patient_id: str, request: AnalysisRequest): return {"status": "no tasks found"} except Exception as e: - print(f"❌ ERROR: {str(e)}") # Ye terminal mein asli error dikhayega - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail="Request failed") # D. Toggle Task Status @app.patch("/api/tasks/{task_id}") -async def toggle_task(task_id: str): +async def toggle_task(task_id: str, account: Account = Depends(current_account)): + require_role(account, "nurse") + if not ObjectId.is_valid(task_id): + raise HTTPException(422, "Invalid task ID") task = await tasks_collection.find_one({"_id": ObjectId(task_id)}) if not task: raise HTTPException(status_code=404, detail="Task not found") @@ -192,7 +206,8 @@ async def toggle_task(task_id: str): import uuid @app.post("/api/patients") -async def register_patient(patient: dict): +async def register_patient(patient: dict, account: Account = Depends(current_account)): + require_role(account, "doctor") try: # Unique ID aur default Ward assign karna patient["id"] = str(uuid.uuid4())[:8].upper() # Short Unique ID e.g. CF72A1 @@ -200,12 +215,16 @@ async def register_patient(patient: dict): patient["ward_id"] = "WARD-01" await patients_collection.insert_one(patient) + patient.pop("_id", None) return {"status": "success", "patient": patient} except Exception as e: - raise HTTPException(status_code=500, detail=str(e)) + raise HTTPException(status_code=500, detail="Request failed") @app.post("/api/agent-audit/{patient_id}") -async def agent_audit(patient_id: str, request: AnalysisRequest): +async def agent_audit(patient_id: str, request: AnalysisRequest, account: Account = Depends(current_account)): + require_role(account, "doctor") + if groq_client is None: + raise HTTPException(503, "AI provider is not configured") try: # 1. Alag Prompt jo sirf 3 points nikalega audit_prompt = f""" @@ -219,7 +238,7 @@ async def agent_audit(patient_id: str, request: AnalysisRequest): """ # 2. Groq Call (Alag variable names ke saath taaki purana code na phate) - audit_completion = groq_client.chat.completions.create( + audit_completion = await groq_client.chat.completions.create( messages=[{"role": "user", "content": audit_prompt}], model="llama-3.1-8b-instant", response_format={"type": "json_object"}, @@ -230,7 +249,6 @@ async def agent_audit(patient_id: str, request: AnalysisRequest): return audit_data except Exception as e: - print(f"Audit Error: {e}") raise HTTPException(status_code=500, detail="Audit failed") if __name__ == "__main__": diff --git a/backend/requirements.txt b/backend/requirements.txt index 7b29940..734518b 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -51,3 +51,6 @@ uvicorn==0.42.0 Werkzeug==3.1.3 wheel==0.45.1 yt-dlp==2026.3.3 + +PyJWT>=2.9,<3 +bcrypt>=4,<6 diff --git a/frontend/app/page.tsx b/frontend/app/page.tsx index 377b29c..3ccd930 100644 --- a/frontend/app/page.tsx +++ b/frontend/app/page.tsx @@ -648,7 +648,7 @@ //