Coverage for app / util / document_images.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-10-31 11:21 +0000

1"""Images a document carries — how they are named, stored and checked. 

2 

3A document (``render_document``) may show images. svc-ai fetches each once, 

4when the document is made, normalises it to a PNG or JPEG and stores it in 

5MinIO under the SHA-256 of those bytes; the document's fence records the hash 

6(its *asset* id). The PDF (svc-ai) and the document card (served by svc-core) 

7draw that stored copy, never the original URL. 

8 

9This module is carried by both services, byte for byte 

10(``tools/test_shared_modules.py``): svc-ai writes the objects, svc-core serves 

11them, and both must agree on the key an id names and on what counts as an 

12image worth serving. An object is served only when its bytes hash to the id 

13that named it and are one of :data:`SERVED_TYPES` — so an id copied into a 

14record cannot be made to serve anything else. 

15""" 

16 

17from __future__ import annotations 

18 

19import hashlib 

20import re 

21 

22#: An asset id: the lower-case SHA-256 of the stored bytes. 

23ASSET_ID = re.compile(r"^[0-9a-f]{64}$") 

24 

25#: Where the stored copies live in the knowledge bucket. 

26OBJECT_PREFIX = "document-images/" 

27 

28#: What a stored copy may be. Everything fetched is re-encoded to one of these. 

29SERVED_TYPES = frozenset({"image/png", "image/jpeg"}) 

30 

31#: Magic bytes → media type, for the raster formats any image may arrive in. 

32_SIGNATURES: tuple[tuple[bytes, int, str], ...] = ( 

33 (b"\x89PNG\r\n\x1a\n", 0, "image/png"), 

34 (b"\x00\x00\x01\x00", 0, "image/x-icon"), 

35 (b"GIF87a", 0, "image/gif"), 

36 (b"GIF89a", 0, "image/gif"), 

37 (b"\xff\xd8\xff", 0, "image/jpeg"), 

38 (b"WEBP", 8, "image/webp"), # after "RIFF????" 

39) 

40 

41 

42def is_asset_id(value: object) -> bool: 

43 """Whether ``value`` is a well-formed asset id.""" 

44 return isinstance(value, str) and bool(ASSET_ID.match(value)) 

45 

46 

47def asset_id_of(data: bytes) -> str: 

48 """The asset id ``data`` is stored under.""" 

49 return hashlib.sha256(data).hexdigest() 

50 

51 

52def object_key(asset: str) -> str: 

53 """The object an asset id names. Raises ``ValueError`` for anything that 

54 is not an asset id, so no caller can build a key from other text.""" 

55 if not is_asset_id(asset): 

56 raise ValueError("not an asset id") 

57 return f"{OBJECT_PREFIX}{asset}" 

58 

59 

60def sniff(data: bytes) -> str | None: 

61 """The raster type ``data`` is, from its bytes — or None.""" 

62 for signature, offset, media_type in _SIGNATURES: 

63 if data[offset : offset + len(signature)] == signature: 

64 if media_type == "image/webp" and data[:4] != b"RIFF": 

65 continue 

66 return media_type 

67 return None 

68 

69 

70def verified(asset: str, data: bytes | None) -> str | None: 

71 """The media type to serve ``data`` as, when it is the asset ``asset`` 

72 names: its bytes hash to the id and are a served type. None otherwise.""" 

73 if not data or not is_asset_id(asset) or asset_id_of(data) != asset: 

74 return None 

75 media_type = sniff(data) 

76 return media_type if media_type in SERVED_TYPES else None