import hashlib import io import os from pathlib import Path import secrets import warnings from PIL import Image, ImageOps, UnidentifiedImageError class InvalidImage(ValueError): pass def normalize_image(content, pixel_limit=20_000_000): try: with warnings.catch_warnings(): warnings.simplefilter('error', Image.DecompressionBombWarning) with Image.open(io.BytesIO(content)) as source: if source.format not in ('JPEG', 'PNG', 'WEBP'): raise InvalidImage('Use JPEG, PNG or static WebP') if getattr(source, 'n_frames', 1) != 1: raise InvalidImage('Animated images are not supported') if source.width * source.height > pixel_limit or min(source.size) < 32: raise InvalidImage('Image must be at least 32px per side and at most 20 megapixels') source.load() image = ImageOps.exif_transpose(source).convert('RGBA') background = Image.new('RGBA', image.size, (255, 255, 255, 255)) background.alpha_composite(image) clean = background.convert('RGB') output = io.BytesIO() clean.save(output, format='PNG') return output.getvalue(), {'width': clean.width, 'height': clean.height, 'content_type': 'image/png'} except (UnidentifiedImageError, OSError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc: raise InvalidImage('Image could not be safely decoded') from exc class Storage: def __init__(self, root): self.root = Path(root).resolve() self.root.mkdir(parents=True, exist_ok=True) def path(self, key): p = (self.root / key).resolve() if not p.is_relative_to(self.root) or p == self.root: raise ValueError('Invalid storage key') return p def write(self, key, data): path = self.path(key) path.parent.mkdir(parents=True, exist_ok=True) temp = path.with_name(path.name + '.' + secrets.token_hex(8) + '.tmp') try: with temp.open('xb') as f: f.write(data) f.flush() os.fsync(f.fileno()) os.replace(temp, path) finally: temp.unlink(missing_ok=True) return hashlib.sha256(data).hexdigest() def check(self): key = '.health/' + secrets.token_hex(8) self.write(key, b'ok') self.path(key).unlink()