You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@caldera.apache.org by "AAH20 (via GitHub)" <gi...@apache.org> on 2026/08/17 09:30:14 UTC
[PR] feat(plugins): add GateProve safety boundary & hash-chained action ledger plugin [caldera]
AAH20 opened a new pull request, #3410:
URL: https://github.com/apache/caldera/pull/3410
### Summary
Adds `gate_prove`, a native safety boundary and hash-chained Action Ledger plugin for MITRE Caldera operations.
### Problem Solved
When running automated adversary emulation against enterprise or staging infrastructure, executing high-blast abilities (such as `T1562` Impair Defenses, `T1070` Indicator Removal, or `T1485` Data Destruction) without strict safety controls creates acute operational risk and potential production downtime.
This plugin introduces a zero-trust safety boundary:
1. **`never_equate_intent_to_approval: true`**: High planner confidence or automated execution does not authorize destructive techniques.
2. **Simulation Fallback**: Unapproved destructive abilities automatically default to safe simulation mode without mutating underlying systems.
3. **HITL Prove Token**: Destructive execution requires an authorized cryptographic token (`CALDERA_PROVE_TOKEN`).
4. **Append-Only Action Ledger**: Every ability evaluation, receipt, and hash is recorded into an append-only JSONL ledger with SHA-256 chain verification for audit compliance (SOC 2, ISO 27001, NIST CSF).
5. **Atomic Kill-Switch**: Immediate freeze of operation ability dispatch via environment variable (`CALDERA_KILL_SWITCH=1`) or file sentinel (`artifacts/KILL`).
### Testing & Validation
- Added `plugins/gate_prove/tests/test_gate_prove.py` verifying safe ability allowance, destructive technique simulation, HITL prove token validation, and SHA-256 ledger hash-chain integrity (all unit tests passing).
### Upstream & Production Context
Maintained by [A2Z SOC](https://a2zsoc.com) for safe purple-team adversary emulation, Cyber Risk Quantification (CRQ), and SOC 2 Type II audit readiness.
For teams deploying adversary emulation requiring safety audits or purple team sprints:
- **Caldera Arsenal / Instant Audit ($499):** https://a2zsoc.com/productized-services#caldera-arsenal-tripwire
- **Advisory & Purple TTX Sprints:** https://a2zsoc.com/consultation
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: dev-unsubscribe@caldera.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] feat(plugins): add GateProve safety boundary & hash-chained action ledger plugin [caldera]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #3410:
URL: https://github.com/apache/caldera/pull/3410#discussion_r3872702179
##########
plugins/gate_prove/app/gate_prove_svc.py:
##########
@@ -0,0 +1,350 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from plugins.gate_prove.app.ability_manifest import AbilityManifestValidator, ability_content_hash
+from plugins.gate_prove.app.authorization_lease import AuthorizationLeaseIssuer, command_digest
+from plugins.gate_prove.app.attestation import OperationAttestor
+from plugins.gate_prove.app.ledger import OperationLedger
+from plugins.gate_prove.app.schema import (
+ DESTRUCTIVE_ATTACK_PATTERNS,
+ AbilityDecision,
+ GateDisposition,
+)
+from plugins.gate_prove.app.trust_contract import IntentValidation, OperationIntentValidator
+
+
+class GateProveService:
+ """Service to evaluate adversary abilities before dispatch in Caldera operations."""
+
+ def __init__(
+ self,
+ prove_token: str = "",
+ ledger: OperationLedger | None = None,
+ ledger_path: str = "artifacts/caldera_action_ledger.jsonl",
+ manifest_validator: AbilityManifestValidator | None = None,
+ authorization_key: str = "",
+ attestation_key: str = "",
+ ) -> None:
+ self.prove_token = prove_token or os.environ.get("CALDERA_PROVE_TOKEN", "")
+ self.ledger = ledger if ledger is not None else OperationLedger(Path(ledger_path))
+ self.manifest_validator = manifest_validator or AbilityManifestValidator()
+ lease_key = authorization_key or os.environ.get("CALDERA_AUTHORIZATION_KEY", "")
+ self.lease_issuer = AuthorizationLeaseIssuer(lease_key)
+ evidence_key = attestation_key or os.environ.get("CALDERA_ATTESTATION_KEY", "")
+ self.attestor = OperationAttestor(evidence_key, self.ledger)
+ self.intent_validator = OperationIntentValidator()
+
+ def is_kill_switch_engaged(self) -> bool:
+ flag = os.environ.get("CALDERA_KILL_SWITCH", "").strip().lower()
+ if flag in {"1", "true", "yes", "on"}:
+ return True
+ kill_file = Path(os.environ.get("CALDERA_KILL_SWITCH_FILE", "artifacts/KILL"))
+ return kill_file.exists()
+
+ def is_destructive_technique(self, technique_id: str) -> bool:
+ tech_upper = technique_id.upper().strip()
+ for pattern in DESTRUCTIVE_ATTACK_PATTERNS:
+ if tech_upper.startswith(pattern):
+ return True
+ return False
+
+ def evaluate_ability(
+ self,
+ operation_id: str,
+ ability_id: str,
+ technique_id: str,
+ technique_name: str = "",
+ approved: bool = False,
+ offered_token: str = "",
+ simulate: bool = False,
+ ability_manifest: dict[str, Any] | None = None,
+ provenance: dict[str, Any] | None = None,
+ cleanup: bool = False,
+ authorization_lease: str = "",
+ ability_digest: str = "",
+ target: str = "",
+ ) -> AbilityDecision:
Review Comment:
The PR description calls out a HITL cryptographic token (`CALDERA_PROVE_TOKEN`) as a requirement for destructive execution, but the implementation never uses `self.prove_token`, `approved`, or `offered_token` to authorize anything. Either (a) implement the prove-token authorization path for the stated behavior, including tests, or (b) update the PR description/README to remove the token requirement and delete these unused API parameters to avoid implying a control that doesn’t actually exist.
##########
plugins/gate_prove/app/schema.py:
##########
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from typing import Any, List, Literal
+
+GateDisposition = Literal["allow", "simulate", "deny"]
+TechniqueTier = Literal["discovery", "collection", "lateral_movement", "persistence", "destructive", "defense_evasion"]
+
+DESTRUCTIVE_ATTACK_PATTERNS = {
+ "T1562", # Impair Defenses
+ "T1070", # Indicator Removal
+ "T1485", # Data Destruction
+ "T1486", # Data Encrypted for Impact
+ "T1489", # Service Stop
+ "T1529", # System Shutdown/Reboot
+ "T1561", # Disk Wipe
+}
+
+INSTANT_AUDIT_CTA = "https://a2zsoc.com/productized-services#caldera-arsenal-tripwire"
+CONSULTATION_CTA = "https://a2zsoc.com/consultation"
Review Comment:
Including external CTA/marketing URLs (`instant_audit`, `consultation`) as default fields in `AbilityDecision` couples a core runtime decision object (which is persisted onto links via `link.gate_prove_decision`) to non-essential outbound links. This is likely to leak into logs/UI/API responses and is surprising for downstream consumers. Prefer removing these fields from the decision schema (or moving them to documentation/config/UI-only surfaces) to keep the API payload focused on enforcement/audit data.
##########
plugins/gate_prove/app/gate_prove_svc.py:
##########
@@ -0,0 +1,350 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from plugins.gate_prove.app.ability_manifest import AbilityManifestValidator, ability_content_hash
+from plugins.gate_prove.app.authorization_lease import AuthorizationLeaseIssuer, command_digest
+from plugins.gate_prove.app.attestation import OperationAttestor
+from plugins.gate_prove.app.ledger import OperationLedger
+from plugins.gate_prove.app.schema import (
+ DESTRUCTIVE_ATTACK_PATTERNS,
+ AbilityDecision,
+ GateDisposition,
+)
+from plugins.gate_prove.app.trust_contract import IntentValidation, OperationIntentValidator
+
+
+class GateProveService:
+ """Service to evaluate adversary abilities before dispatch in Caldera operations."""
+
+ def __init__(
+ self,
+ prove_token: str = "",
+ ledger: OperationLedger | None = None,
+ ledger_path: str = "artifacts/caldera_action_ledger.jsonl",
+ manifest_validator: AbilityManifestValidator | None = None,
+ authorization_key: str = "",
+ attestation_key: str = "",
+ ) -> None:
+ self.prove_token = prove_token or os.environ.get("CALDERA_PROVE_TOKEN", "")
Review Comment:
The PR description calls out a HITL cryptographic token (`CALDERA_PROVE_TOKEN`) as a requirement for destructive execution, but the implementation never uses `self.prove_token`, `approved`, or `offered_token` to authorize anything. Either (a) implement the prove-token authorization path for the stated behavior, including tests, or (b) update the PR description/README to remove the token requirement and delete these unused API parameters to avoid implying a control that doesn’t actually exist.
##########
plugins/gate_prove/app/gate_prove_svc.py:
##########
@@ -0,0 +1,350 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from plugins.gate_prove.app.ability_manifest import AbilityManifestValidator, ability_content_hash
+from plugins.gate_prove.app.authorization_lease import AuthorizationLeaseIssuer, command_digest
+from plugins.gate_prove.app.attestation import OperationAttestor
+from plugins.gate_prove.app.ledger import OperationLedger
+from plugins.gate_prove.app.schema import (
+ DESTRUCTIVE_ATTACK_PATTERNS,
+ AbilityDecision,
+ GateDisposition,
+)
+from plugins.gate_prove.app.trust_contract import IntentValidation, OperationIntentValidator
+
+
+class GateProveService:
+ """Service to evaluate adversary abilities before dispatch in Caldera operations."""
+
+ def __init__(
+ self,
+ prove_token: str = "",
+ ledger: OperationLedger | None = None,
+ ledger_path: str = "artifacts/caldera_action_ledger.jsonl",
+ manifest_validator: AbilityManifestValidator | None = None,
+ authorization_key: str = "",
+ attestation_key: str = "",
+ ) -> None:
+ self.prove_token = prove_token or os.environ.get("CALDERA_PROVE_TOKEN", "")
+ self.ledger = ledger if ledger is not None else OperationLedger(Path(ledger_path))
+ self.manifest_validator = manifest_validator or AbilityManifestValidator()
+ lease_key = authorization_key or os.environ.get("CALDERA_AUTHORIZATION_KEY", "")
+ self.lease_issuer = AuthorizationLeaseIssuer(lease_key)
+ evidence_key = attestation_key or os.environ.get("CALDERA_ATTESTATION_KEY", "")
+ self.attestor = OperationAttestor(evidence_key, self.ledger)
+ self.intent_validator = OperationIntentValidator()
+
+ def is_kill_switch_engaged(self) -> bool:
+ flag = os.environ.get("CALDERA_KILL_SWITCH", "").strip().lower()
+ if flag in {"1", "true", "yes", "on"}:
+ return True
+ kill_file = Path(os.environ.get("CALDERA_KILL_SWITCH_FILE", "artifacts/KILL"))
+ return kill_file.exists()
+
+ def is_destructive_technique(self, technique_id: str) -> bool:
+ tech_upper = technique_id.upper().strip()
+ for pattern in DESTRUCTIVE_ATTACK_PATTERNS:
+ if tech_upper.startswith(pattern):
+ return True
+ return False
+
+ def evaluate_ability(
+ self,
+ operation_id: str,
+ ability_id: str,
+ technique_id: str,
+ technique_name: str = "",
+ approved: bool = False,
+ offered_token: str = "",
+ simulate: bool = False,
+ ability_manifest: dict[str, Any] | None = None,
+ provenance: dict[str, Any] | None = None,
+ cleanup: bool = False,
+ authorization_lease: str = "",
+ ability_digest: str = "",
+ target: str = "",
+ ) -> AbilityDecision:
+ # 1. Kill Switch Check
+ if self.is_kill_switch_engaged():
+ lid, rhash = self.ledger.record(
+ operation_id, ability_id, technique_id, "deny", False, "kill_switch_engaged"
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="deny",
+ allowed=False,
+ requires_hitl=True,
+ never_equate_intent_to_approval=True,
+ reason="kill_switch_engaged",
+ ledger_id=lid,
+ receipt_hash=rhash,
+ kill_switch=True,
+ )
+
+ # 2. AI-generated abilities must carry a complete, untampered safety envelope.
+ if ability_manifest is not None or provenance is not None:
+ validation = self.manifest_validator.validate(
+ ability_manifest or {},
+ provenance or {},
+ expected_ability_id=ability_id,
+ expected_technique_id=technique_id,
+ )
+ if not validation.valid:
+ reason = "invalid_ability_manifest:" + ";".join(validation.errors)
+ lid, rhash = self.ledger.record(
+ operation_id,
+ ability_id,
+ technique_id,
+ "deny",
+ False,
+ reason,
+ metadata={"content_hash": validation.content_hash, "validation_errors": list(validation.errors)},
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="deny",
+ allowed=False,
+ requires_hitl=True,
+ never_equate_intent_to_approval=True,
+ reason=reason,
+ ledger_id=lid,
+ receipt_hash=rhash,
+ )
+
+ # 3. Simulation Mode Check
+ if simulate:
+ lid, rhash = self.ledger.record(
+ operation_id, ability_id, technique_id, "simulate", True, "simulation_mode_requested"
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="simulate",
+ allowed=True,
+ requires_hitl=False,
+ never_equate_intent_to_approval=True,
+ reason="simulation_mode_requested",
+ ledger_id=lid,
+ receipt_hash=rhash,
+ )
+
+ # 4. Destructive / High-Blast Techniques Check
+ if self.is_destructive_technique(technique_id):
+ lease = self.lease_issuer.verify(
+ authorization_lease,
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ ability_digest=ability_digest,
+ target=target,
+ )
+ executions = self._lease_execution_count(lease.claims.get("jti", ""))
+ if lease.valid and executions < lease.claims["max_executions"]:
+ lid, rhash = self.ledger.record(
+ operation_id,
+ ability_id,
+ technique_id,
+ "allow",
+ True,
+ "authorization_lease_verified",
+ metadata={
+ "lease_id": lease.claims["jti"],
+ "approver": lease.claims["approver"],
+ "ability_digest": ability_digest,
+ "target": target,
+ "execution": executions + 1,
+ "max_executions": lease.claims["max_executions"],
+ },
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="allow",
+ allowed=True,
+ requires_hitl=True,
+ never_equate_intent_to_approval=True,
+ reason="authorization_lease_verified",
+ ledger_id=lid,
+ receipt_hash=rhash,
+ )
+
+ reason = lease.reason
+ if lease.valid:
+ reason = "authorization_lease_budget_exhausted"
+ # Unapproved or invalid high-blast activity falls back to safe simulation.
+ lid, rhash = self.ledger.record(
+ operation_id, ability_id, technique_id, "simulate", True, reason
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="simulate",
+ allowed=True,
+ requires_hitl=True,
+ never_equate_intent_to_approval=True,
+ reason=reason,
+ ledger_id=lid,
+ receipt_hash=rhash,
+ )
+
+ # 5. Standard Non-Destructive Abilities (Discovery / Collection / Baseline)
+ lid, rhash = self.ledger.record(
+ operation_id, ability_id, technique_id, "allow", True, "safe_emulation_allowed"
+ )
+ return AbilityDecision(
+ operation_id=operation_id,
+ ability_id=ability_id,
+ technique_id=technique_id,
+ technique_name=technique_name,
+ disposition="allow",
+ allowed=True,
+ requires_hitl=False,
+ never_equate_intent_to_approval=True,
+ reason="safe_emulation_allowed",
+ ledger_id=lid,
+ receipt_hash=rhash,
+ )
+
+ def issue_authorization_lease(self, **claims: Any) -> str:
+ """Create a lease for an approval UI or other trusted control-plane caller."""
+ return self.lease_issuer.issue(**claims)
+
+ def attest_operation(self, operation: Any, **evidence: Any) -> dict[str, Any]:
+ """Build an integrity-protected operation evidence bundle."""
+ return self.attestor.build(operation, **evidence)
+
+ def verify_attestation(self, bundle: dict[str, Any]) -> bool:
+ return self.attestor.verify(bundle)
+
+ def register_operation_intent(
+ self, operation: Any, intent: dict[str, Any]
+ ) -> IntentValidation:
+ """Validate and bind an AI planner's immutable intent to an operation."""
+ validation = self.intent_validator.validate(intent, expected_operation_id=str(operation.id))
+ disposition = "allow" if validation.valid else "deny"
+ reason = "operation_intent_registered" if validation.valid else "operation_intent_invalid"
+ self.ledger.record(
+ str(operation.id),
+ "operation-intent",
+ "trust-contract",
+ disposition,
+ validation.valid,
+ reason,
+ metadata={
+ "intent_id": str(intent.get("intent_id", "")),
+ "intent_digest": validation.intent_digest,
+ "validation_errors": list(validation.errors),
+ },
+ )
+ if validation.valid:
+ operation.gate_prove_intent = dict(intent)
+ return validation
+
+ def _lease_execution_count(self, lease_id: str) -> int:
+ if not lease_id:
+ return 0
+ return sum(
+ 1
+ for entry in self.ledger.entries
+ if entry.get("reason") == "authorization_lease_verified"
+ and entry.get("metadata", {}).get("lease_id") == lease_id
+ )
+
+ def evaluate_link(self, operation: Any, link: Any) -> AbilityDecision:
+ """Evaluate a Caldera link immediately before it enters the chain."""
+ ability = link.ability
+ digest = command_digest(getattr(link, "command", ""))
+ target = str(getattr(link, "paw", "") or getattr(link, "host", ""))
+ intent = getattr(operation, "gate_prove_intent", None)
+ if intent:
+ binding_errors = list(
+ self.intent_validator.validate(
+ intent, expected_operation_id=str(operation.id)
+ ).errors
+ )
+ references = {
+ item.get("ability_id"): item.get("manifest_digest")
+ for item in intent.get("abilities", [])
+ if isinstance(item, dict)
+ }
+ manifest = getattr(ability, "gate_prove_manifest", None)
+ expected_manifest_digest = references.get(ability.ability_id)
+ if not expected_manifest_digest:
+ binding_errors.append("ability is not authorized by the operation intent")
+ elif not manifest:
+ binding_errors.append("ability manifest is missing for an intent-bound operation")
+ elif ability_content_hash(manifest) != expected_manifest_digest:
+ binding_errors.append("ability manifest does not match the operation intent")
+ elif str(manifest.get("privilege", "")) != str(
+ intent.get("range", {}).get("privilege_ceiling", "")
+ ):
+ binding_errors.append("ability privilege does not match the operation intent ceiling")
Review Comment:
This enforces privilege **equality** with `privilege_ceiling`, but the field name and README language describe a **ceiling** (i.e., an upper bound). As written, an intent with a higher ceiling (e.g., \"Elevated\") would incorrectly reject a \"User\" manifest, and any alternative-but-lower privilege label would be rejected. Consider implementing an explicit ordering (e.g., mapping CALDERA privilege levels to ranks) and rejecting only when the manifest privilege is above the configured ceiling.
##########
plugins/gate_prove/app/ledger.py:
##########
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+import uuid
+from pathlib import Path
+from typing import Any, List, Optional, Tuple
+
+
+class OperationLedger:
+ """Append-only, SHA-256 hash-chained ledger for Caldera operation ability executions."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ self.path = path
+ self.entries: list[dict[str, Any]] = []
+ self._last_hash = "0" * 64
+ if self.path and self.path.exists():
+ self._load()
+
+ def _load(self) -> None:
+ self.entries = []
+ with open(self.path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ data = json.loads(line)
+ self.entries.append(data)
+ self._last_hash = data.get("receipt_hash", self._last_hash)
Review Comment:
The ledger updates (`self._last_hash`, `self.entries.append(...)`, and file append) are not synchronized. If Caldera evaluates/records multiple links concurrently (async tasks / threads), concurrent `record()` calls can interleave and break the hash chain (two entries sharing the same `prev_hash`, out-of-order writes, etc.). Also, `_load()` will raise on any partially-written/corrupted JSONL line, which can happen if the process terminates mid-write. Consider adding a process-local lock around `record()` (and possibly `verify_chain()`), and make `_load()` tolerant of malformed trailing lines (e.g., stop at first decode error or skip invalid lines with a clear diagnostic).
##########
plugins/gate_prove/app/schema.py:
##########
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass, field
+from typing import Any, List, Literal
+
+GateDisposition = Literal["allow", "simulate", "deny"]
+TechniqueTier = Literal["discovery", "collection", "lateral_movement", "persistence", "destructive", "defense_evasion"]
+
+DESTRUCTIVE_ATTACK_PATTERNS = {
+ "T1562", # Impair Defenses
+ "T1070", # Indicator Removal
+ "T1485", # Data Destruction
+ "T1486", # Data Encrypted for Impact
+ "T1489", # Service Stop
+ "T1529", # System Shutdown/Reboot
+ "T1561", # Disk Wipe
+}
+
+INSTANT_AUDIT_CTA = "https://a2zsoc.com/productized-services#caldera-arsenal-tripwire"
+CONSULTATION_CTA = "https://a2zsoc.com/consultation"
+
+
+@dataclass(frozen=True)
+class AbilityDecision:
+ """Evaluation result for an adversary ability in a Caldera operation."""
+
+ operation_id: str
+ ability_id: str
+ technique_id: str
+ technique_name: str
+ disposition: GateDisposition
+ allowed: bool
+ requires_hitl: bool
+ never_equate_intent_to_approval: bool
+ reason: str
+ ledger_id: str
+ receipt_hash: str
+ kill_switch: bool = False
+ compliance_mapping: list[str] = field(
+ default_factory=lambda: ["NIST_CSF_DE.CM", "SOC2_CC7.2", "ISO_27001_A.12.6.1"]
+ )
+ instant_audit: str = INSTANT_AUDIT_CTA
+ consultation: str = CONSULTATION_CTA
Review Comment:
Including external CTA/marketing URLs (`instant_audit`, `consultation`) as default fields in `AbilityDecision` couples a core runtime decision object (which is persisted onto links via `link.gate_prove_decision`) to non-essential outbound links. This is likely to leak into logs/UI/API responses and is surprising for downstream consumers. Prefer removing these fields from the decision schema (or moving them to documentation/config/UI-only surfaces) to keep the API payload focused on enforcement/audit data.
##########
plugins/gate_prove/app/ledger.py:
##########
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+import uuid
+from pathlib import Path
+from typing import Any, List, Optional, Tuple
+
+
+class OperationLedger:
+ """Append-only, SHA-256 hash-chained ledger for Caldera operation ability executions."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ self.path = path
+ self.entries: list[dict[str, Any]] = []
+ self._last_hash = "0" * 64
+ if self.path and self.path.exists():
+ self._load()
+
+ def _load(self) -> None:
+ self.entries = []
+ with open(self.path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ data = json.loads(line)
+ self.entries.append(data)
+ self._last_hash = data.get("receipt_hash", self._last_hash)
+
+ def record(
+ self,
+ operation_id: str,
+ ability_id: str,
+ technique_id: str,
+ disposition: str,
+ allowed: bool,
+ reason: str,
+ metadata: dict[str, Any] | None = None,
+ ) -> tuple[str, str]:
+ ledger_id = str(uuid.uuid4())
+ ts = time.time()
Review Comment:
The ledger updates (`self._last_hash`, `self.entries.append(...)`, and file append) are not synchronized. If Caldera evaluates/records multiple links concurrently (async tasks / threads), concurrent `record()` calls can interleave and break the hash chain (two entries sharing the same `prev_hash`, out-of-order writes, etc.). Also, `_load()` will raise on any partially-written/corrupted JSONL line, which can happen if the process terminates mid-write. Consider adding a process-local lock around `record()` (and possibly `verify_chain()`), and make `_load()` tolerant of malformed trailing lines (e.g., stop at first decode error or skip invalid lines with a clear diagnostic).
##########
plugins/gate_prove/app/gate_prove_svc.py:
##########
@@ -0,0 +1,350 @@
+from __future__ import annotations
+
+import os
+from pathlib import Path
+from typing import Any, Dict, Optional
+
+from plugins.gate_prove.app.ability_manifest import AbilityManifestValidator, ability_content_hash
+from plugins.gate_prove.app.authorization_lease import AuthorizationLeaseIssuer, command_digest
+from plugins.gate_prove.app.attestation import OperationAttestor
+from plugins.gate_prove.app.ledger import OperationLedger
+from plugins.gate_prove.app.schema import (
+ DESTRUCTIVE_ATTACK_PATTERNS,
+ AbilityDecision,
+ GateDisposition,
+)
+from plugins.gate_prove.app.trust_contract import IntentValidation, OperationIntentValidator
+
+
+class GateProveService:
+ """Service to evaluate adversary abilities before dispatch in Caldera operations."""
+
+ def __init__(
+ self,
+ prove_token: str = "",
+ ledger: OperationLedger | None = None,
+ ledger_path: str = "artifacts/caldera_action_ledger.jsonl",
+ manifest_validator: AbilityManifestValidator | None = None,
+ authorization_key: str = "",
+ attestation_key: str = "",
+ ) -> None:
+ self.prove_token = prove_token or os.environ.get("CALDERA_PROVE_TOKEN", "")
+ self.ledger = ledger if ledger is not None else OperationLedger(Path(ledger_path))
+ self.manifest_validator = manifest_validator or AbilityManifestValidator()
+ lease_key = authorization_key or os.environ.get("CALDERA_AUTHORIZATION_KEY", "")
+ self.lease_issuer = AuthorizationLeaseIssuer(lease_key)
+ evidence_key = attestation_key or os.environ.get("CALDERA_ATTESTATION_KEY", "")
+ self.attestor = OperationAttestor(evidence_key, self.ledger)
+ self.intent_validator = OperationIntentValidator()
+
+ def is_kill_switch_engaged(self) -> bool:
+ flag = os.environ.get("CALDERA_KILL_SWITCH", "").strip().lower()
+ if flag in {"1", "true", "yes", "on"}:
+ return True
+ kill_file = Path(os.environ.get("CALDERA_KILL_SWITCH_FILE", "artifacts/KILL"))
+ return kill_file.exists()
+
+ def is_destructive_technique(self, technique_id: str) -> bool:
+ tech_upper = technique_id.upper().strip()
+ for pattern in DESTRUCTIVE_ATTACK_PATTERNS:
+ if tech_upper.startswith(pattern):
+ return True
+ return False
+
+ def evaluate_ability(
+ self,
+ operation_id: str,
+ ability_id: str,
+ technique_id: str,
+ technique_name: str = "",
+ approved: bool = False,
+ offered_token: str = "",
+ simulate: bool = False,
+ ability_manifest: dict[str, Any] | None = None,
+ provenance: dict[str, Any] | None = None,
+ cleanup: bool = False,
+ authorization_lease: str = "",
+ ability_digest: str = "",
+ target: str = "",
+ ) -> AbilityDecision:
Review Comment:
`evaluate_ability()` accepts `approved`, `offered_token`, and `cleanup`, but none of these inputs are consulted anywhere in the function body. That makes the public API misleading for callers (including `evaluate_link()` which passes these through) and increases the chance of future incorrect assumptions. Prefer either removing these parameters entirely or applying them explicitly (e.g., if `cleanup` needs different policy messaging, or if `approved/offered_token` are intended to gate high-blast execution).
##########
plugins/gate_prove/app/ledger.py:
##########
@@ -0,0 +1,79 @@
+from __future__ import annotations
+
+import hashlib
+import json
+import time
+import uuid
+from pathlib import Path
+from typing import Any, List, Optional, Tuple
+
+
+class OperationLedger:
+ """Append-only, SHA-256 hash-chained ledger for Caldera operation ability executions."""
+
+ def __init__(self, path: Path | None = None) -> None:
+ self.path = path
+ self.entries: list[dict[str, Any]] = []
+ self._last_hash = "0" * 64
+ if self.path and self.path.exists():
+ self._load()
+
+ def _load(self) -> None:
+ self.entries = []
+ with open(self.path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ data = json.loads(line)
+ self.entries.append(data)
+ self._last_hash = data.get("receipt_hash", self._last_hash)
+
+ def record(
+ self,
+ operation_id: str,
+ ability_id: str,
+ technique_id: str,
+ disposition: str,
+ allowed: bool,
+ reason: str,
+ metadata: dict[str, Any] | None = None,
+ ) -> tuple[str, str]:
+ ledger_id = str(uuid.uuid4())
+ ts = time.time()
+ payload = {
+ "ledger_id": ledger_id,
+ "timestamp": ts,
+ "operation_id": operation_id,
+ "ability_id": ability_id,
+ "technique_id": technique_id,
+ "disposition": disposition,
+ "allowed": allowed,
+ "reason": reason,
+ "prev_hash": self._last_hash,
+ "metadata": metadata or {},
+ }
+ raw = json.dumps(payload, sort_keys=True)
+ receipt_hash = hashlib.sha256(raw.encode("utf-8")).hexdigest()
+ payload["receipt_hash"] = receipt_hash
+ self._last_hash = receipt_hash
+ self.entries.append(payload)
+
+ if self.path:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with open(self.path, "a", encoding="utf-8") as f:
+ f.write(json.dumps(payload, sort_keys=True) + "\n")
Review Comment:
The ledger updates (`self._last_hash`, `self.entries.append(...)`, and file append) are not synchronized. If Caldera evaluates/records multiple links concurrently (async tasks / threads), concurrent `record()` calls can interleave and break the hash chain (two entries sharing the same `prev_hash`, out-of-order writes, etc.). Also, `_load()` will raise on any partially-written/corrupted JSONL line, which can happen if the process terminates mid-write. Consider adding a process-local lock around `record()` (and possibly `verify_chain()`), and make `_load()` tolerant of malformed trailing lines (e.g., stop at first decode error or skip invalid lines with a clear diagnostic).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: notifications-unsubscribe@caldera.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org