"""Seal personal cells with AES-256-GCM and a named environment key slot.""" from __future__ import annotations import base64 import binascii import json import os from cryptography.exceptions import InvalidTag from cryptography.hazmat.primitives.ciphers.aead import AESGCM KEY_SLOT = "AMAZON_PII_KEY" PREFIX = "amazon-pii:v1:" NONCE_BYTES = 12 class PiiKeyUnavailable(ValueError): """The named environment slot cannot supply an AES-256 key.""" class PiiCiphertextError(ValueError): """A personal cell has no valid authenticated envelope.""" def _payload(value): if not isinstance(value, str) or not value.startswith(PREFIX): raise PiiCiphertextError("Amazon personal cell requires an AES-256-GCM envelope") try: raw = base64.b64decode(value[len(PREFIX):], altchars=b"-_", validate=True) except (ValueError, binascii.Error): raise PiiCiphertextError("Invalid Amazon personal cell envelope") from None if len(raw) <= NONCE_BYTES + 16: raise PiiCiphertextError("Invalid Amazon personal cell envelope") return raw def is_envelope(value): """Check envelope structure without reading a key or decrypting a cell.""" try: _payload(value) except PiiCiphertextError: return False return True class PiiCipher: """Load exactly 32 decoded key bytes from one environment slot.""" def __init__(self, slot=KEY_SLOT): encoded = os.environ.get(slot) if not encoded: raise PiiKeyUnavailable(f"Missing Amazon personal encryption key slot: {slot}") try: key = base64.b64decode(encoded, altchars=b"-_", validate=True) except (ValueError, binascii.Error): raise PiiKeyUnavailable( f"Invalid Amazon personal encryption key slot: {slot}; expected base64 for exactly 32 bytes") from None if len(key) != 32: raise PiiKeyUnavailable( f"Invalid Amazon personal encryption key slot: {slot}; expected base64 for exactly 32 bytes") self._aes = AESGCM(key) @staticmethod def _context(table, column): return json.dumps(["amazon", table, column], separators=(",", ":")).encode("utf-8") def encrypt(self, value, *, table, column): """Return a fresh authenticated envelope while preserving null cells.""" if value is None: return None nonce = os.urandom(NONCE_BYTES) plain = json.dumps(value, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode("utf-8") sealed = self._aes.encrypt(nonce, plain, self._context(table, column)) return PREFIX + base64.urlsafe_b64encode(nonce + sealed).decode("ascii") def decrypt(self, value, *, table, column): """Authenticate the envelope and its table/column binding before returning a value.""" if value is None: return None raw = _payload(value) try: plain = self._aes.decrypt(raw[:NONCE_BYTES], raw[NONCE_BYTES:], self._context(table, column)) return json.loads(plain) except (InvalidTag, ValueError, UnicodeError): raise PiiCiphertextError("Amazon personal cell authentication failed") from None