cap-sdk-python 2.13.3__py3-none-any.whl → 2.16.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. cap/__init__.py +92 -25
  2. cap/client.py +14 -11
  3. cap/handshake.py +24 -13
  4. cap/heartbeat.py +56 -36
  5. cap/metrics.py +16 -1
  6. cap/packet_boundary.py +155 -0
  7. cap/pb/cordum/agent/v1/alert_pb2_grpc.py +1 -1
  8. cap/pb/cordum/agent/v1/buspacket_pb2.py +4 -2
  9. cap/pb/cordum/agent/v1/buspacket_pb2_grpc.py +1 -1
  10. cap/pb/cordum/agent/v1/handshake_pb2.py +22 -7
  11. cap/pb/cordum/agent/v1/handshake_pb2_grpc.py +1 -1
  12. cap/pb/cordum/agent/v1/heartbeat_pb2_grpc.py +1 -1
  13. cap/pb/cordum/agent/v1/job_pb2.py +42 -35
  14. cap/pb/cordum/agent/v1/job_pb2_grpc.py +1 -1
  15. cap/pb/cordum/agent/v1/policy_pb2_grpc.py +1 -1
  16. cap/pb/cordum/agent/v1/safety_pb2.py +28 -28
  17. cap/pb/cordum/agent/v1/safety_pb2_grpc.py +1 -1
  18. cap/production_events.py +222 -0
  19. cap/production_replay.py +79 -0
  20. cap/production_resource.py +163 -0
  21. cap/production_signing.py +293 -0
  22. cap/production_validation.py +50 -0
  23. cap/progress.py +25 -23
  24. cap/py.typed +1 -0
  25. cap/runtime.py +882 -116
  26. cap/subjects.py +2 -0
  27. cap/testing.py +10 -2
  28. cap/trust_signing.py +148 -0
  29. cap/validate.py +119 -78
  30. cap/worker.py +272 -121
  31. cap/worker_trust.py +223 -0
  32. cap/worker_trust_async.py +85 -0
  33. cap/worker_trust_build.py +128 -0
  34. cap/worker_trust_codec.py +34 -0
  35. cap/worker_trust_runtime.py +272 -0
  36. cap/worker_trust_runtime_config.py +148 -0
  37. cap/worker_trust_validate.py +213 -0
  38. cap/worker_trust_verify.py +117 -0
  39. cap_sdk_python-2.16.1.dist-info/METADATA +414 -0
  40. cap_sdk_python-2.16.1.dist-info/RECORD +54 -0
  41. cap_sdk_python-2.16.1.dist-info/licenses/LICENSE +190 -0
  42. cap_sdk_python-2.13.3.dist-info/METADATA +0 -241
  43. cap_sdk_python-2.13.3.dist-info/RECORD +0 -37
  44. {cap_sdk_python-2.13.3.dist-info → cap_sdk_python-2.16.1.dist-info}/WHEEL +0 -0
  45. {cap_sdk_python-2.13.3.dist-info → cap_sdk_python-2.16.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,79 @@
1
+ """CAP-PRODUCTION atomic replay admission (in-memory reference store)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timezone
8
+ from enum import Enum
9
+ from typing import Dict, Protocol
10
+
11
+
12
+ class ReplayOutcome(Enum):
13
+ FIRST = "first"
14
+ DUPLICATE = "duplicate"
15
+
16
+
17
+ class ReplayConflictError(ValueError):
18
+ """Same (tenant, audience, sender, message_id) seen with a different digest."""
19
+
20
+
21
+ class ReplayStoreUnavailableError(ValueError):
22
+ """The replay store rejected the request (invalid input or backend down).
23
+
24
+ Callers MUST fail closed on this error, never treat it as first-seen.
25
+ """
26
+
27
+
28
+ class ReplayStore(Protocol):
29
+ def admit(
30
+ self,
31
+ tenant: str,
32
+ audience: str,
33
+ sender: str,
34
+ message_id: bytes,
35
+ digest: bytes,
36
+ expires_at: datetime,
37
+ ) -> ReplayOutcome: ...
38
+
39
+
40
+ @dataclass
41
+ class _Entry:
42
+ digest: bytes
43
+ expires_at: datetime
44
+
45
+
46
+ class InMemoryReplayStore:
47
+ """Reference ReplayStore. Durable deployments (e.g. Cordum) supply a
48
+ Redis- or other durable-backed implementation of the same interface."""
49
+
50
+ def __init__(self) -> None:
51
+ self._lock = threading.Lock()
52
+ self._entries: Dict[tuple[str, str, str, bytes], _Entry] = {}
53
+
54
+ def admit(
55
+ self,
56
+ tenant: str,
57
+ audience: str,
58
+ sender: str,
59
+ message_id: bytes,
60
+ digest: bytes,
61
+ expires_at: datetime,
62
+ ) -> ReplayOutcome:
63
+ if not tenant or not audience or not sender or len(message_id) != 16 or not digest:
64
+ raise ReplayStoreUnavailableError("invalid replay admission input")
65
+ now = datetime.now(timezone.utc)
66
+ if expires_at <= now:
67
+ raise ReplayStoreUnavailableError("expires_at must be in the future")
68
+ key = (tenant, audience, sender, bytes(message_id))
69
+ with self._lock:
70
+ expired = [key for key, entry in self._entries.items() if entry.expires_at <= now]
71
+ for expired_key in expired:
72
+ del self._entries[expired_key]
73
+ existing = self._entries.get(key)
74
+ if existing is not None and existing.expires_at > now:
75
+ if existing.digest == digest:
76
+ return ReplayOutcome.DUPLICATE
77
+ raise ReplayConflictError(f"replay digest conflict for message_id={message_id.hex()}")
78
+ self._entries[key] = _Entry(digest=digest, expires_at=expires_at)
79
+ return ReplayOutcome.FIRST
@@ -0,0 +1,163 @@
1
+ """Fail-closed CAP-PRODUCTION ResourceRef validation."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime, timezone
6
+ import re
7
+ from typing import Optional, Sequence
8
+
9
+ from .pb.cordum.agent.v1.job_pb2 import ResourceRef
10
+
11
+
12
+ MAX_RESOURCE_IDENTIFIER_BYTES = 128
13
+ MAX_RESOURCE_AUTHORITY_BYTES = 255
14
+ MAX_RESOURCE_URI_BYTES = 2048
15
+ MAX_RESOURCE_MEDIA_TYPE_BYTES = 127
16
+ MAX_RESOURCE_PURPOSE_BYTES = 128
17
+ MAX_RESOURCE_SIZE_BYTES = 1 << 30
18
+ MAX_LEGACY_REDIS_KEY_BYTES = 1024
19
+
20
+ _ID_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._-]*$")
21
+ _PURPOSE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9._:-]*$")
22
+ _MEDIA_PATTERN = re.compile(r"^[a-z0-9][a-z0-9!#$&^_.+-]*/[a-z0-9][a-z0-9!#$&^_.+-]*$")
23
+ _URI_PATTERN = re.compile(r"^([a-z][a-z0-9+.-]{0,31})://(.+)$")
24
+ _LEGACY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:._@\-\[\]]*$")
25
+
26
+
27
+ class ResourceRefValidationError(ValueError):
28
+ """A structured or migration resource reference is unsafe."""
29
+
30
+
31
+ def validate_resource_ref(
32
+ ref: ResourceRef,
33
+ installed_resolvers: Sequence[str],
34
+ *,
35
+ now: Optional[datetime] = None,
36
+ ) -> None:
37
+ """Validate generic production bounds before resolver-specific checks."""
38
+ if ref is None:
39
+ raise ResourceRefValidationError("missing resource reference")
40
+ _validate_installed_resolvers(installed_resolvers)
41
+ _validate_identifiers(ref, installed_resolvers)
42
+ if len(ref.sha256) != 32:
43
+ raise ResourceRefValidationError("SHA-256 must contain exactly 32 bytes")
44
+ if ref.size_bytes <= 0 or ref.size_bytes > MAX_RESOURCE_SIZE_BYTES:
45
+ raise ResourceRefValidationError("declared size is outside production bounds")
46
+ _validate_uri(ref.uri)
47
+ _validate_expiry(ref, now or datetime.now(timezone.utc))
48
+
49
+
50
+ def _validate_installed_resolvers(installed: Sequence[str]) -> None:
51
+ if isinstance(installed, (str, bytes)) or not installed:
52
+ raise ResourceRefValidationError("resolver configuration is empty or noncanonical")
53
+ if any(not _valid_identifier(value, MAX_RESOURCE_IDENTIFIER_BYTES, _ID_PATTERN) for value in installed):
54
+ raise ResourceRefValidationError("resolver configuration is empty or noncanonical")
55
+
56
+
57
+ def _validate_identifiers(ref: ResourceRef, installed: Sequence[str]) -> None:
58
+ if not _valid_identifier(ref.resolver_id, MAX_RESOURCE_IDENTIFIER_BYTES, _ID_PATTERN):
59
+ raise ResourceRefValidationError("resolver ID is not canonical")
60
+ if ref.resolver_id not in installed:
61
+ raise ResourceRefValidationError("resolver is not installed")
62
+ if not _valid_identifier(ref.media_type, MAX_RESOURCE_MEDIA_TYPE_BYTES, _MEDIA_PATTERN):
63
+ raise ResourceRefValidationError("media type is not canonical")
64
+ if not _valid_identifier(ref.purpose, MAX_RESOURCE_PURPOSE_BYTES, _PURPOSE_PATTERN):
65
+ raise ResourceRefValidationError("purpose is not canonical")
66
+
67
+
68
+ def _valid_identifier(value: str, limit: int, pattern: re.Pattern[str]) -> bool:
69
+ try:
70
+ encoded = value.encode("ascii")
71
+ except UnicodeEncodeError:
72
+ return False
73
+ return bool(value and len(encoded) <= limit and value.strip() == value and pattern.fullmatch(value))
74
+
75
+
76
+ def _validate_uri(uri: str) -> None:
77
+ try:
78
+ encoded = uri.encode("ascii")
79
+ except UnicodeEncodeError as exc:
80
+ raise ResourceRefValidationError("resource URI must be ASCII") from exc
81
+ if not uri or len(encoded) > MAX_RESOURCE_URI_BYTES or uri.strip() != uri:
82
+ raise ResourceRefValidationError("resource URI is empty, untrimmed, or too long")
83
+ if any(byte < 0x21 or byte > 0x7E for byte in encoded):
84
+ raise ResourceRefValidationError("resource URI contains a control character")
85
+ match = _URI_PATTERN.fullmatch(uri)
86
+ if match is None:
87
+ raise ResourceRefValidationError("resource URI scheme is not canonical")
88
+ authority_and_path = match.group(2)
89
+ if any(character in authority_and_path for character in "@?#\\%"):
90
+ raise ResourceRefValidationError("resource URI contains credentials, metadata, or escapes")
91
+ _validate_path(authority_and_path)
92
+
93
+
94
+ def _validate_path(authority_and_path: str) -> None:
95
+ authority, separator, path = authority_and_path.partition("/")
96
+ if not authority or len(authority.encode("ascii")) > MAX_RESOURCE_AUTHORITY_BYTES:
97
+ raise ResourceRefValidationError("resource URI authority is empty or too long")
98
+ if not separator:
99
+ return
100
+ segments = path.split("/")
101
+ if any(not segment or segment in {".", ".."} or ".." in segment for segment in segments):
102
+ raise ResourceRefValidationError("resource URI path is not normalized")
103
+
104
+
105
+ def _validate_expiry(ref: ResourceRef, now: datetime) -> None:
106
+ if now.tzinfo is None or now.utcoffset() is None:
107
+ raise ResourceRefValidationError("validation time must be timezone-aware")
108
+ if not ref.HasField("expires_at"):
109
+ raise ResourceRefValidationError("resource expiry is required")
110
+ if ref.expires_at.nanos < 0 or ref.expires_at.nanos >= 1_000_000_000:
111
+ raise ResourceRefValidationError("resource expiry timestamp is invalid")
112
+ try:
113
+ expiry = ref.expires_at.ToDatetime(tzinfo=timezone.utc)
114
+ except (OverflowError, ValueError) as exc:
115
+ raise ResourceRefValidationError("resource expiry timestamp is invalid") from exc
116
+ if expiry <= now.astimezone(timezone.utc):
117
+ raise ResourceRefValidationError("resource expiry is not in the future")
118
+
119
+
120
+ def canonical_legacy_redis_key(pointer: str) -> bytes:
121
+ """Return exact Redis key bytes without URL-parser normalization."""
122
+ if pointer.strip() != pointer or len(pointer.encode("utf-8")) > len("redis://") + MAX_LEGACY_REDIS_KEY_BYTES:
123
+ raise ResourceRefValidationError("legacy Redis pointer is untrimmed or too long")
124
+ if not pointer.startswith("redis://"):
125
+ raise ResourceRefValidationError("legacy Redis pointer has the wrong scheme")
126
+ key = pointer[len("redis://") :]
127
+ at, colon = key.find("@"), key.find(":")
128
+ has_userinfo = at >= 0 and (colon < 0 or at < colon)
129
+ if _LEGACY_KEY_PATTERN.fullmatch(key) is None or ".." in key or has_userinfo:
130
+ raise ResourceRefValidationError("legacy Redis key is empty or ambiguous")
131
+ return key.encode("ascii")
132
+
133
+
134
+ def validate_resource_ref_compatibility(
135
+ legacy_pointer: str, ref: Optional[ResourceRef]
136
+ ) -> None:
137
+ """Reject differing dual legacy/structured Redis references."""
138
+ if not legacy_pointer or ref is None:
139
+ return
140
+ if ref.resolver_id != "redis":
141
+ raise ResourceRefValidationError("legacy Redis pointer uses a different resolver")
142
+ legacy_key = canonical_legacy_redis_key(legacy_pointer)
143
+ try:
144
+ structured_key = canonical_legacy_redis_key(ref.uri)
145
+ except ResourceRefValidationError as exc:
146
+ raise ResourceRefValidationError("legacy structured URI is ambiguous") from exc
147
+ if legacy_key != structured_key:
148
+ raise ResourceRefValidationError("legacy and structured references differ")
149
+
150
+
151
+ __all__ = [
152
+ "MAX_LEGACY_REDIS_KEY_BYTES",
153
+ "MAX_RESOURCE_AUTHORITY_BYTES",
154
+ "MAX_RESOURCE_IDENTIFIER_BYTES",
155
+ "MAX_RESOURCE_MEDIA_TYPE_BYTES",
156
+ "MAX_RESOURCE_PURPOSE_BYTES",
157
+ "MAX_RESOURCE_SIZE_BYTES",
158
+ "MAX_RESOURCE_URI_BYTES",
159
+ "ResourceRefValidationError",
160
+ "canonical_legacy_redis_key",
161
+ "validate_resource_ref",
162
+ "validate_resource_ref_compatibility",
163
+ ]
@@ -0,0 +1,293 @@
1
+ """CAP-PRODUCTION exact-wire signing and verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from dataclasses import dataclass
7
+ from datetime import datetime, timedelta, timezone
8
+ from typing import Callable, Mapping
9
+
10
+ from cryptography.hazmat.primitives import hashes
11
+ from cryptography.hazmat.primitives.asymmetric import ec, utils
12
+ from google.protobuf.message import DecodeError
13
+
14
+ from .pb.cordum.agent.v1.buspacket_pb2 import BusPacket, SignatureMetadata
15
+
16
+ DOMAIN = b"CAP-PRODUCTION-SIGNATURE-V1\x00"
17
+ PROFILE_VERSION = "cap-production-v1"
18
+ ALGORITHM = "ECDSA-P256-SHA256"
19
+ DEFAULT_MAX_LIFETIME = timedelta(minutes=5)
20
+ MAX_CLOCK_SKEW = timedelta(minutes=1)
21
+ MAX_PRODUCTION_RAW_BYTES = 1 << 20
22
+ _BUS_PACKET_WIRE_TYPES = {
23
+ **{number: 2 for number in (1, 2, 3, 5, 6)},
24
+ 4: 0,
25
+ **{number: 2 for number in range(10, 23)},
26
+ }
27
+ _BUS_PACKET_PAYLOAD_FIELDS = frozenset(
28
+ {10, 11, 12, 13, 15, 16, 17, 19, 20, 21, 22}
29
+ )
30
+
31
+
32
+ class ProductionSignatureError(ValueError):
33
+ """Raised when production wire admission fails closed."""
34
+
35
+
36
+ @dataclass(frozen=True)
37
+ class ProductionTrust:
38
+ audience: str
39
+ public_keys: Mapping[str, ec.EllipticCurvePublicKey]
40
+ tenant: str
41
+ sender: str
42
+ max_lifetime: timedelta = DEFAULT_MAX_LIFETIME
43
+ clock_skew: timedelta = timedelta(0)
44
+ now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)
45
+
46
+
47
+ def sign_production_packet(packet: BusPacket, key: ec.EllipticCurvePrivateKey) -> bytes:
48
+ _require_p256_key(key)
49
+ _validate_metadata(packet)
50
+ clone = BusPacket()
51
+ clone.CopyFrom(packet)
52
+ clone.signature = b""
53
+ unsigned = clone.SerializeToString()
54
+ _validate_unsigned_bus_packet(unsigned)
55
+ _reject_unknown_nested_fields(clone)
56
+ signature = key.sign(_digest(unsigned), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
57
+ raw = unsigned + _field(14, signature)
58
+ if len(raw) > MAX_PRODUCTION_RAW_BYTES:
59
+ raise ProductionSignatureError("production packet exceeds size limit")
60
+ return raw
61
+
62
+
63
+ def verify_production_packet(raw: bytes, trust: ProductionTrust) -> BusPacket:
64
+ _validate_trust_authority(trust)
65
+ unsigned, signature = extract_signature(raw)
66
+ packet = BusPacket()
67
+ try:
68
+ packet.ParseFromString(unsigned)
69
+ except DecodeError as exc:
70
+ raise ProductionSignatureError("malformed production protobuf") from exc
71
+ _reject_unknown_nested_fields(packet)
72
+ _validate_metadata(packet, trust.audience, trust)
73
+ if packet.identity.tenant_id != trust.tenant:
74
+ raise ProductionSignatureError("tenant mismatch")
75
+ if packet.sender_id != trust.sender:
76
+ raise ProductionSignatureError("sender mismatch")
77
+ key = trust.public_keys.get(packet.signature_metadata.key_id)
78
+ if key is None:
79
+ raise ProductionSignatureError("unknown key id")
80
+ _require_p256_key(key)
81
+ try:
82
+ key.verify(signature, _digest(unsigned), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
83
+ except Exception as exc:
84
+ raise ProductionSignatureError("invalid signature") from exc
85
+ packet.signature = signature
86
+ return packet
87
+
88
+
89
+ def extract_signature(raw: bytes) -> tuple[bytes, bytes]:
90
+ if len(raw) > MAX_PRODUCTION_RAW_BYTES:
91
+ raise ProductionSignatureError("production packet exceeds size limit")
92
+ unsigned = bytearray()
93
+ signature: bytes | None = None
94
+ seen: set[int] = set()
95
+ payload_field: int | None = None
96
+ offset = 0
97
+ while offset < len(raw):
98
+ start = offset
99
+ tag, offset = _varint(raw, offset)
100
+ number, wire_type = tag >> 3, tag & 7
101
+ payload_field = _validate_bus_packet_field(
102
+ number, wire_type, seen, payload_field
103
+ )
104
+ if number == 4:
105
+ protocol_version, value_end = _varint(raw, offset)
106
+ if protocol_version != 1 or raw[offset:value_end] != b"\x01":
107
+ raise ProductionSignatureError("invalid protocol version wire")
108
+ else:
109
+ value_end = _skip_value(raw, offset, wire_type)
110
+ if number == 14:
111
+ length, data_start = _varint(raw, offset)
112
+ if data_start + length != value_end or length == 0:
113
+ raise ProductionSignatureError("malformed signature")
114
+ signature = raw[data_start:value_end]
115
+ else:
116
+ unsigned.extend(raw[start:value_end])
117
+ offset = value_end
118
+ if 4 not in seen:
119
+ raise ProductionSignatureError("invalid protocol version wire")
120
+ if signature is None:
121
+ raise ProductionSignatureError("missing signature")
122
+ return bytes(unsigned), signature
123
+
124
+
125
+ def _validate_trust_authority(trust: ProductionTrust) -> None:
126
+ authorities = (trust.audience, trust.tenant, trust.sender)
127
+ if any(
128
+ not isinstance(value, str)
129
+ or not value.strip()
130
+ or value != value.strip()
131
+ for value in authorities
132
+ ):
133
+ raise ProductionSignatureError("production trust authority required")
134
+
135
+
136
+ def _validate_unsigned_bus_packet(unsigned: bytes) -> None:
137
+ """Apply the verifier's exact-wire rules before emitting a signature."""
138
+ extract_signature(unsigned + _field(14, b"\x01"))
139
+
140
+
141
+ def _reject_unknown_nested_fields(packet: BusPacket) -> None:
142
+ probe = BusPacket()
143
+ probe.CopyFrom(packet)
144
+ with_unknown = probe.SerializeToString(deterministic=True)
145
+ probe.DiscardUnknownFields()
146
+ without_unknown = probe.SerializeToString(deterministic=True)
147
+ if with_unknown != without_unknown:
148
+ raise ProductionSignatureError("unknown nested protobuf field")
149
+
150
+
151
+ def _validate_bus_packet_field(
152
+ number: int,
153
+ wire_type: int,
154
+ seen: set[int],
155
+ payload_field: int | None,
156
+ ) -> int | None:
157
+ expected = _BUS_PACKET_WIRE_TYPES.get(number)
158
+ if expected is None:
159
+ raise ProductionSignatureError("unknown BusPacket field")
160
+ if wire_type != expected:
161
+ raise ProductionSignatureError("wrong BusPacket field wire type")
162
+ if number in seen:
163
+ raise ProductionSignatureError("duplicate singular BusPacket field")
164
+ seen.add(number)
165
+ if number not in _BUS_PACKET_PAYLOAD_FIELDS:
166
+ return payload_field
167
+ if payload_field is not None:
168
+ raise ProductionSignatureError("multiple BusPacket payload fields")
169
+ return number
170
+
171
+
172
+ def _validate_metadata(
173
+ packet: BusPacket,
174
+ audience: str = "",
175
+ trust: ProductionTrust | None = None,
176
+ ) -> None:
177
+ if not packet.HasField("signature_metadata"):
178
+ raise ProductionSignatureError("missing signature metadata")
179
+ metadata = packet.signature_metadata
180
+ if metadata.profile_version != PROFILE_VERSION or metadata.algorithm != ALGORITHM:
181
+ raise ProductionSignatureError("unsupported production signature profile")
182
+ if len(metadata.message_id) != 16 or not metadata.audience or not metadata.key_id:
183
+ raise ProductionSignatureError("invalid signature metadata")
184
+ if audience and metadata.audience != audience:
185
+ raise ProductionSignatureError("audience mismatch")
186
+ expiry, now, skew, max_lifetime = _validated_time_bounds(metadata, trust)
187
+ try:
188
+ if expiry <= now - skew:
189
+ raise ProductionSignatureError("signature expired")
190
+ if max_lifetime is not None and expiry > now + max_lifetime + skew:
191
+ raise ProductionSignatureError("signature lifetime exceeds bound")
192
+ except (OverflowError, TypeError) as exc:
193
+ raise ProductionSignatureError("invalid production lifetime bounds") from exc
194
+
195
+
196
+ def _validated_time_bounds(
197
+ metadata: SignatureMetadata,
198
+ trust: ProductionTrust | None,
199
+ ) -> tuple[datetime, datetime, timedelta, timedelta | None]:
200
+ try:
201
+ expiry = metadata.expires_at.ToDatetime(tzinfo=timezone.utc)
202
+ except (OverflowError, ValueError) as exc:
203
+ raise ProductionSignatureError("invalid signature expiry") from exc
204
+ if trust is None:
205
+ return (
206
+ expiry,
207
+ datetime.now(timezone.utc),
208
+ timedelta(0),
209
+ DEFAULT_MAX_LIFETIME,
210
+ )
211
+ try:
212
+ now = trust.now()
213
+ except Exception as exc:
214
+ raise ProductionSignatureError("invalid production lifetime bounds") from exc
215
+ skew, max_lifetime = trust.clock_skew, trust.max_lifetime
216
+ if (
217
+ not isinstance(now, datetime)
218
+ or not isinstance(skew, timedelta)
219
+ or not isinstance(max_lifetime, timedelta)
220
+ or skew < timedelta(0)
221
+ or max_lifetime <= timedelta(0)
222
+ or max_lifetime > DEFAULT_MAX_LIFETIME
223
+ or skew > MAX_CLOCK_SKEW
224
+ or skew > max_lifetime
225
+ ):
226
+ raise ProductionSignatureError("invalid production lifetime bounds")
227
+ try:
228
+ if now.tzinfo is None or now.utcoffset() is None:
229
+ raise ProductionSignatureError("invalid production lifetime bounds")
230
+ except ProductionSignatureError:
231
+ raise
232
+ except Exception as exc:
233
+ raise ProductionSignatureError("invalid production lifetime bounds") from exc
234
+ return expiry, now, skew, max_lifetime
235
+
236
+
237
+ def _digest(unsigned: bytes) -> bytes:
238
+ return hashlib.sha256(DOMAIN + unsigned).digest()
239
+
240
+
241
+ def _require_p256_key(
242
+ key: ec.EllipticCurvePrivateKey | ec.EllipticCurvePublicKey,
243
+ ) -> None:
244
+ if not isinstance(key.curve, ec.SECP256R1):
245
+ raise ProductionSignatureError(
246
+ "production signatures require ECDSA P-256"
247
+ )
248
+
249
+
250
+ def _field(number: int, value: bytes) -> bytes:
251
+ return _encode_varint(number << 3 | 2) + _encode_varint(len(value)) + value
252
+
253
+
254
+ def _varint(raw: bytes, offset: int) -> tuple[int, int]:
255
+ value = 0
256
+ for index in range(10):
257
+ if offset >= len(raw):
258
+ raise ProductionSignatureError("truncated varint")
259
+ byte = raw[offset]
260
+ offset += 1
261
+ value |= (byte & 0x7F) << (index * 7)
262
+ if byte < 0x80:
263
+ if _encode_varint(value) != raw[offset - index - 1 : offset]:
264
+ raise ProductionSignatureError("non-minimal varint")
265
+ return value, offset
266
+ raise ProductionSignatureError("oversize varint")
267
+
268
+
269
+ def _encode_varint(value: int) -> bytes:
270
+ output = bytearray()
271
+ while value >= 0x80:
272
+ output.append((value & 0x7F) | 0x80)
273
+ value >>= 7
274
+ output.append(value)
275
+ return bytes(output)
276
+
277
+
278
+ def _skip_value(raw: bytes, offset: int, wire_type: int) -> int:
279
+ if wire_type == 0:
280
+ _, offset = _varint(raw, offset)
281
+ return offset
282
+ if wire_type == 1:
283
+ end = offset + 8
284
+ elif wire_type == 2:
285
+ length, offset = _varint(raw, offset)
286
+ end = offset + length
287
+ elif wire_type == 5:
288
+ end = offset + 4
289
+ else:
290
+ raise ProductionSignatureError("unsupported wire type")
291
+ if end > len(raw):
292
+ raise ProductionSignatureError("truncated field")
293
+ return end
@@ -0,0 +1,50 @@
1
+ """CAP-PRODUCTION authoritative identity validation (admission-layer subset).
2
+
3
+ Mirrors sdk/go/production_validation.go's ValidateIdentityBinding. Broader
4
+ cross-mirror identity normalization (top-level/meta/env/label agreement
5
+ across every ingress) is task-a13f83fa step-9 scope; this module covers only
6
+ what the raw-packet admission layer (step-7) needs before dispatch.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from .pb.cordum.agent.v1.job_pb2 import IdentityBinding, JobRequest
12
+
13
+
14
+ class IdentityMismatchError(ValueError):
15
+ """A JobRequest mirror disagrees with the authoritative IdentityBinding."""
16
+
17
+
18
+ def validate_identity_binding(request: JobRequest, authoritative: IdentityBinding) -> None:
19
+ if request is None or authoritative is None or not authoritative.tenant_id:
20
+ raise IdentityMismatchError("missing request or authoritative identity")
21
+ mirrors = {
22
+ "tenant": request.tenant_id,
23
+ "principal": request.principal_id,
24
+ "meta.tenant": request.meta.tenant_id if request.HasField("meta") else "",
25
+ "meta.actor": request.meta.actor_id if request.HasField("meta") else "",
26
+ "env.tenant": request.env.get("tenant_id", ""),
27
+ "env.principal": request.env.get("principal_id", ""),
28
+ }
29
+ for name, actual in mirrors.items():
30
+ if not actual:
31
+ continue
32
+ if "actor" in name:
33
+ expected = authoritative.actor_id
34
+ elif "principal" in name:
35
+ expected = authoritative.principal_id
36
+ else:
37
+ expected = authoritative.tenant_id
38
+ if actual != expected:
39
+ raise IdentityMismatchError(f"{name} mismatch")
40
+ if request.HasField("identity") and not _same_identity(request.identity, authoritative):
41
+ raise IdentityMismatchError("request.identity mismatch")
42
+
43
+
44
+ def _same_identity(a: IdentityBinding, b: IdentityBinding) -> bool:
45
+ return (
46
+ a.tenant_id == b.tenant_id
47
+ and a.principal_id == b.principal_id
48
+ and a.actor_id == b.actor_id
49
+ and a.delegation_id == b.delegation_id
50
+ )