257 lines
11 KiB
Python
257 lines
11 KiB
Python
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"
|