Skip to content

Health Software Common Practices

HSCP-T-001 · open test

Machine-readable component inventory, later than the last deployment

Serves HSCP-G-160 · Recipe: HSCP-R-010

Code under the licence Apache 2.0 · Python 3.10 or later, standard library only, no network access

What the test checks

The evidence item is the component inventory of a piece of software (SBOM), in JSON. The test accepts it if:

  • it is a CycloneDX document (version 1.4, 1.5 or 1.6) or an SPDX document (version 2.2 or 2.3);
  • it carries its production date (metadata.timestamp in CycloneDX, creationInfo.created in SPDX);
  • it lists at least one component, and every component has a name and a version;
  • its date is not earlier than the last declared deployment: an inventory older than what is running does not describe what is running.

A component without a purl is reported, without refusal.

Running the test

python3 verifier.py inventaire.cdx.json --deploiement 2026-11-20T09:30:00Z

--json gives the same answer in JSON. Exit code: 0 evidence accepted, 1 evidence refused, 2 incorrect call. Python 3.10 or later, no dependency, no network access.

In continuous integration, run the test right after the inventory is produced, with the time of the current deployment.

Producing the evidence

The test does not produce the inventory: free tools already do, for example Syft (syft <image> -o cyclonedx-json), cdxgen (cdxgen -o bom.json) or Trivy (trivy image --format cyclonedx <image>). The test checks what they produced.

Examples

  • exemples/valide/: a CycloneDX 1.6 inventory produced after the deployment. Accepted.
  • exemples/refuse/: an SPDX 2.3 inventory produced eight days before the deployment, with one package without a version. Refused twice.

Each folder holds the command line in its commande file. python3 lancer.py, at the root of the tests, runs every example.

What the test does not say

  • It does not say whether the inventory is complete: a component missing from the inventory cannot be detected from the inventory alone.
  • It does not say whether a component is vulnerable.
  • It does not validate the document against the full CycloneDX or SPDX schema: it checks the fields the evidence needs.

Code

Download the test (zip archive: program, examples, README, licence) (10 KB) · verifier.py

The code and its messages are not translated (French).

#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 les contributeurs des Gestes communs du logiciel de santé
"""HSCP-T-001 : inventaire des composants lisible par machine, postérieur au dernier déploiement.

    python3 verifier.py <inventaire.json> --deploiement AAAA-MM-JJTHH:MM:SSZ [--json]

Vérifie la pièce, pas le produit : l'inventaire est un document CycloneDX (JSON, version 1.4 à 1.6) ou SPDX (JSON,
version 2.2 ou 2.3), il porte une date de production, il liste au moins un composant nommé et versionné, et sa date
n'est pas antérieure au dernier déploiement déclaré. Il ne dit pas si l'inventaire est complet ni si un composant est
vulnérable.

Codes de retour : 0 pièce acceptée, 1 pièce refusée, 2 appel incorrect.
Bibliothèque standard seulement, aucun accès réseau.
"""
import argparse
import datetime as dt
import json
import sys

ID = "HSCP-T-001"
CYCLONEDX = ("1.4", "1.5", "1.6")
SPDX = ("SPDX-2.2", "SPDX-2.3")


def instant(texte):
    """Date ISO 8601 (avec heure et fuseau, ou date seule lue à minuit UTC) → datetime avec fuseau, ou None."""
    s = str(texte or "").strip()
    if not s:
        return None
    try:
        d = dt.datetime.fromisoformat(s.replace("Z", "+00:00") if "T" in s else s + "T00:00:00+00:00")
    except ValueError:
        return None
    return d if d.tzinfo else d.replace(tzinfo=dt.timezone.utc)


def lire_cyclonedx(doc, refus, notes):
    if doc.get("specVersion") not in CYCLONEDX:
        refus.append(f"CycloneDX specVersion « {doc.get('specVersion')} » non lue (attendu : {', '.join(CYCLONEDX)})")
    date = (doc.get("metadata") or {}).get("timestamp")
    composants = doc.get("components")
    if not isinstance(composants, list):
        refus.append("champ components absent ou qui n'est pas une liste")
        composants = []
    sans_version = [c.get("name") or "(sans nom)" for c in composants if isinstance(c, dict) and not c.get("version")]
    sans_nom = sum(1 for c in composants if not isinstance(c, dict) or not c.get("name"))
    if sans_nom:
        refus.append(f"{sans_nom} composant(s) sans nom")
    if sans_version:
        refus.append(f"{len(sans_version)} composant(s) sans version, dont « {sans_version[0]} »")
    sans_purl = sum(1 for c in composants if isinstance(c, dict) and not c.get("purl"))
    if sans_purl:
        notes.append(f"{sans_purl} composant(s) sans purl : l'identification reste possible par nom et version")
    return "metadata.timestamp", date, len(composants)


