Add plan-only Device Core runtime drift audit without changing acceptance
This commit is contained in:
@@ -8,6 +8,7 @@ import grp
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
@@ -2960,6 +2961,11 @@ GITEA_SALVAGE_UNSUPPORTED_SCHEMA_TABLES = tuple(
|
||||
)
|
||||
|
||||
COMPONENTS = {
|
||||
"device-core-release-drift-audit": {
|
||||
"payload_root": DEVICE_PLANE_ROOT,
|
||||
"artifact_only": True,
|
||||
"services": (),
|
||||
},
|
||||
"device-core-release-reconciliation": {
|
||||
"payload_root": DEVICE_PLANE_ROOT,
|
||||
"artifact_only": True,
|
||||
@@ -4968,6 +4974,10 @@ def denied_payload_path(component, rel):
|
||||
|
||||
def allowed_payload_path(component, rel):
|
||||
validate_posix_path(rel)
|
||||
if component == "device-core-release-drift-audit":
|
||||
if rel in ("deployment", DEVICE_RELEASE_DRIFT_AUDIT_ENTRY):
|
||||
return True
|
||||
die("Device Core drift audit accepts only its exact descriptor")
|
||||
if component == "device-core-release-reconciliation":
|
||||
if rel in ("deployment", DEVICE_RELEASE_RECONCILIATION_ENTRY):
|
||||
return True
|
||||
@@ -11588,6 +11598,8 @@ def load_artifact(artifact, work_dir):
|
||||
die(f"files.txt entry missing in payload: {rel}")
|
||||
|
||||
validate_payload_tree(manifest["component"], payload_dir, entries)
|
||||
if manifest["component"] == "device-core-release-drift-audit":
|
||||
validate_device_release_drift_audit_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-core-release-reconciliation":
|
||||
validate_device_release_reconciliation_payload(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-core-release":
|
||||
@@ -22440,6 +22452,10 @@ def is_platform_provider_catalog_only(entries):
|
||||
|
||||
|
||||
def component_services(component, entries=None):
|
||||
if component == "device-core-release-drift-audit":
|
||||
if tuple(entries or ()) != (DEVICE_RELEASE_DRIFT_AUDIT_ENTRY,):
|
||||
die("Device Core drift audit requires the exact descriptor entry")
|
||||
return ()
|
||||
if component == "device-core-release-reconciliation":
|
||||
if tuple(entries or ()) != (DEVICE_RELEASE_RECONCILIATION_ENTRY,):
|
||||
die("Device Core reconciliation requires the exact descriptor entry")
|
||||
@@ -32623,6 +32639,159 @@ def device_release_r5_reconciled(row):
|
||||
return True
|
||||
|
||||
|
||||
# Diagnostic-only domain. Never used as a substitute acceptance fingerprint.
|
||||
DEVICE_RELEASE_DRIFT_AUDIT_ID = "device-core-release-r5-drift-audit-v1-20260929-001"
|
||||
DEVICE_RELEASE_DRIFT_AUDIT_ENTRY = "deployment/device-core-release-r5-drift-audit-v1.json"
|
||||
|
||||
|
||||
def device_release_drift_audit_descriptor():
|
||||
return {"schemaVersion": "nodedc.device-core.release-drift-audit.v1",
|
||||
"auditId": DEVICE_RELEASE_DRIFT_AUDIT_ID,
|
||||
"failedReleaseId": DEVICE_RELEASE_R5_ID,
|
||||
"failedSha256": DEVICE_RELEASE_R5_SHA,
|
||||
"backupId": DEVICE_RELEASE_R5_BACKUP, "mode": "read-only-plan;apply-forbidden"}
|
||||
|
||||
|
||||
def validate_device_release_drift_audit_payload(payload, entries, patch_id):
|
||||
if tuple(entries) != (DEVICE_RELEASE_DRIFT_AUDIT_ENTRY,) or patch_id != DEVICE_RELEASE_DRIFT_AUDIT_ID:
|
||||
die("Device Core drift audit identity/entry mismatch")
|
||||
if read_strict_json(payload / DEVICE_RELEASE_DRIFT_AUDIT_ENTRY, "Device Core drift audit") != device_release_drift_audit_descriptor():
|
||||
die("Device Core drift audit descriptor mismatch")
|
||||
|
||||
|
||||
def device_release_drift_fields(info):
|
||||
# Exact preimage of the existing snapshot, deliberately not changing it.
|
||||
host = json.loads(json.dumps(info.get("HostConfig") or {}))
|
||||
if isinstance(host.get("Ulimits"), list):
|
||||
host["Ulimits"].sort(key=lambda x: json.dumps(x, sort_keys=True))
|
||||
config = info.get("Config") or {}
|
||||
fields = {"HostConfig": host,
|
||||
"Config": {k: config.get(k) for k in ("Env", "User", "Cmd", "Entrypoint", "WorkingDir", "ExposedPorts")},
|
||||
"Mounts": sorted(info.get("Mounts") or [], key=lambda x: json.dumps(x, sort_keys=True)),
|
||||
"networks": sorted((info.get("NetworkSettings") or {}).get("Networks") or {})}
|
||||
if isinstance(fields["Config"]["Env"], list):
|
||||
fields["Config"]["Env"] = sorted(fields["Config"]["Env"])
|
||||
return fields
|
||||
|
||||
|
||||
def device_release_drift_digest(fields):
|
||||
return hashlib.sha256(json.dumps(fields, sort_keys=True).encode()).hexdigest()
|
||||
|
||||
|
||||
def device_release_drift_probe(fields, expected, budget=20000):
|
||||
"""Find an exact saved SHA preimage; report differences, never accept them."""
|
||||
current = device_release_drift_digest(fields)
|
||||
result = {"expectedSha256": expected, "actualSha256": current,
|
||||
"exactCurrentMatch": current == expected, "exactPreimageFound": current == expected,
|
||||
"candidatesChecked": 1, "changedFields": [], "searchTruncated": False}
|
||||
if current == expected:
|
||||
return result
|
||||
if not isinstance(expected, str) or not re.fullmatch(r"[a-f0-9]{64}", expected):
|
||||
die("Device Core drift audit expected digest is invalid")
|
||||
original = json.loads(json.dumps(fields))
|
||||
lists = []
|
||||
for name in ("Binds", "Mounts"):
|
||||
value = original["HostConfig"].get(name)
|
||||
if value is None:
|
||||
lists.append((name, None))
|
||||
continue
|
||||
if not isinstance(value, list) or len(value) > 8:
|
||||
result["searchTruncated"] = True
|
||||
result["reason"] = "mount-list-bound"
|
||||
return result
|
||||
encoded = [json.dumps(item, sort_keys=True) for item in value]
|
||||
if len(set(encoded)) != len(encoded):
|
||||
result["searchTruncated"] = True
|
||||
result["reason"] = "ambiguous-duplicate-mounts"
|
||||
return result
|
||||
lists.append((name, value))
|
||||
actual_mode = original["HostConfig"].get("NetworkMode")
|
||||
modes = [actual_mode] + [name for name in original["networks"] if name != actual_mode]
|
||||
# Only permutations of observed values and attached-network names. This can
|
||||
# identify a NetworkMode difference but cannot authorize changing/ignoring it.
|
||||
work = json.loads(json.dumps(original))
|
||||
left, right = lists
|
||||
for mode in modes:
|
||||
if mode != actual_mode or "NetworkMode" in original["HostConfig"]:
|
||||
work["HostConfig"]["NetworkMode"] = mode
|
||||
for left_order in ([None] if left[1] is None else itertools.permutations(left[1])):
|
||||
if left[1] is not None:
|
||||
work["HostConfig"][left[0]] = list(left_order)
|
||||
for right_order in ([None] if right[1] is None else itertools.permutations(right[1])):
|
||||
if right[1] is not None:
|
||||
work["HostConfig"][right[0]] = list(right_order)
|
||||
if result["candidatesChecked"] >= budget:
|
||||
result["searchTruncated"] = True
|
||||
return result
|
||||
result["candidatesChecked"] += 1
|
||||
if device_release_drift_digest(work) != expected:
|
||||
continue
|
||||
result["exactPreimageFound"] = True
|
||||
result["changedFields"] = ["HostConfig." + key for key in ("Binds", "Mounts", "NetworkMode")
|
||||
if work["HostConfig"].get(key) != original["HostConfig"].get(key)]
|
||||
if mode != actual_mode:
|
||||
result["currentNetworkMode"] = actual_mode
|
||||
result["matchingSavedNetworkMode"] = mode
|
||||
return result
|
||||
return result
|
||||
|
||||
|
||||
def device_release_drift_sample():
|
||||
inventory = device_plane_runtime_inventory(DEVICE_RELEASE_INVENTORY)
|
||||
if set(device_plane_inventory_service_names(inventory)) != set(DEVICE_RELEASE_INVENTORY):
|
||||
die("Device Core drift audit requires the exact five-service inventory")
|
||||
samples = {}
|
||||
for row in inventory["services"]:
|
||||
fields = device_release_drift_fields(inspect_device_plane_container(row["containerId"]))
|
||||
row["runtimeConfigSha256"] = device_release_drift_digest(fields)
|
||||
samples[row["service"]] = {"runtime": row, "fields": fields}
|
||||
return samples
|
||||
|
||||
|
||||
def device_release_drift_audit(payload, entries, patch_id):
|
||||
validate_device_release_drift_audit_payload(payload, entries, patch_id)
|
||||
before = device_release_r5_evidence()
|
||||
report = {"schemaVersion": "nodedc.device-core.runtime-drift-report.v1",
|
||||
"mutation": False, "applyAllowed": False, "failedReleaseId": DEVICE_RELEASE_R5_ID,
|
||||
"incidentEvidenceExact": True, "checks": {}, "services": {}}
|
||||
|
||||
def check(name, operation):
|
||||
try:
|
||||
value = operation()
|
||||
report["checks"][name] = {"ok": value is not False}
|
||||
except Exception as exc:
|
||||
# Never emit raw inspect, environment/secret values, or exception text.
|
||||
report["checks"][name] = {"ok": False, "errorType": type(exc).__name__}
|
||||
|
||||
check("source", lambda: collect_exact_files(DEVICE_PLANE_ROOT, DEVICE_RELEASE_ENTRIES[:-1], "Device Core drift source") == before["installedFiles"])
|
||||
check("noOrphanRelease", lambda: not (DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY).exists() and not (DEVICE_PLANE_ROOT / DEVICE_RELEASE_ENTRY).is_symlink())
|
||||
check("compose", lambda: {str(p): sha256_file(p) for p in component_compose_files("device-plane")} == before["compose"])
|
||||
check("health", lambda: run_healthchecks("device-core-release", DEVICE_RELEASE_ENTRIES, DEVICE_RELEASE_SERVICES))
|
||||
check("runtimeBoundaries", lambda: validate_device_manager_control_plane_runtime(require_edge_channel=True, core_network_mode="private-egress", require_persistent_data=True, read_only=True))
|
||||
check("otherComposeServices", lambda: device_release_other_compose_services() == before["otherComposeServices"])
|
||||
observations = [device_release_drift_sample() for _ in range(3)]
|
||||
for service in DEVICE_RELEASE_INVENTORY:
|
||||
saved = before["runtime"][service]
|
||||
samples = [observation[service] for observation in observations]
|
||||
row = samples[0]["runtime"]
|
||||
fields = samples[0]["fields"]
|
||||
proof = device_release_drift_probe(fields, saved["runtimeConfigSha256"])
|
||||
proof.update({"expectedImageId": saved["imageId"], "actualImageId": row["imageId"],
|
||||
"imageMatches": row["imageId"] == saved["imageId"],
|
||||
"samplesStable": all(sample == samples[0] for sample in samples),
|
||||
"sampleCount": len(samples),
|
||||
"sampleSha256": [sample["runtime"]["runtimeConfigSha256"] for sample in samples],
|
||||
"healthReady": all(sample["runtime"]["running"] and sample["runtime"]["health"] in (None, "healthy") for sample in samples),
|
||||
"preservedServiceExact": row == saved if service not in DEVICE_RELEASE_SERVICES else None,
|
||||
"mountCounts": {key: len(fields["HostConfig"].get(key) or []) for key in ("Binds", "Mounts")},
|
||||
"fieldSha256": {section: {key: device_release_drift_digest(value) for key, value in fields[section].items()}
|
||||
for section in ("HostConfig", "Config")}})
|
||||
report["services"][service] = proof
|
||||
print("device_release_drift_audit=" + json.dumps(report, sort_keys=True, separators=(",", ":")))
|
||||
print("device_release_drift_audit_result=diagnostic-only;apply=forbidden;acceptance-barriers=unchanged")
|
||||
return report
|
||||
|
||||
|
||||
def preflight_device_release(payload, entries, patch_id):
|
||||
d = validate_device_release_payload(payload, entries, patch_id)
|
||||
predecessor = device_release_predecessor(d)
|
||||
@@ -32742,6 +32911,9 @@ def plan_artifact(artifact):
|
||||
gitea_salvage_preflight = None
|
||||
with tempfile.TemporaryDirectory(prefix="plan-", dir=TMP_DIR) as tmp:
|
||||
manifest, entries, payload_dir = load_artifact(artifact, Path(tmp))
|
||||
if manifest["component"] == "device-core-release-drift-audit":
|
||||
device_release_drift_audit(payload_dir, entries, manifest["id"])
|
||||
return
|
||||
if manifest["component"] == "device-core-release-reconciliation":
|
||||
preflight_device_release_reconciliation(payload_dir, entries, manifest["id"])
|
||||
if manifest["component"] == "device-core-release":
|
||||
@@ -40040,6 +40212,8 @@ def apply_artifact(artifact):
|
||||
with tempfile.TemporaryDirectory(prefix=f"apply-{current_stamp}-", dir=TMP_DIR) as tmp:
|
||||
work = Path(tmp)
|
||||
manifest, entries, payload_dir = load_artifact(artifact, work)
|
||||
if manifest["component"] == "device-core-release-drift-audit":
|
||||
die("Device Core drift audit is plan-only; apply is forbidden")
|
||||
if is_gitea_fresh_install_slice(
|
||||
manifest["component"],
|
||||
entries,
|
||||
|
||||
Reference in New Issue
Block a user