Governance — Trust, Traceability & Audit Trail¶
The governance module provides core capabilities required for regulated clinical data environments:
Configuration Version Control — immutable, AES-256/Fernet-encrypted, parent-chained SHA-256
Studyconfiguration 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
StudyConfigurationJSON payloads are encrypted at rest before SQLite persistence usingcryptography.fernet.Fernet. Key material is resolved fromIMEDNET_ENCRYPTION_KEY, falling back toIMEDNET_SECURITY_KEY, the activesecurity_key_contextbound byImednetSDK/sdk.study_context(...), or thesdksecurity key captured duringcommit_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 withValueError.Dynamic host path scoping & legacy fallback — the base SQLite path defaults to
IMEDNET_CONFIG_DB_PATHor~/.imednet/config_versions.sqlite3. At runtime,db_pathisolates ledger files per host under<base_dir>/<sanitized_host>/<filename>derived from the activebase_url_context/IMEDNET_BASE_URL(defaultlocalhost), validatingstudy_keyandstudy_contextviavalidate_partition_keyto prevent path traversal without splitting directories bystudy_context(whileresolve_committed_configfalls 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 usecontent_hashascommit_id, while child commits chain cryptographically viasha256(f"{parent_commit_id}:{content_hash}")(withStudy-key disambiguation if an identical chain appears in anotherStudy) and update per-StudyHEAD pointers inconfig_heads. SQLiteBEFORE UPDATEandBEFORE DELETEtriggers block in-place mutation or deletion ofconfig_commitsrows, andget_history/rollback_config()re-verify bothcontent_hashand the parent-chainedcommit_idafter decryption. Committing an unchanged configuration relative to HEAD raisesValueError.Role-Based Access Control (RBAC) —
commit_config(..., sdk=sdk)requires an authenticatedImednetSDKinstance withsdk.authconfigured (raisingPermissionErrorotherwise).sdk.auth.get_user_roles()must grant"admin"or"manager"(rejecting"reviewer"and"viewer"roles withPermissionError). When legacyApiKeyAuthis used without OIDC role claims,ConfigVersionStorevalidates server-sideStudyaccess viasdk.get_sites(study_key, limit=1)before recordingauthor="legacy-api-key".Rollback safety —
rollback_config()is non-destructive; it decrypts, verifies, and returns the historicalStudyConfigurationwithout 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:
objectImmutable append-only store for
StudyConfigurationversions.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
StudyConfigurationto 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, andchangedsub-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_idfor study_key, orNoneif 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, andcontent_hash. Theconfig_databody is intentionally omitted to keep the payload small — userollback_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
StudyConfigurationwithout 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, orNoneif 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
StudyConfigurationstored 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: