####################################################### Importing a *Specifieke categorie 3-milieuverklaring* ####################################################### A *Specifieke categorie 3-milieuverklaring* (SCM) is a project-specific environmental declaration derived from a published environmental declaration. Calculation tools can use this guide to verify an SCM export and use its environmental data in a project calculation. ******************************** JSON Schema and schema version ******************************** This guide covers `SCM export 1.0.0 <../../_static/schemas/scm-export-1.0.0.schema.json>`_. The JSON Schema uses `Draft 2020-12 `_. In the schema, ``$schema`` specifies the dialect and ``$id`` identifies this version of the SCM schema. .. code-block:: text https://documentatie.milieudatabase.nl/_static/schemas/scm-export-1.0.0.schema.json The export JSON carries neither a schema ID nor a schema version. Configure the calculation tool to use the schema above for this export format and record the schema version on import. The schema follows `SemVer `_. Each schema version has its own ``$id`` and documentation. The schema allows unknown properties so importers can retain extensions and continue processing known fields. ************************************** SCM registration number and revision ************************************** The SCM ``registration_number`` takes the form ``nmdscm__``. In ``nmdscm_94424_abcd``, ``94424`` comes from source registration ``nmd_94424``, and ``abcd`` is a random suffix of four lowercase letters from ``a`` to ``z``. NMD assigns the full registration number. It stays the same across revisions of an SCM. ``version_number`` is an integer that starts at 1 and increments by 1 for each SCM. Use ``registration_number`` and ``version_number`` together as the key and keep a record of the revision each calculation uses. Version 1 of the example SCM has the following archive contents. .. code-block:: text nmdscm_94424_abcd_v1.zip nmdscm_94424_abcd_v1.jwt nmdscm_94424_abcd_v1.pdf onderbouwingsbestanden/nmdscm_94424_abcd_v1_bijlage_1_onderbouwing.pdf ************* JSON fields ************* .. list-table:: :header-rows: 1 :widths: 34 66 - - Field - Meaning - - ``registration_number``, ``version_number`` - SCM registration number and revision number. - - ``title``, ``description`` - Title and description of this SCM revision. Use ``title`` as the display name. - - ``exported_at`` - Date and time of export, including the time zone. - - ``project.title``, ``project.reference_date`` - Project name and project reference date in ``YYYY-MM-DD`` format. - - ``source_declaration.id``, ``source_declaration.registration_number`` - NMD UUID of the specific source declaration revision and its registration number. - - ``environmental_declaration`` - Source declaration data based on the NMD API v3.0 response structure, with recalculated scores for this SCM revision. - - ``files`` - Manifest of the SCM report and supporting documents in the ZIP archive. Project context and source declaration ====================================== The client sets the project reference date. This date is used to check whether the source declaration is active and meets the SCM eligibility rules. Link the SCM to the intended project and check the project name and reference date on import. For profile recalculation, the standard transport distances and reference process data applicable on the source declaration's LCA reference date are used. A source declaration that covers both buildings and utilities (B&U) and civil engineering (GWW) meets the GWW field-of-application criterion even if the export shows the B&U UUID in ``field_of_application``. A source declaration with an explicit A4 transport amount override is ineligible for an SCM. Use ``source_declaration.id`` to look up the published source revision with ``GET /api/3.0/environmental-declarations/{id}/``. The same source revision UUID appears in ``environmental_declaration.id`` and in each profile's ``environmental_declaration`` field. The embedded ``environmental_declaration`` uses the same top-level fields as the v3.0 response. In its nested ``environmental_data`` entries, the SCM export omits ``score_file`` and provides the recalculated score matrices in ``scores``. Validate the embedded object using the SCM export schema. ``active_from`` and ``active_until`` define the validity period of the source revision. A ``null`` value for ``active_until`` means the source revision has no end date recorded in the export. SCM overrides ============= An SCM revision must modify or add at least one life cycle item in module A4 or A5 of a source environmental profile. - **A4 (transport to the construction site).** Change the distance or reference process of an existing transport item, or add an item with its own distance and reference process. The full profile mass for an added transport item is used. - **A5 (construction and installation).** Change the quantity or reference process of an existing material item, or add an item with its own quantity and reference process. Export requires an explanation for each overridden value on an existing item or for the addition of a new item, plus a supporting document for each changed or added item. The profiles are recalculated before export of the SCM. Use the complete matrices in ``environmental_data[].scores`` as the input to your calculation. These contain the effect of the overrides and use the source entry's UUID and assessment strategy. See the :doc:`NMD API v3.0 documentation ` for the shared field definitions. ********************************* Report and supporting documents ********************************* ``files`` contains one entry with ``role: report`` for the SCM report and one entry with ``role: supportive_document`` for each supporting document. ``file_name`` is the relative path in the ZIP archive. Attachments live under ``onderbouwingsbestanden/`` and have an attachment number in the filename. Use the full path from the manifest to find each attachment. The manifest associates attachments with the SCM revision as a whole. This export format has no references from individual scores, profiles, or A4/A5 changes to specific attachments. After verifying the eSeal, check the complete contents of the ZIP archive. 1. Require exactly one root-level ``.jwt`` entry. Its filename stem must match the signed ``registration_number`` and ``version_number``, for example ``nmdscm_94424_abcd_v1``. The outer ZIP filename may differ. 2. Compare the remaining archive paths with the manifest's ``file_name`` values. Each path must appear exactly once in both lists. Reject duplicate, missing, or extra files. 3. For each manifest entry, compare ``size`` with the number of uncompressed bytes and ``hash`` with the hexadecimal SHA-256 digest of those bytes. The manifest records the algorithm in ``hash_algorithm``. The exporter derives ``mime_type`` from the filename. It uses ``application/octet-stream`` for an unknown extension or an extension with a separate compression encoding, such as gzip for ``.tgz``. Apply the same size and hash checks to attachments with this media type. ********************* Verifying the eSeal ********************* The ``.jwt`` file contains a compact JWS with three base64url segments separated by periods. Its payload contains the declaration as UTF-8 JSON. The protected header contains the following fields. .. list-table:: :header-rows: 1 :widths: 34 66 - - Field - Value - - ``alg`` - ``RS256`` - - ``typ`` - ``JWT`` - - ``iat`` - An integer Unix timestamp in seconds. - - ``x5c`` - The X.509 certificate chain. Each certificate is DER encoded and represented in standard base64. The signer's certificate comes first and the self-signed root certificate comes last. See `RFC 7515 `_ and `RFC 7518 `_. The SCM payload is signed using RS256 and supplies the certificate chain in ``x5c``, following the same approach as the DSGO ``client_assertion``. See `DSGO Guide 4, step 3 `_. Configure the trusted root CA certificate and the expected NMD ``organizationIdentifier`` (OID ``2.5.4.97``) for the export environment through an independent trusted source. Confirm these values with NMD. .. warning:: Treat every certificate supplied in ``x5c`` as untrusted input until verification succeeds. 1. Read the protected header to obtain the signing certificate. Require ``RS256`` and use the public key from the first certificate to verify the signature over the original first two segments, including the period between them. 2. Use the verified header's integer ``iat`` as the X.509 validation time, including on later imports. The signer sets ``iat`` when creating the seal, so it can differ from ``exported_at``. Verify the supplied chain in order up to the configured root, and check the validity period of every certificate, including the root. If your trust policy requires revocation checks, obtain the required CRL or OCSP evidence from the CA as part of certificate validation. 3. Require exactly one ``organizationIdentifier`` with the configured NMD value and the ``contentCommitment`` (``nonRepudiation``) key usage in the signing certificate. 4. After verification succeeds, decode the payload as UTF-8 and parse it as JSON. Python verification example =========================== The Python example uses a JWS API to return the raw payload bytes and an X.509 store with one trusted root to validate the certificate path at ``iat``. Add revocation handling as required by your trust policy. See the `PyJWT JWS API `_ and `pyOpenSSL X.509 API `_. .. code-block:: python import argparse import base64 import sys from datetime import UTC, datetime from pathlib import Path from cryptography import x509 from cryptography.hazmat.primitives.asymmetric import rsa from jwt.api_jws import PyJWS from OpenSSL import crypto def load_trusted_root(pem: bytes) -> x509.Certificate: roots = [] for certificate in x509.load_pem_x509_certificates(pem): if certificate.subject != certificate.issuer: continue try: constraints = certificate.extensions.get_extension_for_class( x509.BasicConstraints ).value except x509.ExtensionNotFound: continue if constraints.ca: roots.append(certificate) if len(roots) != 1: raise ValueError("Expected exactly one root CA certificate in the trusted PEM") return roots[0] def verify_eseal( token: bytes, trusted_root: x509.Certificate, organization_identifier: str, ) -> bytes: jws = PyJWS() header = jws.get_unverified_header(token) if header.get("alg") != "RS256" or header.get("typ") != "JWT": raise ValueError("Expected an RS256 eSeal JWT") if "crit" in header or header.get("b64", True) is not True: raise ValueError("Unsupported JWS header parameters") encoded_chain = header.get("x5c") if not isinstance(encoded_chain, list) or not encoded_chain: raise ValueError("Missing certificate chain in x5c") chain = [] for encoded_certificate in encoded_chain: if not isinstance(encoded_certificate, str): raise ValueError("Expected base64-encoded certificates in x5c") der = base64.b64decode(encoded_certificate, validate=True) chain.append(x509.load_der_x509_certificate(der)) leaf = chain[0] public_key = leaf.public_key() if not isinstance(public_key, rsa.RSAPublicKey): raise ValueError("Expected an RSA signing certificate") verified = jws.decode_complete(token, key=public_key, algorithms=["RS256"]) issued_at = verified["header"].get("iat") if type(issued_at) is not int: raise ValueError("Expected an integer iat in the protected header") signed_at = datetime.fromtimestamp(issued_at, tz=UTC) store = crypto.X509Store() store.add_cert(crypto.X509.from_cryptography(trusted_root)) store.set_time(signed_at) store.set_flags(crypto.X509StoreFlags.CHECK_SS_SIGNATURE) context = crypto.X509StoreContext( store, crypto.X509.from_cryptography(leaf), [crypto.X509.from_cryptography(cert) for cert in chain[1:-1]], ) verified_chain = [cert.to_cryptography() for cert in context.get_verified_chain()] if verified_chain != chain: raise ValueError("x5c does not match the validated chain to the trusted root") identifiers = leaf.subject.get_attributes_for_oid( x509.NameOID.ORGANIZATION_IDENTIFIER ) if len(identifiers) != 1 or identifiers[0].value != organization_identifier: raise ValueError("Unexpected signing organisation") key_usage = leaf.extensions.get_extension_for_class(x509.KeyUsage).value if not key_usage.content_commitment: raise ValueError("Signing certificate lacks contentCommitment key usage") return verified["payload"] def main(): parser = argparse.ArgumentParser( description="Verify an SCM eSeal and write its JSON payload to standard output" ) parser.add_argument("--jwt_file", type=Path) parser.add_argument( "--trusted_root_pem", type=Path, help="Trusted PEM file containing the root CA, optionally with its chain", ) parser.add_argument("--organization_identifier") args = parser.parse_args() try: trusted_root = load_trusted_root(args.trusted_root_pem.read_bytes()) except ValueError as error: parser.error(str(error)) json_bytes = verify_eseal( args.jwt_file.read_bytes(), trusted_root, args.organization_identifier, ) sys.stdout.buffer.write(json_bytes) if __name__ == "__main__": main() After verifying the eSeal, complete these checks before using an SCM ZIP export in a calculation. - **Schema.** Validate the verified JSON payload against the supported SCM schema, including date and UUID formats. See :ref:`JSON Schema and schema version`. - **JWT filename.** Check that the root-level JWT filename uses the stem derived from the signed ``registration_number`` and ``version_number``. - **Manifest.** Check that the remaining ZIP entries match ``files`` exactly, with no duplicates. Verify each file's uncompressed size and SHA-256 digest. See :ref:`Report and supporting documents` for the filename and manifest rules. Testing an export locally ========================= Save the Python verification example above as ``verify_eseal.py`` and run it with Python 3.11 or later. Use the ``.jwt`` file and the independently configured root certificate in PEM format. Substitute your test filenames and organisation identifier below. .. code-block:: bash python -m pip install 'PyJWT[crypto]' pyOpenSSL python verify_eseal.py \ --jwt_file nmdscm_94424_abcd_v1.jwt \ --trusted_root_pem trusted-root.pem \ --organization_identifier NTRNL-00000000 \ > verified.json On success, the command exits with code 0 and ``verified.json`` contains the exact payload bytes. Expect a nonzero exit code and no bytes on standard output if the signature is invalid, the configured root CA or organisation identifier is incorrect, or the signed ``iat`` is outside a certificate's validity period. *********************************** Importing into a calculation tool *********************************** You can import an SCM directly in place of its published source declaration for the intended project. Use the embedded ``environmental_declaration`` as the input to your existing declaration import. Its product and profile fields follow the NMD API v3.0 structure. Read the complete, recalculated score matrices from ``environmental_data[].scores`` in each profile. Use ``source_declaration`` to identify the published revision the SCM is based on. 1. Find exactly one root-level ``.jwt`` entry in the ZIP and verify its eSeal as described in :ref:`Verifying the eSeal`. Parse the verified payload as JSON and validate it against the supported SCM schema, with date and UUID format checks enabled. Check that the source revision UUID in ``source_declaration`` matches the UUID in ``environmental_declaration`` and in each profile. Verify the JWT filename and ZIP manifest as described in :ref:`Report and supporting documents`. Stop the import if any check fails. 2. Link the SCM to the intended project and store it under ``(registration_number, version_number)``. Scope its profiles and scores to that key so they can share source UUIDs with other SCM revisions and the source declaration. Preserve the order and precision of the score matrices. When reimporting the same revision with identical JSON, you can reuse the existing record. Flag differing contents under an already imported key before replacing any existing data. 3. Select the SCM revision for the project calculation. Run the standard NMD calculation with the SCM's profile quantities and scores, applying any :doc:`scaling `, weighting, and category surcharge required by the applicable rules. Report any missing scores or references the calculation requires. 4. Keep the original ZIP archive or the original JWT and all files listed in its manifest with the revision so the tool can verify the calculation inputs again later.