feat(p5): add reject-only event recovery boundary

这个提交存在于:
YokiiroBW 2026-07-30 08:59:31 +08:00
父节点 670a956f3d
当前提交 daf9255810
共有 4 个文件被更改,包括 172 次插入 和 0 次删除

查看文件

@ -9168,6 +9168,23 @@
}
}
},
"p5d_safety_config": {
"description": "P5-D 跨轮安全事件与人工恢复门",
"type": "object",
"hint": "两项均默认关闭。当前没有宿主签发的跨轮 issuer 或 owner capability;启用后仅受控拒绝,不会从事件、会话、页面或 JSON 推导授权。",
"items": {
"enable_p5d_cross_turn_correlation": {
"description": "拒绝跨轮安全事件关联",
"type": "bool",
"default": false
},
"enable_p5d_manual_recovery": {
"description": "拒绝无宿主能力的人工恢复",
"type": "bool",
"default": false
}
}
},
"legacy_compat_config": {
"description": "旧版兼容项",
"type": "object",

查看文件

@ -140,6 +140,7 @@ from .context_orchestration import (
from .p5_ingress_firewall import evaluate_ingress_segments
from .p5_provenance_attestation import FIREWALL_STATUSES, P5AttestationRegistry
from .p5c_gate import RAW_IMAGE_PROVIDER_SINK, p5c_gate_allows
from .p5d_security_events import p5d_security_event_allows
from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed
from .token_budget import TokenBudgetMixin
from .balance_awareness import BalanceAwarenessMixin
@ -1959,6 +1960,10 @@ class PrivateCompanionPlugin(
self.enable_p5c_group_image_vision_gate = self._cfg_bool(c, "enable_p5c_group_image_vision_gate", False)
self.enable_p5c_context_image_caption_gate = self._cfg_bool(c, "enable_p5c_context_image_caption_gate", False)
self.enable_p5c_tool_parameter_gate = self._cfg_bool(c, "enable_p5c_tool_parameter_gate", False)
# P5-D has no host-verified owner capability or cross-turn issuer
# contract. These default-off flags therefore remain reject-only.
self.enable_p5d_cross_turn_correlation = self._cfg_bool(c, "enable_p5d_cross_turn_correlation", False)
self.enable_p5d_manual_recovery = self._cfg_bool(c, "enable_p5d_manual_recovery", False)
self.memory_companion_context_timeout_seconds = self._cfg_float(c, "memory_companion_context_timeout_seconds", 1.2, 0.2)
self.enable_memory_companion_emotional_drift = self._cfg_bool(c, "enable_memory_companion_emotional_drift", True)
self.enable_memory_companion_cross_window_emotion = self._cfg_bool(c, "enable_memory_companion_cross_window_emotion", True)
@ -9876,6 +9881,10 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"""Deny an enabled P5-C sink without treating carriers as authority."""
return p5c_gate_allows(self, sink)
def _p5d_security_event_allows(self, operation: str, *opaque: Any) -> bool:
"""Expose the P5-D reject-only boundary without creating a live hook."""
return p5d_security_event_allows(self, operation, *opaque)
def _p5_b1c_runtime_attestation_inputs(
self,
event: AstrMessageEvent,

68
p5d_security_events.py 普通文件
查看文件

@ -0,0 +1,68 @@
"""P5-D default-off, reject-only security-event boundary.
This plugin has no host-issued, owner-verified cross-turn capability. P5-A
projections, P5-B request handles, P5-C deny audits, P3 carriers, P4 shadow
state, events, sessions, mappings, and page payloads are not substitutes.
Accordingly, an enabled P5-D operation has exactly one outcome: deny.
"""
from __future__ import annotations
import hashlib
import logging
from typing import Any
logger = logging.getLogger("PrivateCompanion.P5D")
CROSS_TURN_CORRELATION_OPERATION = "cross_turn_correlation"
MANUAL_RECOVERY_OPERATION = "manual_recovery"
P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE = "p5d_host_owner_capability_unavailable"
P5D_OPERATION_FLAGS = {
CROSS_TURN_CORRELATION_OPERATION: "enable_p5d_cross_turn_correlation",
MANUAL_RECOVERY_OPERATION: "enable_p5d_manual_recovery",
}
def p5d_security_event_allows(host: Any, operation: str, *opaque: Any) -> bool:
"""Bypass only while disabled; never derive allow from caller objects."""
# Do not inspect, serialize, compare, store, or log caller values. They
# are the future host contract's responsibility, not local credentials.
del opaque
flag = P5D_OPERATION_FLAGS.get(operation)
if not flag:
raise ValueError("p5d_unknown_operation")
try:
enabled = bool(getattr(host, flag, False))
except Exception:
enabled = True
if not enabled:
return True
audit = {
"operation": operation,
"outcome": "denied",
"reason_code": P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE,
"ref_hash": hashlib.sha256(f"p5d:{operation}".encode("utf-8")).hexdigest(),
}
try:
entries = getattr(host, "_p5d_denial_audit", None)
if not isinstance(entries, list):
entries = []
setattr(host, "_p5d_denial_audit", entries)
entries.append(audit)
del entries[:-64]
except Exception:
pass
logger.warning("[PrivateCompanion][P5-D] gate=%s", audit)
return False
__all__ = [
"CROSS_TURN_CORRELATION_OPERATION",
"MANUAL_RECOVERY_OPERATION",
"P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE",
"P5D_OPERATION_FLAGS",
"p5d_security_event_allows",
]

查看文件

@ -0,0 +1,78 @@
# -*- coding: utf-8 -*-
"""Focused proof that P5-D never treats caller data as a capability."""
from __future__ import annotations
import importlib
import json
from pathlib import Path
import sys
from types import SimpleNamespace
import types
import unittest
sys.path.insert(0, str(Path(__file__).resolve().parent))
import _host_stub # noqa: E402
_host_stub.install()
event_module = importlib.import_module("astrbot.api.event")
event_module.filter.EventMessageType = SimpleNamespace(ALL="ALL", PRIVATE_MESSAGE="PRIVATE_MESSAGE", GROUP_MESSAGE="GROUP_MESSAGE")
PACKAGE = "_p5d_security_events_companion"
if PACKAGE not in sys.modules:
package = types.ModuleType(PACKAGE)
package.__path__ = [str(Path(__file__).resolve().parents[1])]
sys.modules[PACKAGE] = package
gate = importlib.import_module(f"{PACKAGE}.p5d_security_events")
main = importlib.import_module(f"{PACKAGE}.main")
class _EnabledHost:
enable_p5d_cross_turn_correlation = True
enable_p5d_manual_recovery = True
class _Poisoned:
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 - called only on regression
raise AssertionError("caller object must not be represented")
class P5DSecurityEventTests(unittest.TestCase):
def test_default_off_preserves_bypass(self) -> None:
host = SimpleNamespace()
for operation in gate.P5D_OPERATION_FLAGS:
self.assertTrue(gate.p5d_security_event_allows(host, operation, _Poisoned(), _Poisoned()))
def test_enabled_operations_reject_without_inspecting_forged_inputs(self) -> None:
for operation in gate.P5D_OPERATION_FLAGS:
host = _EnabledHost()
with self.subTest(operation=operation), self.assertLogs("PrivateCompanion.P5D", level="WARNING") as logs:
allowed = gate.p5d_security_event_allows(host, operation, _Poisoned(), _Poisoned(), _Poisoned())
self.assertFalse(allowed)
audit = host._p5d_denial_audit[-1]
self.assertEqual({"operation", "outcome", "reason_code", "ref_hash"}, set(audit))
self.assertEqual(gate.P5D_HOST_OWNER_CAPABILITY_UNAVAILABLE, audit["reason_code"])
self.assertNotIn("Poisoned", "\n".join(logs.output))
def test_main_helper_and_unknown_operation_keep_the_same_contract(self) -> None:
host = _EnabledHost()
host._p5d_security_event_allows = main.PrivateCompanionPlugin._p5d_security_event_allows.__get__(host, _EnabledHost)
self.assertFalse(host._p5d_security_event_allows(gate.MANUAL_RECOVERY_OPERATION, _Poisoned()))
with self.assertRaisesRegex(ValueError, "p5d_unknown_operation"):
gate.p5d_security_event_allows(host, "forged_operation")
def test_schema_has_exactly_the_two_default_off_operations(self) -> None:
schema = json.loads((Path(__file__).resolve().parents[1] / "_conf_schema.json").read_text(encoding="utf-8"))
items = schema["p5d_safety_config"]["items"]
self.assertEqual(set(gate.P5D_OPERATION_FLAGS.values()), set(items))
self.assertTrue(all(item["type"] == "bool" and item["default"] is False for item in items.values()))
if __name__ == "__main__":
unittest.main()