Part IV — Expert Production Engineering · Chapter 20 · Lesson 6 of 7 · 5 min read
Lesson 6: Secure Serialization, Signing, Encryption, and Key Handling
Lesson level: Expert
Purpose: Protect model artifacts and monitoring data against tampering, unauthorized loading, and disclosure, using safe serialization, digital signatures, encryption, and disciplined key management.
Learning objectives
By the end of this lesson you will be able to:
- explain why some serialization formats are dangerous to load
- distinguish integrity, authenticity, and confidentiality
- sign and verify a bundle manifest with an asymmetric key
- encrypt artifacts and audit data at rest with authenticated encryption
- design key storage, access, rotation, and revocation
- build a load path that refuses anything unverified
6.1 The serialization risk
Some general-purpose object-serialization formats can reconstruct arbitrary objects and run code while loading. A model file in such a format is effectively a program: anyone who can replace it can run code on your serving hosts. Defences, in order:
- Prefer data-only formats for model content — numeric arrays, JSON metadata, and documented layouts provided by the ML layer — over arbitrary object pickling.
- Verify the signature and every hash before deserializing anything.
- Load only from controlled, write-restricted locations.
- Run serving processes with least privilege (Chapter 14 and Chapter 22), so that a compromised load does as little damage as possible.
6.2 Three properties
| Property | Question | Mechanism |
|---|---|---|
| Integrity | Has the content changed? | Content hashes (Lesson 1) |
| Authenticity | Did a trusted party produce it? | Digital signatures |
| Confidentiality | Can unauthorized parties read it? | Encryption |
Most model bundles need integrity and authenticity. Bundles and monitoring stores that contain personal data, proprietary features, or commercially sensitive weights also need confidentiality.
6.3 Signing the manifest
Sign the manifest, not each file: the manifest already holds every file's hash, so one signature covers the whole bundle. Use an asymmetric signature scheme such as Ed25519. The release pipeline holds the private key and signs; serving hosts hold only the public keys of trusted signers and verify. The same idea underpins the signed packages and trusted keys of Chapter 11.
Illustrative listing using the cryptography library, which PeaLang declares as a runtime dependency.
from cryptography.hazmat.primitives.asymmetric.ed25519 import (
Ed25519PrivateKey, Ed25519PublicKey)
from cryptography.exceptions import InvalidSignature
def sign_manifest(manifest_bytes: bytes, private_key: Ed25519PrivateKey) -> bytes:
return private_key.sign(manifest_bytes)
def verify_manifest(manifest_bytes: bytes, signature: bytes,
trusted: list[Ed25519PublicKey]) -> bool:
for key in trusted:
try:
key.verify(signature, manifest_bytes)
return True
except InvalidSignature:
continue
return False
Sign a canonical form of the manifest — fixed key order and encoding — so that harmless reformatting does not break verification. Record the signer key identifier in the registry with the version.
6.4 Encryption at rest
Use authenticated encryption, such as AES-GCM, which provides confidentiality and detects tampering in one step. Each encryption needs a fresh, never-reused nonce; reusing a nonce with the same key breaks the scheme. A common pattern is envelope encryption: encrypt each artifact with its own random data key, then encrypt (wrap) the data key with a master key held in a key-management service. Rotating the master key then requires re-wrapping only the small data keys, not re-encrypting every artifact.
Illustrative listing.
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
def encrypt_artifact(plaintext: bytes, data_key: bytes, aad: bytes) -> bytes:
nonce = os.urandom(12) # never reuse with the same key
return nonce + AESGCM(data_key).encrypt(nonce, plaintext, aad)
def decrypt_artifact(blob: bytes, data_key: bytes, aad: bytes) -> bytes:
nonce, ciphertext = blob[:12], blob[12:]
return AESGCM(data_key).decrypt(nonce, ciphertext, aad)
The associated data (aad) — for example the model name and version — is authenticated but not encrypted, so a ciphertext copied into the wrong bundle fails to decrypt. Do not invent your own cryptographic constructions; use well-reviewed library primitives exactly as documented.
6.5 Key handling
- Storage: private signing keys and master encryption keys live in a key-management service or hardware security module, never in source code, bundles, container images, or environment files committed to version control.
- Access: only the release pipeline may sign; only serving identities may unwrap data keys for the models they serve. Grant through the secret providers of Chapter 17 with least privilege.
- Rotation: rotate keys on a schedule and immediately after suspected exposure. Keep old public keys trusted for verifying older bundles until those bundles are retired.
- Revocation: maintain a revocation list; a revoked signer's bundles fail verification and must be re-signed or retired.
- Audit: log every signing and key-unwrap operation with identity and time.
6.6 The secure load path
- Fetch the bundle from the controlled location named in the registry.
- Verify the manifest signature against trusted, non-revoked public keys.
- Recompute every file hash and compare with the manifest; reject missing or extra files.
- Confirm the registry state permits serving this version on this route.
- Unwrap the data key and decrypt confidential files, if any.
- Only now deserialize the pipeline, using the data-only format.
- Run golden-prediction smoke tests (Chapter 19, Lesson 6) before taking traffic.
Any failure stops the load, raises a high-severity alert (Lesson 4), and keeps the previous version serving.
Common mistakes
- Deserializing before verifying: the attack has already run by the time you check.
- Hashes without signatures: an attacker replaces both.
- Keys in images or repositories: use a key-management service.
- Nonce reuse: generate a fresh random nonce for every encryption.
- No rotation or revocation plan: a leaked key compromises every future bundle.
- Home-made cryptography: use reviewed library primitives.
Guided practice
- Generate a signing key pair, sign a manifest, and verify it; then change one character and confirm verification fails.
- Encrypt a schema file with associated data, then try to decrypt it with different associated data.
- Write a key-rotation runbook for the signing key.
Hands-on lab: A signed, encrypted bundle
- Canonicalize and sign the Lesson 1 manifest; store the signature and signer key ID.
- Encrypt the evaluation file and model card with envelope encryption using a local stand-in for a key service.
- Implement the secure load path of Section 6.6 and test each failure: bad signature, revoked key, modified file, wrong registry state, wrong associated data.
- Confirm every failure leaves the previous version serving and writes an alert.
Review questions
- Why can loading a serialized model execute code?
- How do integrity, authenticity, and confidentiality differ?
- Why sign the manifest rather than each file?
- What does authenticated encryption add to ordinary encryption?
- What is envelope encryption, and why does it simplify rotation?
- List the steps of a secure load path in order.
Applied challenge
Your signing key may have been exposed in a build log. Write the incident plan: containment, revocation, re-signing of affected bundles, verification of currently serving versions, and how you will show auditors which predictions, if any, could have come from tampered artifacts.
Lesson summary
Treat model files as potentially executable and never deserialize before verification. Sign the canonical manifest with an asymmetric key, encrypt sensitive artifacts with authenticated, envelope encryption, and keep keys in managed storage with least-privilege access, rotation, revocation, and audit. A strict, ordered load path stops anything unverified from ever serving.
Lesson status: Ready for review.