From 4a3cab725c5cff4d69783ff77d80b46890f1df95 Mon Sep 17 00:00:00 2001 From: Arvind Kumar Date: Sat, 10 Oct 2026 14:45:12 +0530 Subject: [PATCH] fix: Enforce server-side account roles and patient access --- .github/workflows/audit-checks.yml | 14 ++++ .gitignore | 6 ++ AUDIT_FIXES.md | 17 ++++ README.md | Bin 26 -> 441 bytes backend/.env | 9 --- backend/.env.example | 8 ++ .../__pycache__/ai_service.cpython-314.pyc | Bin 1346 -> 0 bytes backend/__pycache__/main.cpython-314.pyc | Bin 7835 -> 0 bytes backend/auth.py | 76 ++++++++++++++++++ backend/main.py | 58 ++++++++----- backend/requirements.txt | 3 + frontend/app/page.tsx | 15 ++-- frontend/components/AuthOverlay.tsx | 25 +++--- frontend/lib/api.ts | 17 +++- pytest.ini | 3 + requirements-test.txt | 9 +++ tests/conftest.py | 3 + tests/test_auth.py | 64 +++++++++++++++ 18 files changed, 275 insertions(+), 52 deletions(-) create mode 100644 .github/workflows/audit-checks.yml create mode 100644 .gitignore create mode 100644 AUDIT_FIXES.md delete mode 100644 backend/.env create mode 100644 backend/.env.example delete mode 100644 backend/__pycache__/ai_service.cpython-314.pyc delete mode 100644 backend/__pycache__/main.cpython-314.pyc create mode 100644 backend/auth.py create mode 100644 pytest.ini create mode 100644 requirements-test.txt create mode 100644 tests/conftest.py create mode 100644 tests/test_auth.py 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 7274ae93edca9d12b0ed7ea64b5fc7d903f746fd..138fbc111301fcb70764d54f47fc20912f90d8fb 100644 GIT binary patch literal 441 zcmY+A-Acni5QXpa6a(HUw8=9Rwa^=p{(vAN)7^;~yV(gl)6~4ZlR^=%_GiwXbH2TU zM=aDPxm49|%GQx_SVlC2PIO?y1Q#i%Sph>46PpHt3tIeEp@<=sA&nu2A)ld~ftP`c0RUkX1&aUx 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 6328450124754f6d1829ccc348f94f1548e4dcff..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1346 zcmZuxOK%)S5boZY*@xFJ{EWtN+#5?aE59(Y{K9}7ViFT%Z-!tg(mJd0Y}=lAc6;b< zJ6WHM#3AAW;(`$%dXvwR^s>F`MYQT3o3EDm6pcT{zCwbclaSzH?O!Sh0 z)4xs`^K}i_#r~^vB97shD|jq2iXF>|Iy?aZL8~}D1QN=izqalM7Fc8y=~O3$MANf7dZ`~@xIYt z<39G$J4P?^aXPs>+(3X99!Tzbk`!p(_uPO;S8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oNrBCpW39idbhg@%mDaqCirD(m_ar#KE=?-a5VPt_VD(x syknri4DK+4xa>m>{g2uNcX!A8?ATHC;Zf_joBr^WbKFkfwVMI{KhSsVGynhq 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 @@ //
// {/* 1. Sidebar Component (Self-contained data fetching) */} -// setSelectedPatient(p)} /> +// setSelectedPatient(p)} /> // {/* 2. Main Workspace */} //
@@ -839,6 +839,7 @@ import { Calendar, Clock, ClipboardList, User, FileText } from "lucide-react"; import AuthOverlay from '@/components/AuthOverlay'; +import { generateAudit } from '@/lib/api'; import { Button } from "@/components/ui/button"; import { Textarea } from "@/components/ui/textarea"; import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"; @@ -901,7 +902,7 @@ export default function Dashboard() { }; const handleToggleTask = async (taskId: string) => { - if (role === 'doctor') return alert("Only Nurses can update status."); + if (role !== 'nurse') return alert("Only Nurses can update status."); try { await toggleTaskStatus(taskId); fetchLatestTasks(); @@ -955,12 +956,8 @@ const generateAgenticReport = async () => { if (!selectedPatient) return; setIsGeneratingReport(true); try { - const res = await fetch(`https://careflow-backend-4l8t.onrender.com/api/agent-audit/${selectedPatient.id}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ note: "Generate report" }) - }); - const data = await res.json(); + if (!note.trim()) throw new Error("Enter a source note before generating an audit"); + const data = await generateAudit(selectedPatient.id, note); let reportText = "CAREFLOW CLINICAL AUDIT\n"; reportText += "=======================\n\n"; @@ -1012,7 +1009,7 @@ return ( {/* Yahan Condition dalo: Agar role 'patient' nahi hai tabhi ye dikhao */} {role !== 'patient' && ( //
- setSelectedPatient(p)} /> + setSelectedPatient(p)} /> )} diff --git a/frontend/components/AuthOverlay.tsx b/frontend/components/AuthOverlay.tsx index 90ec244..721ec9a 100644 --- a/frontend/components/AuthOverlay.tsx +++ b/frontend/components/AuthOverlay.tsx @@ -1,21 +1,19 @@ 'use client' import { useState } from 'react' +import { loginAccount } from '@/lib/api' export default function AuthOverlay({ onLogin }: { onLogin: (role: string, id?: string) => void }) { const [view, setView] = useState<'select' | 'staff' | 'patient'>('select'); const [id, setId] = useState(''); const [pass, setPass] = useState(''); - const handleStaffLogin = () => { - // Simple logic: Doc ke liye 'doc123', Nurse ke liye 'nurse123' - if (id === 'doctor' && pass === 'doc123') onLogin('doctor'); - else if (id === 'nurse' && pass === 'nurse123') onLogin('nurse'); - else alert("Invalid Staff Credentials"); - }; - - const handlePatientLogin = () => { - if (id.length > 3) onLogin('patient', id); // Patient apni ID se login karega - else alert("Enter valid Patient ID"); + const handleLogin = async () => { + try { + const account = await loginAccount(id, pass); + onLogin(account.role, account.patient_id); + } catch { + alert("Login failed. Check your configured account credentials."); + } }; return ( @@ -34,15 +32,16 @@ export default function AuthOverlay({ onLogin }: { onLogin: (role: string, id?:
setId(e.target.value)} className="w-full p-4 border rounded-2xl text-sm" /> setPass(e.target.value)} className="w-full p-4 border rounded-2xl text-sm" /> - +
)} {view === 'patient' && (
- setId(e.target.value)} className="w-full p-4 border rounded-2xl text-sm" /> - + setId(e.target.value)} className="w-full p-4 border rounded-2xl text-sm" /> + setPass(e.target.value)} className="w-full p-4 border rounded-2xl text-sm" /> +
)} diff --git a/frontend/lib/api.ts b/frontend/lib/api.ts index b89d3ed..5e3fa9f 100644 --- a/frontend/lib/api.ts +++ b/frontend/lib/api.ts @@ -15,12 +15,27 @@ import axios from 'axios'; // 1. Axios Instance Setup // Dhyaan rakhna: 'baseURL' likhna zaroori hai, varna 404 error aayega. const api = axios.create({ - baseURL: 'https://careflow-backend-4l8t.onrender.com/api', // Tumhara FastAPI backend URL + baseURL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api', headers: { 'Content-Type': 'application/json', }, }); +let accessToken: string | null = null; +api.interceptors.request.use((config) => { + if (accessToken) config.headers.Authorization = `Bearer ${accessToken}`; + return config; +}); +export const loginAccount = async (username: string, password: string) => { + const response = await api.post('/auth/login', { username, password }); + accessToken = response.data.access_token; + return response.data as { role: 'doctor' | 'nurse' | 'patient'; patient_id?: string }; +}; +export const generateAudit = async (patientId: string, note: string) => { + const response = await api.post(`/agent-audit/${patientId}`, { note }); + return response.data; +}; + // 2. API Functions (Zero to End) // A. Sare Patients ki list mangne ke liye (Sidebar ke liye) diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..ab88e56 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +pythonpath = backend +testpaths = tests diff --git a/requirements-test.txt b/requirements-test.txt new file mode 100644 index 0000000..71b4bc7 --- /dev/null +++ b/requirements-test.txt @@ -0,0 +1,9 @@ +pytest>=8,<9 +fastapi>=0.115,<1 +httpx>=0.27,<1 +PyJWT>=2.9,<3 +bcrypt>=4,<6 +motor>=3.6,<4 +groq>=0.16,<2 +faker>=30 +python-dotenv>=1,<2 diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..3514f46 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,3 @@ +import os +os.environ['GROQ_API_KEY'] = '' +os.environ['SEED_SYNTHETIC_PATIENTS'] = 'false' diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..89faea7 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,64 @@ +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import bcrypt +import pytest +from fastapi.testclient import TestClient +import main + + +@pytest.fixture +def client(monkeypatch): + monkeypatch.setenv('CAREFLOW_JWT_SECRET', 'fixture-secret-with-at-least-32-characters') + password_hash = bcrypt.hashpw(b'fixture-password', bcrypt.gensalt(rounds=4)).decode() + rows = [{'username': name, 'password_hash': password_hash, 'role': role, 'patient_id': patient} for name, role, patient in [('doctor', 'doctor', None), ('nurse', 'nurse', None), ('patient', 'patient', 'bound-patient')]] + monkeypatch.setenv('CAREFLOW_USERS_JSON', json.dumps(rows)) + return TestClient(main.app) + + +def headers(client, name): + response = client.post('/api/auth/login', json={'username': name, 'password': 'fixture-password'}) + assert response.status_code == 200 + return {'Authorization': 'Bearer ' + response.json()['access_token']} + + +@pytest.mark.parametrize('path', ['/api/patients', '/api/tasks/any']) +def test_read_requires_server_authentication(client, path): + assert client.get(path).status_code in (401, 403) + + +def test_bad_password_cannot_select_doctor_role(client): + assert client.post('/api/auth/login', json={'username': 'doctor', 'password': 'doc123'}).status_code == 401 + + +def test_patient_cannot_read_other_patients_tasks(client): + assert client.get('/api/tasks/other-patient', headers=headers(client, 'patient')).status_code == 403 + + +def test_patient_cannot_create_patients_or_analyze(client): + auth = headers(client, 'patient') + assert client.post('/api/patients', headers=auth, json={'name': 'fixture'}).status_code == 403 + assert client.post('/api/analyze/bound-patient', headers=auth, json={'note': 'fixture'}).status_code == 403 + + +def test_doctor_cannot_toggle_tasks(client): + assert client.patch('/api/tasks/invalid', headers=headers(client, 'doctor')).status_code == 403 + + +def test_patient_can_read_only_bound_tasks(client, monkeypatch): + class Cursor: + def sort(self, *args): return self + def __aiter__(self): return self + async def __anext__(self): raise StopAsyncIteration + seen = [] + collection = SimpleNamespace(find=lambda query: (seen.append(query), Cursor())[1]) + monkeypatch.setattr(main, 'tasks_collection', collection) + response = client.get('/api/tasks/bound-patient', headers=headers(client, 'patient')) + assert response.status_code == 200 + assert seen == [{'patient_id': 'bound-patient'}] + + +def test_login_denies_missing_auth_configuration(client, monkeypatch): + monkeypatch.setenv('CAREFLOW_JWT_SECRET', '') + assert client.post('/api/auth/login', json={'username': 'doctor', 'password': 'fixture-password'}).status_code == 503