Secure model artifacts and avoid untrusted deserialization
In this article (5 sections)
Common Python model formats built on pickle can execute code while loading. Treat an artifact as executable supply-chain input. Only load from controlled sources after verifying identity, integrity and expected environment.
Verify without loading the tampered file
The deployment lab saves a trusted local joblib artifact, calculates SHA-256, and compares a tampered byte sequence with the expected hash.
from deployment_cases import artifact_security_case
result = artifact_security_case()
assert result["hash_verified_before_load"] is True
assert result["tampered_hash_accepted"] is False
assert result["untrusted_deserialization_performed"] is False
print(result["format"], result["trusted_local_only"])The altered bytes fail integrity verification and are never deserialized. A matching hash alone does not establish source trust: an attacker can supply both a malicious file and its hash.
Establish provenance
Pull artifacts from an allowlisted registry or controlled storage. Authenticate the publisher, verify a signed manifest where supported, restrict write access and log promotion. Bind artifact hash to code, data, environment and review decision.
Run serving with least privilege, read-only storage and constrained network access. Scan dependencies and container layers. Keep secrets outside the artifact.
Choose formats deliberately
Review scikit-learn’s persistence guidance. Safer interchange or serving formats may reduce arbitrary-code risk but can restrict supported operators and still require validation. Test prediction equivalence after conversion.
Never load a user-uploaded .pkl or .joblib to “inspect” it in a privileged process. The Data Science course treats model files as governed release artifacts.
Exercise
Create an allowlisted artifact manifest with hash, signature identity and model version. Test missing, mismatched and revoked artifacts before any deserialization call.
Continue learning
This article is part of the Model deployment and MLOps sequence. Use the neighbouring tasks when you need the prerequisite or the next application.
- Review the prerequisite or neighbouring task in Explain model latency percentiles to a product owner.
- Continue with Build a deployment checklist for a student ML project.
Reference: scikit-learn model persistence security guidance.
Pankit Kumar has 10 years in Data Science & AI, building and shipping production systems in regulated pharma and clinical environments. He is a freelance trainer at Boston Institute of Analytics, AnalytixLabs and Scaler, and has taught this material to thousands of working professionals.
This article is part of our Data Science programme — 6 months. From data foundations to machine learning, deep learning and deployment.
Explore Data Science