Governance — Trust, Traceability & Audit Trail

The governance module provides core capabilities required for regulated clinical data environments:

  1. Configuration Version Control — immutable, AES-256/Fernet-encrypted, parent-chained SHA-256 Study configuration history with RBAC enforcement, structural diff, and read-only rollback.

This capability is implemented in imednet-workflows via the ConfigVersionStore class.

Configuration Version Control

imednet_workflows.config_version_control provides ConfigVersionStore, a thread-safe SQLite-backed ledger for StudyConfiguration versions.

Key properties

  • AES-256 / Fernet payload encryption — serialized StudyConfiguration JSON payloads are encrypted at rest before SQLite persistence using cryptography.fernet.Fernet. Key material is resolved from IMEDNET_ENCRYPTION_KEY, falling back to IMEDNET_SECURITY_KEY, the active security_key_context bound by ImednetSDK / sdk.study_context(...), or the sdk security key captured during commit_config: a 32-byte URL-safe base64 Fernet key is used directly, while passphrases are hashed with SHA-256 into a 32-byte key. Missing or mismatched keys fail closed with ValueError.

  • Dynamic host path scoping & legacy fallback — the base SQLite path defaults to IMEDNET_CONFIG_DB_PATH or ~/.imednet/config_versions.sqlite3. At runtime, db_path isolates ledger files per host under <base_dir>/<sanitized_host>/<filename> derived from the active base_url_context / IMEDNET_BASE_URL (default localhost), validating study_key and study_context via validate_partition_key to prevent path traversal without splitting directories by study_context (while resolve_committed_config falls back read-only to legacy <base_dir>/<sanitized_host>/<study_key>/<filename> and <base_dir>/<filename> paths).

  • Parent-chained SHA-256 commit hashes & SQLite immutability — each payload computes content_hash = sha256(config_json). Root commits use content_hash as commit_id, while child commits chain cryptographically via sha256(f"{parent_commit_id}:{content_hash}") (with Study-key disambiguation if an identical chain appears in another Study) and update per-Study HEAD pointers in config_heads. SQLite BEFORE UPDATE and BEFORE DELETE triggers block in-place mutation or deletion of config_commits rows, and get_history / rollback_config() re-verify both content_hash and the parent-chained commit_id after decryption. Committing an unchanged configuration relative to HEAD raises ValueError.

  • Role-Based Access Control (RBAC) — commit_config(..., sdk=sdk) requires an authenticated ImednetSDK instance with sdk.auth configured (raising PermissionError otherwise). sdk.auth.get_user_roles() must grant "admin" or "manager" (rejecting "reviewer" and "viewer" roles with PermissionError). When legacy ApiKeyAuth is used without OIDC role claims, ConfigVersionStore validates server-side Study access via sdk.get_sites(study_key, limit=1) before recording author="legacy-api-key".

  • Rollback safety — rollback_config() is non-destructive; it decrypts, verifies, and returns the historical StudyConfiguration without modifying existing ledger rows.

Quick-start

import os
import tempfile
from pathlib import Path

from imednet import ImednetSDK
from imednet.models.study_config import MappingRule, StudyConfiguration
from imednet.simulation import SimulationTransport
from imednet_workflows import ConfigVersionStore

prev_enc_key = os.environ.get("IMEDNET_ENCRYPTION_KEY")
os.environ["IMEDNET_ENCRYPTION_KEY"] = "governance-demo-key"  # pragma: allowlist secret
try:
    with tempfile.TemporaryDirectory() as tmpdir:
        db_file = Path(tmpdir) / "config_versions.sqlite3"
        store = ConfigVersionStore(db_path=db_file)
        transport = SimulationTransport()

        with ImednetSDK(
            api_key="sim-api-key",  # pragma: allowlist secret
            security_key="sim-security-key",  # pragma: allowlist secret
            transport=transport,
        ) as sdk:
            v1_config = StudyConfiguration.model_validate(
                {
                    "studyKey": "STUDY",
                    "mappings": [
                        MappingRule.model_validate(
                            {
                                "domain": "AE",
                                "targetField": "AETERM",
                                "sourceFormKey": "AE_FORM",
                                "sourceVariableName": "ae_term",
                            }
                        )
                    ],
                }
            )
            v1_id = store.commit_config(
                study_key="STUDY",
                config=v1_config,
                desc="Initial AE Record mapping configuration",
                sdk=sdk,
            )

            v2_config = StudyConfiguration.model_validate(
                {
                    "studyKey": "STUDY",
                    "phiFields": ["custom_note"],
                    "mappings": v1_config.mappings,
                }
            )
            v2_id = store.commit_config(
                study_key="STUDY",
                config=v2_config,
                desc="Add custom PHI Variable declaration",
                sdk=sdk,
            )

            history = store.get_history("STUDY")
            assert len(history) == 2
            assert history[0]["commit_id"] == v1_id
            assert history[1]["commit_id"] == v2_id
            assert history[1]["parent_commit_id"] == v1_id

            diff = store.diff_configs(v1_id, v2_id)
            assert diff["added"] == {"phiFields[0]": "custom_note"}

            restored = store.rollback_config("STUDY", v1_id)
            assert restored.phi_fields == []
