diff --git a/src/c2pa/c2pa.py b/src/c2pa/c2pa.py index b669a2d0..71bf8ad6 100644 --- a/src/c2pa/c2pa.py +++ b/src/c2pa/c2pa.py @@ -75,6 +75,7 @@ 'c2pa_builder_with_archive', 'c2pa_builder_supported_mime_types', 'c2pa_builder_compose_manifest', + 'c2pa_builder_sign_embeddable', # Signer bindings 'c2pa_signer_create', 'c2pa_signer_from_info', @@ -1389,6 +1390,10 @@ def _setup_function(func, argtypes, restype=None): ctypes.c_ubyte), ctypes.c_size_t, ctypes.POINTER( ctypes.POINTER( ctypes.c_ubyte))], ctypes.c_int64) +_setup_function( + _lib.c2pa_builder_sign_embeddable, [ + ctypes.POINTER(C2paBuilder), ctypes.c_char_p, ctypes.POINTER( + ctypes.POINTER(ctypes.c_ubyte))], ctypes.c_int64) _setup_function(_lib.c2pa_signer_create, [ctypes.c_void_p, SignerCallback, @@ -3899,6 +3904,7 @@ class Builder(ManagedResource): 'action_error': "Error adding action: {}", 'archive_error': "Error writing archive: {}", 'archive_load_error': "Failed to load archive into builder: {}", + 'embeddable_error': "Error during embeddable signing: {}", } @classmethod @@ -4400,6 +4406,79 @@ def compose_manifest( if result_bytes_ptr: _lib.c2pa_free(result_bytes_ptr) + def sign_embeddable(self, format: str) -> bytes: + """Sign the manifest and return the composed bytes ready to + embed into the asset. + + Unlike sign(), no stream is involved: the hard binding + assertion (e.g. c2pa.hash.data) must already carry the real + hash and exclusion ranges. The signer is taken from this + builder's Context. Can only be called once; the Builder + is closed after signing. + + Args: + format: The MIME type of the content. + + Returns: + The composed, signed manifest bytes + + Raises: + C2paError: If no context signer is configured, if there is + no valid hard binding assertion, or if there was an + error during signing + """ + self._ensure_valid_state() + if not self._has_context_signer: + raise C2paError( + "No signer configured on the Builder's Context. " + "Create the Builder with a Context that has a signer.") + + # allow_autodetect=False, so this never returns None (raises instead). + format_arg = _format_ffi_arg( + _encode_format(format, "Builder", allow_autodetect=False)) + manifest_bytes_ptr = ctypes.POINTER(ctypes.c_ubyte)() + + # The Context pins the consumed signer's callback, which + # native invokes during this call + with self._exclusive_native_call(): + with _context_guard(self._context): + try: + result = _lib.c2pa_builder_sign_embeddable( + self._handle, + format_arg, + ctypes.byref(manifest_bytes_ptr), + ) + except Exception as e: + self.close() + raise C2paError(f"Error during signing: {e}") from e + + try: + _check_ffi_operation_result( + result, + "Error during signing", + check=lambda r: r < 0) + finally: + # Single use for a Builder, once signed, close. + self.close() + + # Capture the manifest bytes if available + manifest_bytes = b"" + if manifest_bytes_ptr and result > 0: + try: + manifest_bytes = ctypes.string_at(manifest_bytes_ptr, result) + except Exception: + manifest_bytes = b"" + finally: + # Always free the C-allocated memory, + # even if we failed to copy manifest bytes + try: + _lib.c2pa_free(manifest_bytes_ptr) + except Exception: + logger.error( + "Failed to release native manifest bytes memory") + + return manifest_bytes + def _sign_internal( self, format: str, diff --git a/tests/test_unit_tests.py b/tests/test_unit_tests.py index 92cbea80..93ddb68e 100644 --- a/tests/test_unit_tests.py +++ b/tests/test_unit_tests.py @@ -12,7 +12,9 @@ # each license. import ast +import base64 import gc +import hashlib import inspect import os import io @@ -147,6 +149,12 @@ def test_preflight_version_comes_from_rust_package_not_git_ref(self): self.assertIn(str(Path('/source/c2pa-rs') / 'Cargo.toml'), command.call_args.args[0]) + def test_library_validation_requires_embeddable_symbol(self): + # Fail-fast gate: the bundled native library must expose + # c2pa_builder_sign_embeddable (stream-less signing); a library + # missing it is rejected at import time. + for required in ('c2pa_builder_sign_embeddable',): + self.assertIn(required, c2pa_module._REQUIRED_FUNCTIONS) class TestIsReadableStream(unittest.TestCase): """ A stream is anything Stream will accept (read/write/seek/tell/flush). @@ -6191,7 +6199,178 @@ def test_instance_id_as_ingredient_identifier_in_catalog(self): reader.close() archive.close() +class TestBuilderSignEmbeddable(unittest.TestCase): + """Builder.sign_embeddable: sign and return the composed manifest + store bytes without reading the asset (pre-computed hard binding). + """ + + def setUp(self): + self.data_dir = FIXTURES_DIR + self.testPath = DEFAULT_TEST_FILE + with open(os.path.join(self.data_dir, "es256_certs.pem"), "rb") as cert_file: + self.certs = cert_file.read() + with open(os.path.join(self.data_dir, "es256_private.key"), "rb") as key_file: + self.key = key_file.read() + + with open(self.testPath, "rb") as image_file: + self.image = image_file.read() + + # Where the composed store will be embedded in the asset. + # For a JPEG this is the APP11 position after the SOI marker; + # the direct workflow leaves the choice of O to the caller. + self.excl_start = 2 + + def _signer(self): + signer_info = C2paSignerInfo( + alg=b"es256", + sign_cert=self.certs, + private_key=self.key, + ta_url=None, + ) + signer = Signer.from_info(signer_info) + self.addCleanup(signer.close) + return signer + + def _definition(self, excl_len, asset_hash): + return { + "claim_generator_info": [{"name": "python_test", "version": "0.0.1"}], + "format": "image/jpeg", + "title": "Embeddable Test", + "assertions": [ + { + "label": "c2pa.actions", + "data": { + "actions": [ + { + "action": "c2pa.created", + "digitalSourceType": "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation" + } + ] + } + }, + { + "label": "c2pa.hash.data", + "data": { + "name": "embeddable-test", + "alg": "sha256", + # Byte fields in a C2PA JSON definition use the + # b64'...' marker; a bare base64 string is stored + # verbatim as ASCII text bytes. + "hash": "b64'" + base64.b64encode(asset_hash).decode() + "'", + "exclusions": [ + {"start": self.excl_start, "length": excl_len} + ], + "pad": "b64''", + } + }, + ] + } + + def _sha256_excluding(self, data, start, length): + h = hashlib.sha256() + h.update(data[:start]) + h.update(data[start + length:]) + return h.digest() + + def _embed(self, store): + """Embed the composed store at the exclusion position.""" + return (self.image[:self.excl_start] + store + + self.image[self.excl_start + len(store):]) + + def _sign_embeddable_with_excl(self, excl_len): + """Sign with a hash computed over `self.image` minus the exclusion.""" + definition = self._definition( + excl_len, self._sha256_excluding( + self.image, self.excl_start, excl_len)) + builder = Builder.from_json(definition, Context(signer=self._signer())) + return builder, builder.sign_embeddable("image/jpeg") + + def _failure_codes(self, asset_bytes): + reader = Reader("image/jpeg", io.BytesIO(asset_bytes)) + self.addCleanup(reader.close) + detailed = json.loads(reader.detailed_json()) + results = detailed["validation_results"]["activeManifest"] + return [e["code"] for e in results.get("failure", [])] + + def _success_codes(self, asset_bytes): + reader = Reader("image/jpeg", io.BytesIO(asset_bytes)) + self.addCleanup(reader.close) + detailed = json.loads(reader.detailed_json()) + results = detailed["validation_results"]["activeManifest"] + return [e["code"] for e in results.get("success", [])] + + def test_embedded_store_verifies(self): + # The store size is stable for this definition (32-byte hash, + # one fixed-size exclusion), so the slot size can be measured + # with a placeholder hash and then filled with the real one. + excl_len = 4096 + _, probe = self._sign_embeddable_with_excl(excl_len) + excl_len = len(probe) + builder, store = self._sign_embeddable_with_excl(excl_len) + + self.assertEqual(len(store), excl_len) + self.assertFalse(builder.is_valid, "Builder must close after signing") + + embedded = self._embed(store) + self.assertNotIn( + "assertion.dataHash.mismatch", self._failure_codes(embedded)) + self.assertIn("claimSignature.validated", self._success_codes(embedded)) + + def test_tamper_outside_exclusions_breaks_binding(self): + excl_len = 4096 + _, probe = self._sign_embeddable_with_excl(excl_len) + excl_len = len(probe) + _, store = self._sign_embeddable_with_excl(excl_len) + embedded = bytearray(self._embed(store)) + embedded[self.excl_start + excl_len + 100] ^= 0xFF + self.assertIn( + "assertion.dataHash.mismatch", + self._failure_codes(bytes(embedded))) + + def test_store_slot_corruption_rejected(self): + """The store slot is excluded from the DataHash but carries the + signature: corrupting a byte inside it makes the manifest + undecodable, so the Reader rejects the asset.""" + excl_len = 4096 + _, probe = self._sign_embeddable_with_excl(excl_len) + excl_len = len(probe) + _, store = self._sign_embeddable_with_excl(excl_len) + embedded = bytearray(self._embed(store)) + embedded[self.excl_start + 500] ^= 0xFF + with self.assertRaises(Error): + Reader("image/jpeg", io.BytesIO(bytes(embedded))) + + def test_requires_context_signer(self): + builder = Builder.from_json(self._definition(4096, bytes(32))) + self.addCleanup(builder.close) + with self.assertRaises(Error) as ctx: + builder.sign_embeddable("image/jpeg") + self.assertIn("Context", str(ctx.exception)) + def test_without_hard_binding_fails(self): + definition = { + "claim_generator_info": [{"name": "python_test", "version": "0.0.1"}], + "format": "image/jpeg", + "title": "Embeddable Test", + "assertions": [ + { + "label": "c2pa.actions", + "data": { + "actions": [ + { + "action": "c2pa.created", + "digitalSourceType": "http://cv.iptc.org/newscodes/digitalsourcetype/digitalCreation" + } + ] + } + }, + ] + } + builder = Builder.from_json(definition, Context(signer=self._signer())) + with self.assertRaises(Error) as ctx: + builder.sign_embeddable("image/jpeg") + self.assertIn("hard binding", str(ctx.exception)) + self.assertFalse(builder.is_valid, "Builder closes on failed signing") class TestStream(unittest.TestCase): def setUp(self): self.temp_file = io.BytesIO()