Initial commit: DMH Patient Registration Flask app

This commit is contained in:
Ayush
2026-11-27 17:07:03 +05:30
commit 6c03977aab
34 changed files with 5445 additions and 0 deletions
+234
View File
@@ -0,0 +1,234 @@
import io
from datetime import date, timedelta
from unittest.mock import patch
import pytest
from PIL import Image
from app import app
def _valid_png_bytes() -> bytes:
buf = io.BytesIO()
Image.new("RGB", (10, 10), color=(0, 128, 255)).save(buf, format="PNG")
return buf.getvalue()
@pytest.fixture
def client(tmp_path):
app.config["TESTING"] = True
app.config["UPLOAD_FOLDER"] = str(tmp_path / "uploads")
with app.test_client() as c:
yield c
def _valid_payload():
"""Return a complete, valid fake registration payload."""
return {
"title": "1",
"lname": "DOE",
"fname": "JOHN",
"mname": "A",
"pan_no": "ABCDE1234F",
"aadhar_no": "123456789012",
"gender": "1",
"father": "RICHARD DOE",
"dob": "15/05/1990",
"age": "36",
"ageUnit": "0",
"approx_dob": "0",
"marital_status": "",
"dom": "",
"bmname": "",
"patient_income": "25000",
"address1": "123 FAKE STREET",
"address2": "NEAR PARK",
"post_office": "PUNE",
"country": "38",
"state": "12",
"city": "289",
"pincode": "411004",
"phone": "0201234567",
"office_phone": "0207654321",
"cell_phone": "9876543210",
"email": "john.doe@example.com",
"p_address1": "123 FAKE STREET",
"p_address2": "NEAR PARK",
"p_post_office": "PUNE",
"p_country": "38",
"p_state": "12",
"p_city": "289",
"p_pincode": "411004",
"p_phone": "0201234567",
"emg_person": "DOE",
"emg_person1": "JANE",
"emg_person2": "",
"relation": "2",
"emg_no": "9876500000",
"re_persone": "JANE DOE",
"re_relation": "2",
"doc_type": "1570",
"txtcaptcha": "AbCd",
"SaveDB": "Save",
"honeypot": "",
"ptnPhoto": (io.BytesIO(_valid_png_bytes()), "photo.png"),
"id_file": (io.BytesIO(b"%PDF-1.4\n1 0 obj\n<<>>\nendobj\ntrailer\n<<>>\n%%EOF"), "aadhar.pdf"),
}
def test_index_routes(client):
for path in ("/", "/index.php"):
resp = client.get(path)
assert resp.status_code == 200
assert b"Patient Registration Form" in resp.data
def test_state_and_city_endpoints_india(client):
r1 = client.post("/getState.php?countryId=38&stateId=12")
assert r1.status_code == 200
assert b'name="state"' in r1.data
assert b"Maharashtra" in r1.data
r2 = client.post("/getCity.php?countryId=38&stateId=12&cityId=289")
assert r2.status_code == 200
assert b'name="city"' in r2.data
assert b"Pune" in r2.data
r3 = client.post("/p_getState.php?countryId=38&stateId=12")
assert r3.status_code == 200
assert b'name="p_state"' in r3.data
r4 = client.post("/p_getCity.php?countryId=38&stateId=12&cityId=289")
assert r4.status_code == 200
assert b'name="p_city"' in r4.data
def test_state_and_city_endpoints_non_india(client):
r1 = client.post("/getState.php?countryId=81&other_state=California")
assert r1.status_code == 200
assert b'name="other_state"' in r1.data
assert b'value="California"' in r1.data
r2 = client.post("/getCity.php?countryId=81&other_city=San%20Jose")
assert r2.status_code == 200
assert b'name="other_city"' in r2.data
assert b'value="San Jose"' in r2.data
r3 = client.post("/p_getState.php?countryId=81&other_state=Texas")
assert r3.status_code == 200
assert b'name="other_p_state"' in r3.data
r4 = client.post("/p_getCity.php?countryId=81&other_city=Austin")
assert r4.status_code == 200
assert b'name="other_p_city"' in r4.data
def test_get_dob_endpoint(client):
r_days = client.post("/getDOB.php?age=10&ageUnit=days")
assert r_days.status_code == 200
expected = (date.today() - timedelta(days=10)).strftime("%d/%m/%Y").encode()
assert r_days.data == expected
r_weeks = client.post("/getDOB.php?age=2&ageUnit=weeks")
assert r_weeks.status_code == 200
expected_w = (date.today() - timedelta(weeks=2)).strftime("%d/%m/%Y").encode()
assert r_weeks.data == expected_w
def test_valid_submission_saves_and_shows_reference_id(client):
with patch("db.save_registration", return_value="250043") as mock_save:
resp = client.post(
"/uploadProxy.php",
data=_valid_payload(),
content_type="multipart/form-data",
)
assert resp.status_code == 200
assert b"Registration Form Saved Successfully.. Your Reference Form ID : 250043" in resp.data
mock_save.assert_called_once()
def test_honeypot_rejected(client):
data = _valid_payload()
data["honeypot"] = "bot-filled"
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
assert b"Invalid submission detected." in resp.data
@pytest.mark.parametrize(
"field,bad_val,expected_msg",
[
("title", "", b"Please Select Title"),
("lname", "", b"Please Enter Last Name"),
("fname", "", b"Please Enter First Name"),
("pan_no", "INVALID123", b"Enter Valid Pan Card Number"),
("aadhar_no", "12345abc", b"Please Enter Numbers In Aadhar Number"),
("aadhar_no", "12345678901", b"Please Enter 12 Digit Aadhar Number"),
("patient_income", "abc", b"Please Enter Numbers In Monthly Income"),
("address1", "", b"Please Enter House Name/Appt.No Details"),
("country", "", b"Please Select Country"),
("state", "", b"Please Select State"),
("city", "", b"Please Select City"),
("pincode", "41100A", b"Please Enter Numbers In Pin Number"),
("cell_phone", "987654321a", b"Please Enter Numbers In Cell Number"),
("cell_phone", "98765", b"Please Enter 10 Digit Cell Number"),
("email", "bad-email", b"You have entered an invalid email address!"),
("email", "user@domain.info", b"You have entered an invalid email address!"),
("emg_person", "", b"Please Enter Emergency Contact Person"),
("emg_person1", "", b"Please Enter Emergency Contact Person"),
("relation", "", b"Please Select Relation With Patient"),
("emg_no", "", b"Please Enter Emergency Contact Number"),
("re_persone", "", b"Please Enter Name Of Representative"),
("re_relation", "", b"Please Select Representative Relation To Patient"),
("txtcaptcha", "", b"Enter captcha text."),
("txtcaptcha", "12", b"Invalid Captcha Text!"),
],
)
def test_field_validations(client, field, bad_val, expected_msg):
data = _valid_payload()
data[field] = bad_val
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
assert expected_msg in resp.data
def test_female_marital_status_rules(client):
data = _valid_payload()
data["title"] = "3"
data["gender"] = "2"
data["marital_status"] = ""
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
assert b"Please Choose Marital Status." in resp.data
data2 = _valid_payload()
data2["title"] = "3"
data2["gender"] = "2"
data2["marital_status"] = "Married"
data2["dom"] = ""
data2["bmname"] = ""
resp2 = client.post("/uploadProxy.php", data=data2, content_type="multipart/form-data")
assert resp2.status_code == 400
assert b"Please Enter Date Of Marriage." in resp2.data
assert b"Please Enter Before Marriage Name." in resp2.data
def test_non_india_free_text_state_city_accepted(client):
data = _valid_payload()
data["country"] = "81"
data.pop("state")
data.pop("city")
data["other_state"] = "California"
data["other_city"] = "San Jose"
with patch("db.save_registration", return_value="250099"):
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 200
assert b"250099" in resp.data
def test_invalid_id_file_type_rejected(client):
data = _valid_payload()
data["id_file"] = (io.BytesIO(b"bad"), "malware.exe")
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
assert b"Invalid file type" in resp.data
+256
View File
@@ -0,0 +1,256 @@
import io
import logging
from contextlib import contextmanager
from unittest.mock import MagicMock, patch
import pytest
from PIL import Image
from app import app
from crypto_utils import (
PiiRedactingFilter,
compute_match_token,
decrypt_pii,
encrypt_pii,
mask_aadhaar,
mask_pan,
validate_production_secrets,
)
from his_adapter import BaseHISAdapter, HISCreateResult, HISReconcileResult, HISSearchResult, get_his_adapter
from upload_service import UploadValidationError, detect_mime_from_magic_bytes, process_staged_upload
from validators import validate_core_fields
from worker import process_outbox_event
def _make_png_bytes(width=10, height=10, mode="RGB") -> bytes:
buf = io.BytesIO()
img = Image.new("RGB", (width, height), color=(255, 0, 0))
if mode == "P":
img = img.convert("P")
img.save(buf, format="PNG")
return buf.getvalue()
def _make_animated_gif_bytes() -> bytes:
buf = io.BytesIO()
f1 = Image.new("RGB", (10, 10), color=(255, 0, 0))
f2 = Image.new("RGB", (10, 10), color=(0, 255, 0))
f1.save(buf, format="GIF", save_all=True, append_images=[f2], duration=100, loop=0)
return buf.getvalue()
@pytest.fixture
def client(tmp_path):
app.config["TESTING"] = True
app.config["UPLOAD_FOLDER"] = str(tmp_path / "uploads")
with app.test_client() as c:
yield c
# ============================================================
# 1. Secrets Guard, HIS_MODE Guard, Encryption & Masking
# ============================================================
def test_production_guards(monkeypatch):
monkeypatch.setenv("FLASK_ENV", "production")
monkeypatch.setenv("HIS_MODE", "mock")
with pytest.raises(RuntimeError):
get_his_adapter()
monkeypatch.setenv("FLASK_SECRET_KEY", "dev-secret-change-me")
with pytest.raises(RuntimeError):
validate_production_secrets()
def test_pii_encryption_masking_and_log_redaction():
raw_aadhar = "123456789012"
raw_pan = "ABCDE1234F"
enc_a = encrypt_pii(raw_aadhar)
enc_p = encrypt_pii(raw_pan)
assert enc_a != raw_aadhar.encode()
assert decrypt_pii(enc_a) == raw_aadhar
assert decrypt_pii(enc_p) == raw_pan
assert mask_aadhaar(raw_aadhar) == "XXXX-XXXX-9012"
assert mask_pan(raw_pan) == "XXXXXX234F"
assert compute_match_token("PAN", "abcde1234f") == compute_match_token("PAN", "ABCDE1234F")
rec = logging.LogRecord("test", logging.INFO, "", 0, "Aadhaar 123456789012 PAN ABCDE1234F", (), None)
assert PiiRedactingFilter().filter(rec)
assert "123456789012" not in rec.msg
assert "ABCDE1234F" not in rec.msg
# ============================================================
# 2. Image Service: Palette PNG, Animated GIF, Magic Bytes & Legacy Upload Guard
# ============================================================
def test_palette_png_and_animated_gif_preserved(tmp_path):
pal_png = _make_png_bytes(mode="P")
meta = process_staged_upload(raw_bytes=pal_png, category="PHOTO", upload_root=str(tmp_path), session_id="s1")
out_img = Image.open(tmp_path / meta["storage_key"])
assert out_img.getpixel((0, 0))[:3] == (255, 0, 0) # Not turned black
gif_bytes = _make_animated_gif_bytes()
meta_gif = process_staged_upload(raw_bytes=gif_bytes, category="PHOTO", upload_root=str(tmp_path), session_id="s1")
out_gif = Image.open(tmp_path / meta_gif["storage_key"])
assert getattr(out_gif, "n_frames", 1) == 2
def test_magic_bytes_and_upload_security(tmp_path):
png = _make_png_bytes()
assert detect_mime_from_magic_bytes(png) == "image/png"
assert detect_mime_from_magic_bytes(b"%PDF-1.4\n...") == "application/pdf"
assert detect_mime_from_magic_bytes(b"MZ\x90\x00exe-spoof") is None
with pytest.raises(UploadValidationError) as exc:
process_staged_upload(raw_bytes=b"MZ\x90\x00not-a-jpg", category="KYC", upload_root=str(tmp_path), session_id="s1")
assert exc.value.status_code == 422
with pytest.raises(UploadValidationError) as exc_size:
process_staged_upload(raw_bytes=b"\xff\xd8\xff" + b"0" * (2 * 1024 * 1024 + 10), category="PHOTO", upload_root=str(tmp_path), session_id="s1")
assert exc_size.value.status_code == 413
eicar_pdf = b"%PDF-1.4\nX5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"
with pytest.raises(UploadValidationError):
process_staged_upload(raw_bytes=eicar_pdf, category="KYC", upload_root=str(tmp_path), session_id="s1")
def test_legacy_upload_proxy_rejects_spoofed_exe_pdf(client):
from tests.test_app import _valid_payload
data = _valid_payload()
data["id_file"] = (io.BytesIO(b"MZ\x90\x00spoofed-exe"), "fake.pdf")
resp = client.post("/uploadProxy.php", data=data, content_type="multipart/form-data")
assert resp.status_code == 400
assert b"magic-byte check failed" in resp.data
# ============================================================
# 3. Max-Length, Date Quality, /getDOB.php Bounds & Address Copy
# ============================================================
def test_max_length_and_date_quality_checks():
base = {
"title": "1", "lname": "D" * 101, "fname": "JOHN", "gender": "1",
"dob": "15/05/1800", "age": "36", "ageUnit": "0",
"address1": "123 LOCAL ST", "country": "38", "state": "12", "city": "289",
"pincode": "411004", "email": "john@example.com", "copy": "true",
"emg_person": "DOE", "emg_person1": "JANE", "relation": "2", "emg_no": "9876500000",
"re_persone": "JANE DOE", "re_relation": "2", "doc_type": "1570",
}
_, errors = validate_core_fields(base, skip_captcha=True)
assert any("100 characters" in e for e in errors)
assert any("120 years" in e for e in errors)
def test_get_dob_huge_age_returns_400_not_500(client):
resp = client.post("/getDOB.php?age=3000&ageUnit=years")
assert resp.status_code == 400
def test_server_derives_permanent_address_when_copy_true():
payload = {
"title": "1", "lname": "DOE", "fname": "JOHN", "gender": "1",
"dob": "15/05/1990", "age": "36", "ageUnit": "0",
"address1": "123 LOCAL ST", "country": "38", "state": "12", "city": "289",
"pincode": "411004", "email": "john@example.com", "copy": "true",
"p_address1": "999 WRONG ST", "p_country": "81", "p_pincode": "999999",
"emg_person": "DOE", "emg_person1": "JANE", "relation": "2", "emg_no": "9876500000",
"re_persone": "JANE DOE", "re_relation": "2", "doc_type": "1570",
}
cleaned, errors = validate_core_fields(payload, skip_captcha=True)
assert errors == []
assert cleaned["p_address1"] == "123 LOCAL ST"
assert cleaned["p_country"] == 38
assert cleaned["p_pincode"] == "411004"
# ============================================================
# 4. v1 API Idempotency, Status Ownership, DB-Backed Admin RBAC & Audit Filter
# ============================================================
@contextmanager
def _fake_db_conn(cur):
conn = MagicMock()
conn.cursor.return_value.__enter__.return_value = cur
yield conn
def test_v1_registration_idempotency_and_conflict(client):
cur = MagicMock()
cached_resp = {"success": True, "data": {"registrationReference": "250044", "status": "SUBMITTED", "hospitalPatientId": None}}
with patch("db.get_connection", return_value=_fake_db_conn(cur).__enter__()), \
patch("db.check_or_reserve_idempotency", return_value={"state": "COMPLETED", "http_status": 201, "response": cached_resp}):
r = client.post(
"/api/v1/registrations",
json={"sessionId": "s1", "captcha": {"challengeId": "c1", "answer": "wrong"}},
headers={"Idempotency-Key": "k1"},
)
assert r.status_code == 201
assert r.get_json()["data"]["registrationReference"] == "250044"
with patch("db.get_connection", return_value=_fake_db_conn(cur).__enter__()), \
patch("db.check_or_reserve_idempotency", return_value={"state": "CONFLICT"}):
r2 = client.post(
"/api/v1/registrations",
json={"sessionId": "s1", "fname": "OTHER"},
headers={"Idempotency-Key": "k1"},
)
assert r2.status_code == 409
def test_status_ownership_and_admin_db_rbac(client):
assert client.get("/api/v1/registrations/250044/status").status_code == 401
with patch("db.get_registration_status_by_ref", return_value={"reference_form_id": "250044", "session_id": "owner-sess", "status": "SUBMITTED", "hospital_patient_id": None, "email_status": "PENDING"}):
assert client.get("/api/v1/registrations/250044/status", headers={"X-Session-Id": "other-sess"}).status_code == 403
assert client.get("/api/v1/registrations/250044/status", headers={"X-Session-Id": "owner-sess"}).status_code == 200
# Admin RBAC uses DB lookup, not client X-Admin-Role header
with patch("db.get_admin_user", return_value={"id": 1, "sso_subject": "staff1", "role": "REG_STAFF"}):
assert client.post(
"/api/v1/admin/registrations/1/review",
json={"decision": "APPROVE_NEW", "reason": "ok"},
headers={"X-Admin-Token": "dev-admin-sso-token", "X-Admin-Subject": "staff1", "X-Admin-Role": "SUPERVISOR"},
).status_code == 403
with patch("db.get_admin_user", return_value={"id": 2, "sso_subject": "sup1", "role": "SUPERVISOR"}):
assert client.get(
"/api/v1/admin/audit-logs?registrationId=abc",
headers={"X-Admin-Token": "dev-admin-sso-token", "X-Admin-Subject": "sup1"},
).status_code == 400
# ============================================================
# 5. Outbox Worker: Timeout Reconciliation & Error Recovery
# ============================================================
def test_worker_timeout_reconciliation():
class TimeoutThenFoundHIS(BaseHISAdapter):
def search_patient(self, **kwargs):
return HISSearchResult(outcome="NONE")
def create_patient(self, **kwargs):
return HISCreateResult(outcome="TIMEOUT", reason="Socket timeout")
def reconcile_registration(self, **kwargs):
return HISReconcileResult(outcome="FOUND", uhid="UHID-RECONCILED-1")
cur = MagicMock()
cur.fetchone.return_value = {
"id": 1, "reference_form_id": "250044", "status": "PENDING_HIS_SYNC",
"fname": "JOHN", "lname": "DOE", "dob": "1990-05-15", "cell_phone": "9876543210",
"email": "john@example.com",
}
with patch("db.transition_registration_status") as mock_trans:
process_outbox_event(
cur,
{"id": "ev-1", "registration_id": 1, "event_type": "HIS_CREATE", "correlation_id": "corr-1"},
TimeoutThenFoundHIS(),
)
mock_trans.assert_called_once()
args, kwargs = mock_trans.call_args
assert args[2] == "REGISTERED"
assert kwargs["hospital_patient_id"] == "UHID-RECONCILED-1"