def lire_spdx(doc, refus, notes):
    if doc.get("spdxVersion") not in SPDX:
        refus.append(f"spdxVersion « {doc.get('spdxVersion')} » non lue (attendu : {', '.join(SPDX)})")
    date = (doc.get("creationInfo") or {}).get("created")
    paquets = doc.get("packages")
    if not isinstance(paquets, list):
        refus.append("champ packages absent ou qui n'est pas une liste")
        paquets = []
    sans_nom = sum(1 for p in paquets if not isinstance(p, dict) or not p.get("name"))
    sans_version = [p.get("name") or "(sans nom)" for p in paquets if isinstance(p, dict) and not p.get("versionInfo")]
    if sans_nom:
        refus.append(f"{sans_nom} paquet(s) sans nom")
    if sans_version:
        refus.append(f"{len(sans_version)} paquet(s) sans versionInfo, dont « {sans_version[0]} »")
    return "creationInfo.created", date, len(paquets)


def verifier(chemin, deploiement):
    refus, notes = [], []
    try:
        with open(chemin, encoding="utf-8") as f:
            doc = json.load(f)
    except OSError as e:
        return {"refus": [f"fichier illisible : {e.strerror}"], "notes": []}
    except ValueError as e:
        return {"refus": [f"JSON illisible : {e}"], "notes": []}
    if not isinstance(doc, dict):
        return {"refus": ["le document n'est pas un objet JSON"], "notes": []}
    if doc.get("bomFormat") == "CycloneDX":
        forme = f"CycloneDX {doc.get('specVersion')}"
        champ, date, n = lire_cyclonedx(doc, refus, notes)
    elif str(doc.get("spdxVersion", "")).startswith("SPDX-"):
        forme = doc.get("spdxVersion")
        champ, date, n = lire_spdx(doc, refus, notes)
    else:
        return {"refus": ["ni CycloneDX (bomFormat) ni SPDX (spdxVersion) : forme non reconnue"], "notes": []}
    if not n:
        refus.append("inventaire sans composant")
    d = instant(date)
    if not date:
        refus.append(f"date de production absente ({champ})")
    elif not d:
        refus.append(f"date de production illisible ({champ} = « {date} »)")
    elif d < deploiement:
        refus.append(f"inventaire du {d.isoformat()} antérieur au dernier déploiement ({deploiement.isoformat()})")
    notes.insert(0, f"{forme}, {n} composant(s), produit le {d.isoformat() if d else '?'}")
    return {"refus": refus, "notes": notes}


def main(argv=None):
    analyseur = argparse.ArgumentParser(description=__doc__.split("\n")[0], formatter_class=argparse.RawDescriptionHelpFormatter)
    analyseur.add_argument("inventaire", help="fichier JSON CycloneDX ou SPDX")
    analyseur.add_argument("--deploiement", required=True, help="date et heure du dernier déploiement (ISO 8601)")
    analyseur.add_argument("--json", action="store_true", help="sortie JSON")
    a = analyseur.parse_args(argv)
    dep = instant(a.deploiement)
    if not dep:
        analyseur.error(f"--deploiement illisible : {a.deploiement}")
    r = verifier(a.inventaire, dep)
    r.update(test=ID, piece=a.inventaire, accepte=not r["refus"])
    if a.json:
        print(json.dumps(r, ensure_ascii=False, indent=1))
    else:
        print(f"{ID} inventaire des composants : {a.inventaire}")
        for x in r["refus"]:
            print(f"  REFUS  {x}")
        for x in r["notes"]:
            print(f"  NOTE   {x}")
        print("Résultat : " + ("pièce acceptée" if r["accepte"] else f"pièce refusée ({len(r['refus'])} refus)"))
    return 0 if r["accepte"] else 1


if __name__ == "__main__":
    sys.exit(main())

Files of the test