finally:
    if prev_enc_key is None:
        os.environ.pop("IMEDNET_ENCRYPTION_KEY", None)
    else:
        os.environ["IMEDNET_ENCRYPTION_KEY"] = prev_enc_key

API reference

class imednet_workflows.config_version_control.ConfigVersionStore[source]

Bases: object

Immutable append-only store for StudyConfiguration versions.

Each call to commit_config() creates a new entry signed with a SHA-256 digest of the serialised configuration body. History is strictly read-only — individual commit rows may never be edited or deleted.

Parameters:

db_path – Filesystem path for the SQLite database. Defaults to ~/.imednet/config_versions.sqlite3.

__init__(db_path=None, *, base_url=None, sdk=None)[source]

Initialize the configuration version store.

Parameters:
  • db_path (str | Path | None) – Path to the SQLite database file.

  • base_url (str | None) – Optional explicit API origin URL to pin this store to.

  • sdk (Any) – Optional SDK instance to extract pinned origin and session credentials from.

Return type:

None

commit_config(study_key, config, desc, *, sdk=None)[source]

Serialise config, compute its SHA-256 hash, and persist the commit.

Parameters:
  • study_key (str) – Identifies the study this configuration belongs to.

  • config (StudyConfiguration) – The StudyConfiguration to store.

  • desc (str) – Human-readable description of what changed.

  • sdk (Any) – The SDK instance used to verify server-side permissions.

Returns:

The commit_id (SHA-256 hex digest of the serialised JSON body).

Raises:
  • ValueError – If a commit with the same content hash already exists.

  • PermissionError – If an authenticated SDK session is not provided, or if the authenticated session does not have manager/admin role.

Return type:

str

classmethod current_store_state_token()[source]

Return a fast in-memory state token capturing active store path, context, and write generation.

Return type:

tuple[Any, …]

property db_path: Path

Return the dynamically selected database file path based on pinned or active base URL.

diff_configs(commit_a, commit_b)[source]

Compute a property-level diff between two commits.

Compares the flat JSON key space of the two commits. Returns a dict with three sub-keys:

  • added — keys present in b but not in a.

  • removed — keys present in a but not in b.

  • changed — keys present in both but with different values.

Parameters:
  • commit_a (str) – SHA-256 commit ID of the before state.

  • commit_b (str) – SHA-256 commit ID of the after state.

Returns:

Dict with added, removed, and changed sub-dicts.

Raises:

KeyError – If either commit ID is not found in the store.

Return type:

dict[str, Any]

get_head(study_key)[source]

Return the current head commit_id for study_key, or None if empty.

Parameters:

study_key (str) –

Return type:

str | None

get_history(study_key)[source]

Return all commits for study_key, ordered oldest-first.

Parameters:

study_key (str) – The study whose history should be retrieved.

Returns:

A list of dicts, each with keys commit_id, study_key, version_tag, modified_by, description, timestamp, parent_commit_id, and content_hash. The config_data body is intentionally omitted to keep the payload small — use rollback_config() to retrieve the full body for a specific commit.

Return type:

list[dict[str, Any]]

classmethod resolve_committed_config(study_key)[source]

Read the latest committed StudyConfiguration without creating empty DB files.

Parameters:

study_key (str) –

Return type:

StudyConfiguration | None

classmethod resolve_committed_study_keys()[source]

Return (state_token, known_study_keys) across active SQLite/legacy paths, or None if mocked.

Return type:

tuple[tuple[Any, …], frozenset[str]] | None

classmethod resolve_legacy_committed_config(study_key)[source]

Read latest committed StudyConfiguration from legacy study-partitioned SQLite paths.

Parameters:

study_key (str) –

Return type:

StudyConfiguration | None

rollback_config(study_key, commit_id)[source]

Restore and return the StudyConfiguration stored at commit_id.

This method is non-destructive — it does not modify any existing history rows. The caller is responsible for creating a new commit via commit_config() if they wish to record the rollback.

Parameters:
  • study_key (str) – The study the commit must belong to.

  • commit_id (str) – The SHA-256 commit ID to restore.

Returns:

The deserialised StudyConfiguration.

Raises:

KeyError – If the commit is not found or does not belong to the requested study.

Return type:

StudyConfiguration