feat(p5): add reject-only event recovery boundary
这个提交存在于:
父节点
bd188f7056
当前提交
f6babf2c1e
共有 3 个文件被更改,包括 245 次插入 和 0 次删除
|
|
@ -843,6 +843,15 @@
|
|||
"enable_p5c_portable_export_gate": {"description": "Gate portable export creation", "type": "bool", "default": false}
|
||||
}
|
||||
},
|
||||
"p5d_safety": {
|
||||
"description": "P5-D reject-only security-event boundaries",
|
||||
"hint": "Each operation is default-off. This repository has no Companion-issued cross-turn projection or host-verified owner capability, so enabling either operation returns only a controlled denial.",
|
||||
"type": "object",
|
||||
"items": {
|
||||
"enable_p5d_cross_turn_correlation": {"description": "Reject-only gate for cross-turn security-event correlation", "type": "bool", "default": false},
|
||||
"enable_p5d_manual_recovery": {"description": "Reject-only gate for manual recovery", "type": "bool", "default": false}
|
||||
}
|
||||
},
|
||||
"maintenance": {
|
||||
"description": "维护",
|
||||
"hint": "控制数据保留和清理策略。",
|
||||
|
|
|
|||
136
core/p5d_security_events.py
普通文件
136
core/p5d_security_events.py
普通文件
|
|
@ -0,0 +1,136 @@
|
|||
"""P5-D default-off, reject-only security-event consumer boundary.
|
||||
|
||||
Memory has no Companion-issued cross-turn projection or host-verified owner
|
||||
capability contract. This module therefore intentionally does not correlate,
|
||||
persist, recover, or authorize anything. When either P5-D operation is
|
||||
enabled, the only possible outcome is a stable controlled denial. Caller
|
||||
objects are opaque and cannot become a grant.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
logger = logging.getLogger("MemoryCompanion.P5D")
|
||||
|
||||
CROSS_TURN_CORRELATION_OPERATION = "cross_turn_correlation"
|
||||
MANUAL_RECOVERY_OPERATION = "manual_recovery"
|
||||
|
||||
P5D_CONFIG_MODULE = "p5d_safety"
|
||||
P5D_OPERATION_FLAGS = {
|
||||
CROSS_TURN_CORRELATION_OPERATION: "enable_p5d_cross_turn_correlation",
|
||||
MANUAL_RECOVERY_OPERATION: "enable_p5d_manual_recovery",
|
||||
}
|
||||
P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE = "p5d_host_owner_capability_unavailable"
|
||||
|
||||
|
||||
class P5DControlledDeny(ValueError):
|
||||
"""A stable, content-free P5-D deny for future bounded integrations."""
|
||||
|
||||
def __init__(self, operation: str, reason_code: str) -> None:
|
||||
self.operation = operation
|
||||
self.reason_code = reason_code
|
||||
super().__init__(reason_code)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class P5DSecurityEventDecision:
|
||||
allowed: bool
|
||||
operation: str
|
||||
reason_code: str
|
||||
audit: dict[str, str]
|
||||
|
||||
|
||||
def _bool(config: Any, flag: str) -> bool:
|
||||
"""Read flat or schema-path config without treating a missing config as enabled."""
|
||||
|
||||
getter = getattr(config, "bool", None)
|
||||
if not callable(getter):
|
||||
return False
|
||||
try:
|
||||
if bool(getter(flag, False)):
|
||||
return True
|
||||
return bool(getter(f"{P5D_CONFIG_MODULE}.{flag}", False))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _audit(operation: str, outcome: str, reason_code: str) -> dict[str, str]:
|
||||
# The ref is derived only from a static operation label. Never include
|
||||
# event/request/session/scope data, owner text, or caller-provided objects.
|
||||
return {
|
||||
"operation": operation,
|
||||
"outcome": outcome,
|
||||
"reason_code": reason_code,
|
||||
"ref_hash": hashlib.sha256(f"p5d:{operation}".encode("utf-8")).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def check_p5d_security_event_operation(
|
||||
config: Any,
|
||||
operation: str,
|
||||
*,
|
||||
issuer: Any = None,
|
||||
principal: Any = None,
|
||||
capability: Any = None,
|
||||
) -> P5DSecurityEventDecision:
|
||||
"""Evaluate a P5-D operation without accepting caller-provided authority.
|
||||
|
||||
A verified Companion projection and host owner capability do not exist in
|
||||
this repository. The arguments make that future interface explicit, but
|
||||
they are deliberately not queried, represented, stored, or logged.
|
||||
"""
|
||||
|
||||
del issuer, principal, capability
|
||||
flag = P5D_OPERATION_FLAGS.get(operation)
|
||||
if not flag:
|
||||
raise ValueError("p5d_unknown_operation")
|
||||
if not _bool(config, flag):
|
||||
return P5DSecurityEventDecision(
|
||||
True,
|
||||
operation,
|
||||
"default_off",
|
||||
_audit(operation, "bypass", "default_off"),
|
||||
)
|
||||
|
||||
audit = _audit(operation, "denied", P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE)
|
||||
logger.warning("[MemoryCompanion][P5-D] gate=%s", audit)
|
||||
return P5DSecurityEventDecision(
|
||||
False,
|
||||
operation,
|
||||
P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE,
|
||||
audit,
|
||||
)
|
||||
|
||||
|
||||
def p5d_security_event_reason(config: Any, operation: str) -> str:
|
||||
"""Return an empty string on the default-off rollback path, else deny."""
|
||||
|
||||
decision = check_p5d_security_event_operation(config, operation)
|
||||
return "" if decision.allowed else decision.reason_code
|
||||
|
||||
|
||||
def require_p5d_security_event_operation(config: Any, operation: str) -> None:
|
||||
"""Raise the stable controlled denial when an enabled operation has no grant."""
|
||||
|
||||
decision = check_p5d_security_event_operation(config, operation)
|
||||
if not decision.allowed:
|
||||
raise P5DControlledDeny(decision.operation, decision.reason_code)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CROSS_TURN_CORRELATION_OPERATION",
|
||||
"MANUAL_RECOVERY_OPERATION",
|
||||
"P5D_CONFIG_MODULE",
|
||||
"P5DControlledDeny",
|
||||
"P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE",
|
||||
"P5D_OPERATION_FLAGS",
|
||||
"P5DSecurityEventDecision",
|
||||
"check_p5d_security_event_operation",
|
||||
"p5d_security_event_reason",
|
||||
"require_p5d_security_event_operation",
|
||||
]
|
||||
100
tests/test_p5d_security_events.py
普通文件
100
tests/test_p5d_security_events.py
普通文件
|
|
@ -0,0 +1,100 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from core.p5d_security_events import (
|
||||
CROSS_TURN_CORRELATION_OPERATION,
|
||||
MANUAL_RECOVERY_OPERATION,
|
||||
P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE,
|
||||
P5D_OPERATION_FLAGS,
|
||||
check_p5d_security_event_operation,
|
||||
p5d_security_event_reason,
|
||||
)
|
||||
|
||||
|
||||
class _Config:
|
||||
def __init__(self, **flags: bool) -> None:
|
||||
self.flags = flags
|
||||
|
||||
def bool(self, key: str, default: bool = False) -> bool:
|
||||
return bool(self.flags.get(key, default))
|
||||
|
||||
|
||||
class _PoisonedObject:
|
||||
def __getattribute__(self, name: str):
|
||||
if name not in {"__class__", "__del__"}:
|
||||
raise AssertionError(f"caller object must not be inspected: {name}")
|
||||
return super().__getattribute__(name)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - only called on a regression
|
||||
raise AssertionError("caller object must not be represented or logged")
|
||||
|
||||
|
||||
class _PoisonedMapping(dict):
|
||||
def __getattribute__(self, name: str):
|
||||
if name not in {"__class__", "__del__"}:
|
||||
raise AssertionError(f"caller mapping must not be inspected: {name}")
|
||||
return super().__getattribute__(name)
|
||||
|
||||
def __repr__(self) -> str: # pragma: no cover - only called on a regression
|
||||
raise AssertionError("caller mapping must not be represented or logged")
|
||||
|
||||
|
||||
class P5DSecurityEventTests(unittest.TestCase):
|
||||
def test_every_operation_is_default_off_with_missing_or_flat_config(self) -> None:
|
||||
for operation in P5D_OPERATION_FLAGS:
|
||||
with self.subTest(operation=operation, config="missing"):
|
||||
decision = check_p5d_security_event_operation(None, operation)
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual("default_off", decision.reason_code)
|
||||
self.assertEqual("", p5d_security_event_reason(None, operation))
|
||||
with self.subTest(operation=operation, config="flat"):
|
||||
decision = check_p5d_security_event_operation(_Config(), operation)
|
||||
self.assertTrue(decision.allowed)
|
||||
self.assertEqual("default_off", decision.reason_code)
|
||||
|
||||
def test_schema_path_config_is_supported_and_enabled_operations_fail_closed(self) -> None:
|
||||
for operation, flag in P5D_OPERATION_FLAGS.items():
|
||||
for config_name, config in (
|
||||
("flat", _Config(**{flag: True})),
|
||||
("schema_path", _Config(**{f"p5d_safety.{flag}": True})),
|
||||
):
|
||||
with self.subTest(operation=operation, config=config_name):
|
||||
with self.assertLogs("MemoryCompanion.P5D", level="WARNING") as logs:
|
||||
decision = check_p5d_security_event_operation(
|
||||
config,
|
||||
operation,
|
||||
issuer=_PoisonedMapping({"issuer": "forged"}),
|
||||
principal=_PoisonedObject(),
|
||||
capability=_PoisonedObject(),
|
||||
)
|
||||
self.assertFalse(decision.allowed)
|
||||
self.assertEqual(P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE, decision.reason_code)
|
||||
self.assertEqual(
|
||||
{"operation", "outcome", "reason_code", "ref_hash"},
|
||||
set(decision.audit),
|
||||
)
|
||||
rendered = "\n".join(logs.output)
|
||||
self.assertNotIn("forged", rendered)
|
||||
self.assertNotIn("Poisoned", rendered)
|
||||
|
||||
def test_unknown_operation_is_rejected(self) -> None:
|
||||
with self.assertRaisesRegex(ValueError, "p5d_unknown_operation"):
|
||||
check_p5d_security_event_operation(_Config(), "forged_operation")
|
||||
|
||||
def test_schema_defines_exactly_two_default_off_flags(self) -> None:
|
||||
schema_path = Path(__file__).resolve().parents[1] / "_conf_schema.json"
|
||||
schema = json.loads(schema_path.read_text(encoding="utf-8"))
|
||||
items = schema["p5d_safety"]["items"]
|
||||
self.assertEqual(set(P5D_OPERATION_FLAGS.values()), set(items))
|
||||
self.assertTrue(all(item["type"] == "bool" and item["default"] is False for item in items.values()))
|
||||
self.assertEqual(
|
||||
{CROSS_TURN_CORRELATION_OPERATION, MANUAL_RECOVERY_OPERATION},
|
||||
set(P5D_OPERATION_FLAGS),
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
正在加载…
添加表格
在新工单中引用