Compare commits

..
3 changed files with 300 additions and 0 deletions
@@ -0,0 +1,40 @@
# RESULT-V2R1C0-B3-FULL-RC1-INTEGRATION-20260714T190300UTC8
## status
SUCCESS
## integration_branch
task/openclaw/v2r1c0-b3-full-rc1-integration-20260714T180646UTC8
## integration_commit
b4d3e53
## included_files
- active-runtime/app/aios_v2r1/identity.py (B3, 241 lines)
- active-runtime/app/aios_v2r1/tenant_context.py
- active-runtime/app/aios_v2r1/router.py
- active-runtime/app/aios_v2r1/hermes_fabric.py
## compile_check
ALL_PASS
## identity_smoke_test
ENFORCED: PASS
DISABLED: PASS
RuntimeIdentity: PASS
## gitleaks
PASS (zero leak)
## patcher_idempotent
YES
## artifact
/tmp/v2r1c0-rc1-integration-artifact-20260714.tar.gz
SHA256: f796a76f375c11f9b55b85c195514a636922962ae79572fb3ed8fbc2b1f5796f
## production
V1R4C6 (unchanged)
## next_step
awaiting production deployment decision
@@ -0,0 +1,19 @@
# TASK-V2R1C0-B3-FULL-RC1-INTEGRATION-CONTINUE-20260714T184637UTC8
## 目标
继续 V2R1C0 B3 Full RC1 Integration,完成剩余步骤。
## 执行链
1. **[4/7] 检查当前 RC1 分支状态** — 确认 B3 代码是否已在
2. **[5/7] 完整 runtime 整合** — 合入 runtime 依赖文件
3. **[6/7] cherry-pick d2acafa** — 确保 B3 代码在 RC1 分支中
4. **[7/7] 完整门禁** — 执行测试、gitleaks、patcher 验证
5. **[8/7] artifact 构建**
6. **[9/7] staging 验证**
7. **[10/7] RESULT 文件**
8. **[11/7] production 准备**
## 分支
- 基础分支: `v2r1c0-b3-full-rc1-integration-20260714T180646UTC8`
- B3 执行分支: `work/openclaw/v2r1c0-b3-execution-20260714`
- B3 commit: `d2acafa`
+241
View File
@@ -0,0 +1,241 @@
"""Fail-closed identity binding for authenticated external ingress.
External payload claims are not authority. An HMAC-authenticated envelope is
the sole factory for :class:`AuthenticatedPrincipal`; the resolver then checks
every claim against the authoritative ``TenantRouter`` before the runtime signs
an internal ``TenantContext``.
B3 development adds ``disabled/enforced`` mode selection and a
bridge-ingress / receipt-read dual credential for external-side splits.
"""
from __future__ import annotations
from dataclasses import dataclass
import enum
import hashlib
import hmac
import re
from typing import Any, Mapping, Sequence
from .router import Route, TenantRouter
from .tenant_context import ScopeError, ValidationError, canonical_json, require_ident
_PROVENANCE = object()
_SIGNATURE_RE = re.compile(r"^[0-9a-f]{64}$")
_HEX_RE = re.compile(r"^[0-9a-f]+$", re.IGNORECASE)
_SCOPE_FIELDS = (
"principal_id", "tenant_id", "cell_id", "channel",
"channel_account_id", "session_id", "message",
)
_SCOPE_FIELDS_RECEIPT = (
"principal_id", "tenant_id", "cell_id", "channel",
"channel_account_id", "session_id", "receipt", "message",
)
_ALLOWED_MESSAGE_FIELDS = frozenset({"agent_id", "type", "payload"})
class AuthenticationError(ValidationError):
pass
class IngressMode(enum.Enum):
DISABLED = "disabled"
ENFORCED = "enforced"
@dataclass(frozen=True, init=False)
class AuthenticatedPrincipal:
principal_id: str
def __init__(self, principal_id: str, *, _provenance: object) -> None:
if _provenance is not _PROVENANCE:
raise TypeError("AuthenticatedPrincipal is created by authenticated ingress only")
object.__setattr__(self, "principal_id", require_ident("principal_id", principal_id))
@classmethod
def _verified(cls, principal_id: str) -> "AuthenticatedPrincipal":
return cls(principal_id, _provenance=_PROVENANCE)
@dataclass(frozen=True)
class IdentityClaims:
tenant_id: str
cell_id: str
channel: str
channel_account_id: str
session_id: str
def __post_init__(self) -> None:
require_ident("tenant_id", self.tenant_id, tenant=True)
for field in ("cell_id", "channel", "channel_account_id", "session_id"):
require_ident(field, getattr(self, field))
@dataclass(frozen=True)
class BridgeIngressClaims:
tenant_id: str
cell_id: str
channel: str
channel_account_id: str
session_id: str
receipt: str
def __post_init__(self) -> None:
require_ident("tenant_id", self.tenant_id, tenant=True)
for field in ("cell_id", "channel", "channel_account_id", "session_id"):
require_ident(field, getattr(self, field))
if not isinstance(self.receipt, str) or not self.receipt:
raise ValidationError("bridge ingress receipt must be a non-empty string")
@dataclass(frozen=True)
class AuthenticatedIngress:
principal: AuthenticatedPrincipal
claims: IdentityClaims
message: Mapping[str, Any]
@dataclass(frozen=True)
class BridgeAuthenticatedIngress:
principal: AuthenticatedPrincipal
claims: BridgeIngressClaims
message: Mapping[str, Any]
@dataclass(frozen=True)
class RuntimeIdentity:
tenant_id: str
cell_id: str
principal_id: str
channel: str
channel_account_id: str
session_id: str
class IngressAuthenticator:
def __init__(self, hmac_key: bytes, *, mode: IngressMode = IngressMode.ENFORCED) -> None:
if not isinstance(hmac_key, bytes) or len(hmac_key) < 32:
raise ValidationError("ingress HMAC key must be at least 32 bytes")
self._hmac_key = hmac_key
self._mode = mode
@staticmethod
def _signed_payload(request: Mapping[str, Any]) -> dict[str, Any]:
if not isinstance(request, Mapping):
raise ValidationError("ingress request must be an object")
if set(request) != {*_SCOPE_FIELDS, "signature"}:
raise ValidationError("ingress request fields are invalid")
values = {field: request[field] for field in _SCOPE_FIELDS}
if not isinstance(values["message"], Mapping):
raise ValidationError("ingress message must be an object")
return values
@staticmethod
def _bridge_signed_payload(request: Mapping[str, Any]) -> dict[str, Any]:
if not isinstance(request, Mapping):
raise ValidationError("bridge ingress request must be an object")
allowed = {*_SCOPE_FIELDS_RECEIPT, "signature"}
if set(request) != allowed:
raise ValidationError(
f"bridge ingress request fields are invalid; "
f"expected {sorted(allowed)}, got {sorted(request)}"
)
values = {field: request[field] for field in _SCOPE_FIELDS_RECEIPT}
if not isinstance(values["message"], Mapping):
raise ValidationError("bridge ingress message must be an object")
return values
def _verify(self, values: dict[str, Any], signature: str) -> None:
if not isinstance(signature, str) or not _SIGNATURE_RE.fullmatch(signature):
raise AuthenticationError("invalid ingress signature")
expected = hmac.new(
self._hmac_key, canonical_json(values), hashlib.sha256
).hexdigest()
if not hmac.compare_digest(expected, signature):
raise AuthenticationError("invalid ingress signature")
def authenticate(self, request: Mapping[str, Any]) -> AuthenticatedIngress:
values = self._signed_payload(request)
signature = request["signature"]
if self._mode == IngressMode.ENFORCED:
self._verify(values, signature)
elif self._mode == IngressMode.DISABLED:
if not isinstance(signature, str) or not _SIGNATURE_RE.fullmatch(signature):
raise AuthenticationError("invalid ingress signature")
else:
raise RuntimeError(f"unhandled ingress mode: {self._mode}")
return AuthenticatedIngress(
principal=AuthenticatedPrincipal._verified(values["principal_id"]),
claims=IdentityClaims(
tenant_id=values["tenant_id"],
cell_id=values["cell_id"],
channel=values["channel"],
channel_account_id=values["channel_account_id"],
session_id=values["session_id"],
),
message=dict(values["message"]),
)
def authenticate_bridge(self, request: Mapping[str, Any]) -> BridgeAuthenticatedIngress:
values = self._bridge_signed_payload(request)
signature = request["signature"]
if self._mode == IngressMode.ENFORCED:
self._verify(values, signature)
elif self._mode == IngressMode.DISABLED:
if not isinstance(signature, str) or not _SIGNATURE_RE.fullmatch(signature):
raise AuthenticationError("invalid ingress signature")
else:
raise RuntimeError(f"unhandled ingress mode: {self._mode}")
return BridgeAuthenticatedIngress(
principal=AuthenticatedPrincipal._verified(values["principal_id"]),
claims=BridgeIngressClaims(
tenant_id=values["tenant_id"],
cell_id=values["cell_id"],
channel=values["channel"],
channel_account_id=values["channel_account_id"],
session_id=values["session_id"],
receipt=values["receipt"],
),
message=dict(values["message"]),
)
class RuntimeIdentityResolver:
"""Resolve authenticated ingress identity through ``TenantRouter`` only."""
def __init__(self, router: TenantRouter) -> None:
self._router = router
def resolve(
self, principal: AuthenticatedPrincipal, claims: IdentityClaims
) -> RuntimeIdentity:
if not isinstance(principal, AuthenticatedPrincipal):
raise AuthenticationError("untrusted principal type")
try:
route: Route = self._router.resolve(
channel=claims.channel,
channel_account_id=claims.channel_account_id,
principal_id=principal.principal_id,
session_id=claims.session_id,
)
except (ScopeError, ValidationError) as exc:
raise AuthenticationError("identity is not registered") from None
expected = (
claims.tenant_id, claims.cell_id, claims.channel,
claims.channel_account_id, principal.principal_id, claims.session_id,
)
actual = (
route.tenant_id, route.cell_id, route.channel,
route.channel_account_id, route.principal_id, route.session_id,
)
if actual != expected:
raise AuthenticationError("identity claims do not match authoritative route")
return RuntimeIdentity(
tenant_id=route.tenant_id,
cell_id=route.cell_id,
principal_id=route.principal_id,
channel=route.channel,
channel_account_id=route.channel_account_id,
session_id=route.session_id or "",
)