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.
- cap/__init__.py +92 -25
- cap/client.py +14 -11
- cap/handshake.py +24 -13
- cap/heartbeat.py +56 -36
- cap/metrics.py +16 -1
- cap/packet_boundary.py +155 -0
- cap/pb/cordum/agent/v1/alert_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/buspacket_pb2.py +4 -2
- cap/pb/cordum/agent/v1/buspacket_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/handshake_pb2.py +22 -7
- cap/pb/cordum/agent/v1/handshake_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/heartbeat_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/job_pb2.py +42 -35
- cap/pb/cordum/agent/v1/job_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/policy_pb2_grpc.py +1 -1
- cap/pb/cordum/agent/v1/safety_pb2.py +28 -28
- cap/pb/cordum/agent/v1/safety_pb2_grpc.py +1 -1
- cap/production_events.py +222 -0
- cap/production_replay.py +79 -0
- cap/production_resource.py +163 -0
- cap/production_signing.py +293 -0
- cap/production_validation.py +50 -0
- cap/progress.py +25 -23
- cap/py.typed +1 -0
- cap/runtime.py +882 -116
- cap/subjects.py +2 -0
- cap/testing.py +10 -2
- cap/trust_signing.py +148 -0
- cap/validate.py +119 -78
- cap/worker.py +272 -121
- cap/worker_trust.py +223 -0
- cap/worker_trust_async.py +85 -0
- cap/worker_trust_build.py +128 -0
- cap/worker_trust_codec.py +34 -0
- cap/worker_trust_runtime.py +272 -0
- cap/worker_trust_runtime_config.py +148 -0
- cap/worker_trust_validate.py +213 -0
- cap/worker_trust_verify.py +117 -0
- cap_sdk_python-2.16.1.dist-info/METADATA +414 -0
- cap_sdk_python-2.16.1.dist-info/RECORD +54 -0
- cap_sdk_python-2.16.1.dist-info/licenses/LICENSE +190 -0
- cap_sdk_python-2.13.3.dist-info/METADATA +0 -241
- cap_sdk_python-2.13.3.dist-info/RECORD +0 -37
- {cap_sdk_python-2.13.3.dist-info → cap_sdk_python-2.16.1.dist-info}/WHEEL +0 -0
- {cap_sdk_python-2.13.3.dist-info → cap_sdk_python-2.16.1.dist-info}/top_level.txt +0 -0
cap/__init__.py
CHANGED
|
@@ -4,31 +4,6 @@ Provides helpers for submitting jobs, running workers, and building
|
|
|
4
4
|
high-level agents on the CAP bus.
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
|
-
import sys
|
|
8
|
-
import types
|
|
9
|
-
|
|
10
|
-
try:
|
|
11
|
-
from google.protobuf import runtime_version as _runtime_version # noqa: F401
|
|
12
|
-
except Exception:
|
|
13
|
-
try:
|
|
14
|
-
import google.protobuf as _protobuf
|
|
15
|
-
except Exception:
|
|
16
|
-
_protobuf = None
|
|
17
|
-
|
|
18
|
-
_shim = types.SimpleNamespace()
|
|
19
|
-
|
|
20
|
-
class _Domain:
|
|
21
|
-
PUBLIC = 0
|
|
22
|
-
|
|
23
|
-
def _validate(*_args, **_kwargs):
|
|
24
|
-
return None
|
|
25
|
-
|
|
26
|
-
_shim.Domain = _Domain
|
|
27
|
-
_shim.ValidateProtobufRuntimeVersion = _validate
|
|
28
|
-
sys.modules["google.protobuf.runtime_version"] = _shim
|
|
29
|
-
if _protobuf is not None:
|
|
30
|
-
setattr(_protobuf, "runtime_version", _shim)
|
|
31
|
-
|
|
32
7
|
from .client import submit_job
|
|
33
8
|
from .worker import run_worker
|
|
34
9
|
from .bus import connect_nats
|
|
@@ -43,16 +18,65 @@ from .heartbeat import (
|
|
|
43
18
|
heartbeat_loop,
|
|
44
19
|
)
|
|
45
20
|
from .handshake import handshake_payload, publish_handshake
|
|
21
|
+
from .trust_signing import (
|
|
22
|
+
TrustSigningError,
|
|
23
|
+
sign_trust_packet,
|
|
24
|
+
trust_packet_digest,
|
|
25
|
+
verify_trust_packet,
|
|
26
|
+
)
|
|
27
|
+
from .worker_trust import (
|
|
28
|
+
WORKER_HANDSHAKE_AUDIENCE,
|
|
29
|
+
VerifiedWorkerHandshakeChallenge,
|
|
30
|
+
WorkerHandshakeBindingError,
|
|
31
|
+
WorkerHandshakeExpiredError,
|
|
32
|
+
WorkerHandshakePacketError,
|
|
33
|
+
WorkerHandshakeRejectionError,
|
|
34
|
+
WorkerHandshakeRequestOptions,
|
|
35
|
+
WorkerHandshakeSession,
|
|
36
|
+
WorkerTrustConfig,
|
|
37
|
+
WorkerTrustConfigError,
|
|
38
|
+
WorkerTrustError,
|
|
39
|
+
WorkerTrustMode,
|
|
40
|
+
WorkerTrustModeError,
|
|
41
|
+
build_authenticate,
|
|
42
|
+
build_challenge_request,
|
|
43
|
+
parse_worker_trust_mode,
|
|
44
|
+
validate_worker_trust_config,
|
|
45
|
+
verify_challenge,
|
|
46
|
+
verify_result,
|
|
47
|
+
)
|
|
48
|
+
from .worker_trust_codec import (
|
|
49
|
+
marshal_worker_trust_packet,
|
|
50
|
+
unmarshal_worker_trust_packet,
|
|
51
|
+
)
|
|
52
|
+
from .worker_trust_validate import validate_worker_trust_packet
|
|
46
53
|
from .progress import (
|
|
47
54
|
progress_payload,
|
|
48
55
|
cancel_payload,
|
|
49
56
|
emit_progress,
|
|
50
57
|
emit_cancel,
|
|
51
58
|
)
|
|
59
|
+
from .production_resource import (
|
|
60
|
+
ResourceRefValidationError,
|
|
61
|
+
canonical_legacy_redis_key,
|
|
62
|
+
validate_resource_ref,
|
|
63
|
+
validate_resource_ref_compatibility,
|
|
64
|
+
)
|
|
65
|
+
from .production_events import (
|
|
66
|
+
ProductionEventAuthority,
|
|
67
|
+
ProductionEventConflictError,
|
|
68
|
+
admit_production_event,
|
|
69
|
+
bind_production_event,
|
|
70
|
+
freeze_production_authority,
|
|
71
|
+
seal_production_event,
|
|
72
|
+
)
|
|
52
73
|
from .validate import (
|
|
53
74
|
ValidationError,
|
|
75
|
+
validate_alert,
|
|
54
76
|
validate_job_request,
|
|
55
77
|
validate_job_result,
|
|
78
|
+
validate_job_progress,
|
|
79
|
+
validate_job_cancel,
|
|
56
80
|
validate_bus_packet,
|
|
57
81
|
)
|
|
58
82
|
from .errors import (
|
|
@@ -86,9 +110,17 @@ from .subjects import (
|
|
|
86
110
|
SUBJECT_DLQ,
|
|
87
111
|
SUBJECT_WORKFLOW_EVENT,
|
|
88
112
|
SUBJECT_HANDSHAKE,
|
|
113
|
+
SUBJECT_WORKER_HANDSHAKE_AUTHENTICATE,
|
|
114
|
+
SUBJECT_WORKER_HANDSHAKE_CHALLENGE,
|
|
89
115
|
)
|
|
90
116
|
|
|
91
117
|
__all__ = [
|
|
118
|
+
"ProductionEventAuthority",
|
|
119
|
+
"ProductionEventConflictError",
|
|
120
|
+
"admit_production_event",
|
|
121
|
+
"bind_production_event",
|
|
122
|
+
"freeze_production_authority",
|
|
123
|
+
"seal_production_event",
|
|
92
124
|
"submit_job",
|
|
93
125
|
"run_worker",
|
|
94
126
|
"connect_nats",
|
|
@@ -109,13 +141,46 @@ __all__ = [
|
|
|
109
141
|
"heartbeat_loop",
|
|
110
142
|
"handshake_payload",
|
|
111
143
|
"publish_handshake",
|
|
144
|
+
"TrustSigningError",
|
|
145
|
+
"sign_trust_packet",
|
|
146
|
+
"trust_packet_digest",
|
|
147
|
+
"verify_trust_packet",
|
|
148
|
+
"WORKER_HANDSHAKE_AUDIENCE",
|
|
149
|
+
"VerifiedWorkerHandshakeChallenge",
|
|
150
|
+
"WorkerHandshakeBindingError",
|
|
151
|
+
"WorkerHandshakeExpiredError",
|
|
152
|
+
"WorkerHandshakePacketError",
|
|
153
|
+
"WorkerHandshakeRejectionError",
|
|
154
|
+
"WorkerHandshakeRequestOptions",
|
|
155
|
+
"WorkerHandshakeSession",
|
|
156
|
+
"WorkerTrustConfig",
|
|
157
|
+
"WorkerTrustConfigError",
|
|
158
|
+
"WorkerTrustError",
|
|
159
|
+
"WorkerTrustMode",
|
|
160
|
+
"WorkerTrustModeError",
|
|
161
|
+
"build_authenticate",
|
|
162
|
+
"build_challenge_request",
|
|
163
|
+
"marshal_worker_trust_packet",
|
|
164
|
+
"parse_worker_trust_mode",
|
|
165
|
+
"unmarshal_worker_trust_packet",
|
|
166
|
+
"validate_worker_trust_config",
|
|
167
|
+
"validate_worker_trust_packet",
|
|
168
|
+
"verify_challenge",
|
|
169
|
+
"verify_result",
|
|
112
170
|
"progress_payload",
|
|
113
171
|
"cancel_payload",
|
|
114
172
|
"emit_progress",
|
|
115
173
|
"emit_cancel",
|
|
174
|
+
"ResourceRefValidationError",
|
|
175
|
+
"canonical_legacy_redis_key",
|
|
176
|
+
"validate_resource_ref",
|
|
177
|
+
"validate_resource_ref_compatibility",
|
|
116
178
|
"ValidationError",
|
|
179
|
+
"validate_alert",
|
|
117
180
|
"validate_job_request",
|
|
118
181
|
"validate_job_result",
|
|
182
|
+
"validate_job_progress",
|
|
183
|
+
"validate_job_cancel",
|
|
119
184
|
"validate_bus_packet",
|
|
120
185
|
"SUBJECT_SUBMIT",
|
|
121
186
|
"SUBJECT_RESULT",
|
|
@@ -126,6 +191,8 @@ __all__ = [
|
|
|
126
191
|
"SUBJECT_DLQ",
|
|
127
192
|
"SUBJECT_WORKFLOW_EVENT",
|
|
128
193
|
"SUBJECT_HANDSHAKE",
|
|
194
|
+
"SUBJECT_WORKER_HANDSHAKE_AUTHENTICATE",
|
|
195
|
+
"SUBJECT_WORKER_HANDSHAKE_CHALLENGE",
|
|
129
196
|
"CAPError",
|
|
130
197
|
"VersionMismatchError",
|
|
131
198
|
"MalformedPacketError",
|
cap/client.py
CHANGED
|
@@ -1,21 +1,23 @@
|
|
|
1
1
|
from google.protobuf import timestamp_pb2
|
|
2
|
-
from cap.pb.cordum.agent.v1 import buspacket_pb2
|
|
2
|
+
from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
|
|
3
3
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
4
|
-
from cryptography.hazmat.primitives import hashes
|
|
5
4
|
from typing import Optional
|
|
6
5
|
|
|
7
6
|
|
|
8
7
|
from cap.constants import DEFAULT_PROTOCOL_VERSION
|
|
8
|
+
from cap.packet_boundary import Publisher, finalize_packet
|
|
9
9
|
from cap.subjects import SUBJECT_SUBMIT
|
|
10
10
|
|
|
11
11
|
|
|
12
12
|
async def submit_job(
|
|
13
|
-
nc,
|
|
14
|
-
job_request,
|
|
13
|
+
nc: Publisher,
|
|
14
|
+
job_request: job_pb2.JobRequest,
|
|
15
15
|
trace_id: str,
|
|
16
16
|
sender_id: str,
|
|
17
17
|
private_key: Optional[ec.EllipticCurvePrivateKey] = None,
|
|
18
|
-
|
|
18
|
+
*,
|
|
19
|
+
session_token: Optional[str] = None,
|
|
20
|
+
) -> None:
|
|
19
21
|
"""Publish a JobRequest onto the CAP submit subject.
|
|
20
22
|
|
|
21
23
|
Args:
|
|
@@ -24,6 +26,7 @@ async def submit_job(
|
|
|
24
26
|
trace_id: Distributed trace identifier propagated through the bus.
|
|
25
27
|
sender_id: Identity of the sender (used in the BusPacket envelope).
|
|
26
28
|
private_key: Optional ECDSA private key for signing the packet.
|
|
29
|
+
session_token: Optional trusted runtime token for the outer envelope.
|
|
27
30
|
"""
|
|
28
31
|
ts = timestamp_pb2.Timestamp()
|
|
29
32
|
ts.GetCurrentTime()
|
|
@@ -34,9 +37,9 @@ async def submit_job(
|
|
|
34
37
|
packet.protocol_version = DEFAULT_PROTOCOL_VERSION
|
|
35
38
|
packet.job_request.CopyFrom(job_request)
|
|
36
39
|
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
40
|
+
outgoing = finalize_packet(
|
|
41
|
+
packet, private_key, session_token=session_token
|
|
42
|
+
)
|
|
43
|
+
await nc.publish(
|
|
44
|
+
SUBJECT_SUBMIT, outgoing.SerializeToString(deterministic=True)
|
|
45
|
+
)
|
cap/handshake.py
CHANGED
|
@@ -4,13 +4,14 @@ These helpers build and publish worker handshake BusPacket envelopes.
|
|
|
4
4
|
"""
|
|
5
5
|
|
|
6
6
|
from typing import Mapping, Optional, Sequence
|
|
7
|
+
from uuid import uuid4
|
|
7
8
|
|
|
8
|
-
from cryptography.hazmat.primitives import hashes
|
|
9
9
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
10
10
|
from google.protobuf import timestamp_pb2
|
|
11
11
|
|
|
12
12
|
from cap.constants import DEFAULT_PROTOCOL_VERSION
|
|
13
13
|
from cap.heartbeat import sanitize_agent_name
|
|
14
|
+
from cap.packet_boundary import Publisher, finalize_packet, parse_packet
|
|
14
15
|
from cap.pb.cordum.agent.v1 import buspacket_pb2, handshake_pb2
|
|
15
16
|
from cap.subjects import SUBJECT_HANDSHAKE
|
|
16
17
|
|
|
@@ -23,12 +24,22 @@ def handshake_payload(
|
|
|
23
24
|
supported_versions: Optional[Sequence[int]] = None,
|
|
24
25
|
ready_topics: Optional[Sequence[str]] = None,
|
|
25
26
|
agent_name: str = "",
|
|
27
|
+
trace_id: Optional[str] = None,
|
|
28
|
+
session_token: Optional[str] = None,
|
|
26
29
|
) -> bytes:
|
|
27
30
|
"""Build a worker handshake payload."""
|
|
31
|
+
versions = (
|
|
32
|
+
[DEFAULT_PROTOCOL_VERSION]
|
|
33
|
+
if supported_versions is None
|
|
34
|
+
else list(supported_versions)
|
|
35
|
+
)
|
|
36
|
+
if versions != [DEFAULT_PROTOCOL_VERSION]:
|
|
37
|
+
raise ValueError("supported_versions must contain exactly protocol v1")
|
|
28
38
|
ts = timestamp_pb2.Timestamp()
|
|
29
39
|
ts.GetCurrentTime()
|
|
30
40
|
|
|
31
41
|
packet = buspacket_pb2.BusPacket()
|
|
42
|
+
packet.trace_id = trace_id or uuid4().hex
|
|
32
43
|
packet.sender_id = sender_id or component_id
|
|
33
44
|
packet.protocol_version = DEFAULT_PROTOCOL_VERSION
|
|
34
45
|
packet.created_at.CopyFrom(ts)
|
|
@@ -36,17 +47,18 @@ def handshake_payload(
|
|
|
36
47
|
handshake_pb2.Handshake(
|
|
37
48
|
component_id=component_id,
|
|
38
49
|
role=handshake_pb2.COMPONENT_ROLE_WORKER,
|
|
39
|
-
supported_versions=
|
|
50
|
+
supported_versions=versions,
|
|
40
51
|
capabilities=dict(capabilities or {}),
|
|
41
52
|
ready_topics=list(ready_topics or []),
|
|
42
53
|
agent_name=sanitize_agent_name(agent_name),
|
|
43
54
|
)
|
|
44
55
|
)
|
|
45
|
-
|
|
56
|
+
outgoing = finalize_packet(packet, session_token=session_token)
|
|
57
|
+
return outgoing.SerializeToString(deterministic=True)
|
|
46
58
|
|
|
47
59
|
|
|
48
60
|
async def publish_handshake(
|
|
49
|
-
nc,
|
|
61
|
+
nc: Publisher,
|
|
50
62
|
component_id: str,
|
|
51
63
|
capabilities: Optional[Mapping[str, bool]] = None,
|
|
52
64
|
*,
|
|
@@ -55,6 +67,8 @@ async def publish_handshake(
|
|
|
55
67
|
supported_versions: Optional[Sequence[int]] = None,
|
|
56
68
|
ready_topics: Optional[Sequence[str]] = None,
|
|
57
69
|
agent_name: str = "",
|
|
70
|
+
trace_id: Optional[str] = None,
|
|
71
|
+
session_token: Optional[str] = None,
|
|
58
72
|
) -> None:
|
|
59
73
|
"""Publish one worker handshake packet to the CAP handshake subject."""
|
|
60
74
|
payload = handshake_payload(
|
|
@@ -64,14 +78,11 @@ async def publish_handshake(
|
|
|
64
78
|
supported_versions=supported_versions,
|
|
65
79
|
ready_topics=ready_topics,
|
|
66
80
|
agent_name=agent_name,
|
|
81
|
+
trace_id=trace_id,
|
|
82
|
+
session_token=session_token,
|
|
67
83
|
)
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
packet.ClearField("signature")
|
|
73
|
-
unsigned_data = packet.SerializeToString(deterministic=True)
|
|
74
|
-
packet.signature = private_key.sign(unsigned_data, ec.ECDSA(hashes.SHA256()))
|
|
75
|
-
data = packet.SerializeToString(deterministic=True)
|
|
76
|
-
|
|
84
|
+
packet = finalize_packet(
|
|
85
|
+
parse_packet(payload), private_key, session_token=session_token
|
|
86
|
+
)
|
|
87
|
+
data = packet.SerializeToString(deterministic=True)
|
|
77
88
|
await nc.publish(SUBJECT_HANDSHAKE, data)
|
cap/heartbeat.py
CHANGED
|
@@ -7,13 +7,13 @@ import asyncio
|
|
|
7
7
|
import logging
|
|
8
8
|
from typing import Callable, Optional
|
|
9
9
|
|
|
10
|
-
from cryptography.hazmat.primitives import hashes
|
|
11
10
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
12
11
|
from google.protobuf import timestamp_pb2
|
|
13
12
|
|
|
14
13
|
from cap.client import DEFAULT_PROTOCOL_VERSION
|
|
15
|
-
from cap.metrics import MetricsHook
|
|
14
|
+
from cap.metrics import MetricsHook, safe_metrics_call
|
|
16
15
|
from cap.pb.cordum.agent.v1 import buspacket_pb2, heartbeat_pb2
|
|
16
|
+
from cap.packet_boundary import Publisher, finalize_packet, parse_packet
|
|
17
17
|
from cap.subjects import SUBJECT_HEARTBEAT
|
|
18
18
|
|
|
19
19
|
_logger = logging.getLogger("cap.heartbeat")
|
|
@@ -41,6 +41,8 @@ def heartbeat_payload(
|
|
|
41
41
|
cpu_load: float,
|
|
42
42
|
auth_token: str = "",
|
|
43
43
|
agent_name: str = "",
|
|
44
|
+
*,
|
|
45
|
+
session_token: Optional[str] = None,
|
|
44
46
|
) -> bytes:
|
|
45
47
|
"""Build a heartbeat payload with CPU utilization only."""
|
|
46
48
|
return heartbeat_payload_with_progress(
|
|
@@ -51,6 +53,7 @@ def heartbeat_payload(
|
|
|
51
53
|
cpu_load=cpu_load,
|
|
52
54
|
auth_token=auth_token,
|
|
53
55
|
agent_name=agent_name,
|
|
56
|
+
session_token=session_token,
|
|
54
57
|
)
|
|
55
58
|
|
|
56
59
|
|
|
@@ -63,6 +66,8 @@ def heartbeat_payload_with_memory(
|
|
|
63
66
|
memory_load: float,
|
|
64
67
|
auth_token: str = "",
|
|
65
68
|
agent_name: str = "",
|
|
69
|
+
*,
|
|
70
|
+
session_token: Optional[str] = None,
|
|
66
71
|
) -> bytes:
|
|
67
72
|
"""Build a heartbeat payload including memory utilization."""
|
|
68
73
|
return heartbeat_payload_with_progress(
|
|
@@ -74,6 +79,7 @@ def heartbeat_payload_with_memory(
|
|
|
74
79
|
memory_load=memory_load,
|
|
75
80
|
auth_token=auth_token,
|
|
76
81
|
agent_name=agent_name,
|
|
82
|
+
session_token=session_token,
|
|
77
83
|
)
|
|
78
84
|
|
|
79
85
|
|
|
@@ -88,6 +94,8 @@ def heartbeat_payload_with_progress(
|
|
|
88
94
|
last_memo: str = "",
|
|
89
95
|
auth_token: str = "",
|
|
90
96
|
agent_name: str = "",
|
|
97
|
+
*,
|
|
98
|
+
session_token: Optional[str] = None,
|
|
91
99
|
) -> bytes:
|
|
92
100
|
"""Build a heartbeat payload including optional progress fields."""
|
|
93
101
|
ts = timestamp_pb2.Timestamp()
|
|
@@ -95,6 +103,7 @@ def heartbeat_payload_with_progress(
|
|
|
95
103
|
auth_token = auth_token.strip()
|
|
96
104
|
|
|
97
105
|
packet = buspacket_pb2.BusPacket()
|
|
106
|
+
packet.trace_id = worker_id
|
|
98
107
|
packet.sender_id = worker_id
|
|
99
108
|
packet.protocol_version = DEFAULT_PROTOCOL_VERSION
|
|
100
109
|
packet.created_at.CopyFrom(ts)
|
|
@@ -112,34 +121,54 @@ def heartbeat_payload_with_progress(
|
|
|
112
121
|
agent_name=sanitize_agent_name(agent_name),
|
|
113
122
|
)
|
|
114
123
|
)
|
|
115
|
-
|
|
124
|
+
outgoing = finalize_packet(packet, session_token=session_token)
|
|
125
|
+
return outgoing.SerializeToString(deterministic=True)
|
|
116
126
|
|
|
117
127
|
|
|
118
128
|
async def emit_heartbeat(
|
|
119
|
-
nc,
|
|
129
|
+
nc: Publisher,
|
|
120
130
|
payload: bytes,
|
|
121
131
|
private_key: Optional[ec.EllipticCurvePrivateKey] = None,
|
|
132
|
+
*,
|
|
133
|
+
session_token: Optional[str] = None,
|
|
122
134
|
) -> None:
|
|
123
135
|
"""Publish one heartbeat packet to the heartbeat subject."""
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
packet.ClearField("signature")
|
|
129
|
-
unsigned_data = packet.SerializeToString(deterministic=True)
|
|
130
|
-
packet.signature = private_key.sign(unsigned_data, ec.ECDSA(hashes.SHA256()))
|
|
131
|
-
data = packet.SerializeToString(deterministic=True)
|
|
132
|
-
|
|
136
|
+
packet = finalize_packet(
|
|
137
|
+
parse_packet(payload), private_key, session_token=session_token
|
|
138
|
+
)
|
|
139
|
+
data = packet.SerializeToString(deterministic=True)
|
|
133
140
|
await nc.publish(SUBJECT_HEARTBEAT, data)
|
|
134
141
|
|
|
135
142
|
|
|
143
|
+
async def _wait_interval(
|
|
144
|
+
interval: float,
|
|
145
|
+
cancel_event: Optional[asyncio.Event],
|
|
146
|
+
) -> bool:
|
|
147
|
+
if cancel_event is None:
|
|
148
|
+
await asyncio.sleep(interval)
|
|
149
|
+
return False
|
|
150
|
+
sleep_task = asyncio.create_task(asyncio.sleep(interval))
|
|
151
|
+
cancel_task = asyncio.create_task(cancel_event.wait())
|
|
152
|
+
done, pending = await asyncio.wait(
|
|
153
|
+
{sleep_task, cancel_task},
|
|
154
|
+
return_when=asyncio.FIRST_COMPLETED,
|
|
155
|
+
)
|
|
156
|
+
for task in pending:
|
|
157
|
+
task.cancel()
|
|
158
|
+
if pending:
|
|
159
|
+
await asyncio.gather(*pending, return_exceptions=True)
|
|
160
|
+
return cancel_task in done and cancel_event.is_set()
|
|
161
|
+
|
|
162
|
+
|
|
136
163
|
async def heartbeat_loop(
|
|
137
|
-
nc,
|
|
164
|
+
nc: Publisher,
|
|
138
165
|
payload_fn: Callable[[], bytes],
|
|
139
166
|
interval: float = 5.0,
|
|
140
167
|
private_key: Optional[ec.EllipticCurvePrivateKey] = None,
|
|
141
|
-
metrics: MetricsHook
|
|
142
|
-
cancel_event: asyncio.Event
|
|
168
|
+
metrics: Optional[MetricsHook] = None,
|
|
169
|
+
cancel_event: Optional[asyncio.Event] = None,
|
|
170
|
+
*,
|
|
171
|
+
session_token: Optional[str] = None,
|
|
143
172
|
) -> None:
|
|
144
173
|
"""Emit heartbeat packets periodically until cancelled."""
|
|
145
174
|
sleep_interval = max(0.0, interval)
|
|
@@ -147,33 +176,24 @@ async def heartbeat_loop(
|
|
|
147
176
|
while True:
|
|
148
177
|
if cancel_event is not None and cancel_event.is_set():
|
|
149
178
|
return
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
await asyncio.sleep(sleep_interval)
|
|
153
|
-
else:
|
|
154
|
-
sleep_task = asyncio.create_task(asyncio.sleep(sleep_interval))
|
|
155
|
-
cancel_task = asyncio.create_task(cancel_event.wait())
|
|
156
|
-
done, pending = await asyncio.wait(
|
|
157
|
-
{sleep_task, cancel_task},
|
|
158
|
-
return_when=asyncio.FIRST_COMPLETED,
|
|
159
|
-
)
|
|
160
|
-
|
|
161
|
-
for task in pending:
|
|
162
|
-
task.cancel()
|
|
163
|
-
if pending:
|
|
164
|
-
await asyncio.gather(*pending, return_exceptions=True)
|
|
165
|
-
|
|
166
|
-
if cancel_task in done and cancel_event.is_set():
|
|
167
|
-
return
|
|
179
|
+
if await _wait_interval(sleep_interval, cancel_event):
|
|
180
|
+
return
|
|
168
181
|
|
|
169
182
|
try:
|
|
170
183
|
payload = payload_fn()
|
|
171
|
-
await emit_heartbeat(
|
|
184
|
+
await emit_heartbeat(
|
|
185
|
+
nc=nc,
|
|
186
|
+
payload=payload,
|
|
187
|
+
private_key=private_key,
|
|
188
|
+
session_token=session_token,
|
|
189
|
+
)
|
|
172
190
|
if metrics is not None:
|
|
173
191
|
packet = buspacket_pb2.BusPacket()
|
|
174
192
|
packet.ParseFromString(payload)
|
|
175
193
|
worker_id = packet.heartbeat.worker_id or packet.sender_id
|
|
176
|
-
|
|
194
|
+
safe_metrics_call(
|
|
195
|
+
_logger, lambda: metrics.on_heartbeat_sent(worker_id)
|
|
196
|
+
)
|
|
177
197
|
except asyncio.CancelledError:
|
|
178
198
|
raise
|
|
179
199
|
except Exception:
|
cap/metrics.py
CHANGED
|
@@ -5,7 +5,22 @@ StatsD, OpenTelemetry, or any other metrics system.
|
|
|
5
5
|
The default is NoopMetrics which has zero overhead.
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Callable, Protocol
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def safe_metrics_call(logger: logging.Logger, callback: Callable[[], None]) -> None:
|
|
13
|
+
"""Run noncritical metrics code without letting it control job delivery."""
|
|
14
|
+
try:
|
|
15
|
+
callback()
|
|
16
|
+
except Exception as exc:
|
|
17
|
+
try:
|
|
18
|
+
logger.warning(
|
|
19
|
+
"metrics hook failed",
|
|
20
|
+
extra={"exception_type": type(exc).__name__},
|
|
21
|
+
)
|
|
22
|
+
except Exception:
|
|
23
|
+
pass
|
|
9
24
|
|
|
10
25
|
|
|
11
26
|
class MetricsHook(Protocol):
|
cap/packet_boundary.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
"""Shared validation and signing boundary for CAP bus packets."""
|
|
2
|
+
|
|
3
|
+
import logging
|
|
4
|
+
from typing import Dict, Optional, Protocol
|
|
5
|
+
|
|
6
|
+
from cryptography.exceptions import InvalidSignature
|
|
7
|
+
from cryptography.hazmat.primitives import hashes
|
|
8
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
9
|
+
from google.protobuf.message import DecodeError
|
|
10
|
+
|
|
11
|
+
from cap.errors import InvalidInputError, MalformedPacketError, SignatureInvalidError
|
|
12
|
+
from cap.pb.cordum.agent.v1 import buspacket_pb2
|
|
13
|
+
from cap.validate import validate_bus_packet
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
PublicKeyMap = Dict[str, ec.EllipticCurvePublicKey]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Publisher(Protocol):
|
|
20
|
+
async def publish(self, subject: str, data: bytes) -> None: ...
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def parse_packet(payload: bytes) -> buspacket_pb2.BusPacket:
|
|
24
|
+
"""Parse a bus packet or raise a typed malformed-packet error."""
|
|
25
|
+
packet = buspacket_pb2.BusPacket()
|
|
26
|
+
try:
|
|
27
|
+
packet.ParseFromString(payload)
|
|
28
|
+
except (DecodeError, TypeError, ValueError) as exc:
|
|
29
|
+
raise MalformedPacketError(str(exc)) from exc
|
|
30
|
+
return packet
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def validate_packet(packet: buspacket_pb2.BusPacket) -> None:
|
|
34
|
+
"""Raise before a malformed envelope crosses a security boundary."""
|
|
35
|
+
errors = validate_bus_packet(packet)
|
|
36
|
+
if not errors:
|
|
37
|
+
return
|
|
38
|
+
details = "; ".join(f"{error.field}: {error.message}" for error in errors)
|
|
39
|
+
raise InvalidInputError(f"invalid BusPacket: {details}")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _attach_session_token(
|
|
43
|
+
packet: buspacket_pb2.BusPacket,
|
|
44
|
+
session_token: Optional[str],
|
|
45
|
+
) -> bool:
|
|
46
|
+
if session_token is None:
|
|
47
|
+
return False
|
|
48
|
+
if not isinstance(session_token, str):
|
|
49
|
+
raise TypeError("session_token must be a string or None")
|
|
50
|
+
previous = packet.auth_token
|
|
51
|
+
if session_token:
|
|
52
|
+
packet.auth_token = session_token
|
|
53
|
+
else:
|
|
54
|
+
packet.ClearField("auth_token")
|
|
55
|
+
return bool(packet.auth_token != previous)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def finalize_packet(
|
|
59
|
+
packet: buspacket_pb2.BusPacket,
|
|
60
|
+
private_key: Optional[ec.EllipticCurvePrivateKey] = None,
|
|
61
|
+
*,
|
|
62
|
+
session_token: Optional[str] = None,
|
|
63
|
+
) -> buspacket_pb2.BusPacket:
|
|
64
|
+
"""Clone, attach session proof, validate, then optionally sign a packet."""
|
|
65
|
+
outgoing = buspacket_pb2.BusPacket()
|
|
66
|
+
outgoing.CopyFrom(packet)
|
|
67
|
+
token_changed = _attach_session_token(outgoing, session_token)
|
|
68
|
+
validate_packet(outgoing)
|
|
69
|
+
if token_changed and outgoing.signature and private_key is None:
|
|
70
|
+
raise InvalidInputError("session token change requires re-signing the packet")
|
|
71
|
+
if private_key is None:
|
|
72
|
+
return outgoing
|
|
73
|
+
if not isinstance(private_key, ec.EllipticCurvePrivateKey):
|
|
74
|
+
raise InvalidInputError("packet signing requires an elliptic-curve private key")
|
|
75
|
+
outgoing.ClearField("signature")
|
|
76
|
+
unsigned = outgoing.SerializeToString(deterministic=True)
|
|
77
|
+
outgoing.signature = private_key.sign(unsigned, ec.ECDSA(hashes.SHA256()))
|
|
78
|
+
return outgoing
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def verify_packet(
|
|
82
|
+
packet: buspacket_pb2.BusPacket,
|
|
83
|
+
public_keys: Optional[PublicKeyMap],
|
|
84
|
+
logger: logging.Logger,
|
|
85
|
+
) -> bool:
|
|
86
|
+
"""Verify a configured sender key; ``None`` alone selects legacy mode."""
|
|
87
|
+
if public_keys is None:
|
|
88
|
+
return True
|
|
89
|
+
safe_sender = _safe_log_field(packet.sender_id)
|
|
90
|
+
if not packet.sender_id or not packet.signature:
|
|
91
|
+
_safe_warning(
|
|
92
|
+
logger, "missing signed sender identity", extra={"sender_id": safe_sender}
|
|
93
|
+
)
|
|
94
|
+
return False
|
|
95
|
+
public_key = public_keys.get(packet.sender_id)
|
|
96
|
+
if public_key is None or not isinstance(public_key, ec.EllipticCurvePublicKey):
|
|
97
|
+
_safe_warning(
|
|
98
|
+
logger, "no valid public key found", extra={"sender_id": safe_sender}
|
|
99
|
+
)
|
|
100
|
+
return False
|
|
101
|
+
unsigned = buspacket_pb2.BusPacket()
|
|
102
|
+
unsigned.CopyFrom(packet)
|
|
103
|
+
signature = unsigned.signature
|
|
104
|
+
unsigned.ClearField("signature")
|
|
105
|
+
try:
|
|
106
|
+
public_key.verify(
|
|
107
|
+
signature,
|
|
108
|
+
unsigned.SerializeToString(deterministic=True),
|
|
109
|
+
ec.ECDSA(hashes.SHA256()),
|
|
110
|
+
)
|
|
111
|
+
except (InvalidSignature, TypeError, ValueError, AttributeError):
|
|
112
|
+
error = SignatureInvalidError(f"sender {safe_sender}")
|
|
113
|
+
_safe_warning(
|
|
114
|
+
logger,
|
|
115
|
+
"invalid signature: %s",
|
|
116
|
+
error,
|
|
117
|
+
extra={"sender_id": safe_sender},
|
|
118
|
+
)
|
|
119
|
+
return False
|
|
120
|
+
return True
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def decode_packet(
|
|
124
|
+
payload: bytes,
|
|
125
|
+
public_keys: Optional[PublicKeyMap],
|
|
126
|
+
logger: logging.Logger,
|
|
127
|
+
) -> Optional[buspacket_pb2.BusPacket]:
|
|
128
|
+
"""Parse and validate before attempting signature verification."""
|
|
129
|
+
try:
|
|
130
|
+
packet = parse_packet(payload)
|
|
131
|
+
validate_packet(packet)
|
|
132
|
+
except (MalformedPacketError, InvalidInputError) as exc:
|
|
133
|
+
_safe_warning(logger, "invalid packet: %s", exc)
|
|
134
|
+
return None
|
|
135
|
+
if not verify_packet(packet, public_keys, logger):
|
|
136
|
+
return None
|
|
137
|
+
return packet
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _safe_warning(
|
|
141
|
+
logger: logging.Logger,
|
|
142
|
+
message: str,
|
|
143
|
+
*args: object,
|
|
144
|
+
extra: Optional[Dict[str, str]] = None,
|
|
145
|
+
) -> None:
|
|
146
|
+
try:
|
|
147
|
+
logger.warning(message, *args, extra=extra)
|
|
148
|
+
except Exception:
|
|
149
|
+
# Diagnostics must not turn rejected traffic into a handler failure.
|
|
150
|
+
pass
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _safe_log_field(value: str, limit: int = 256) -> str:
|
|
154
|
+
safe = value.replace("\r", "\\r").replace("\n", "\\n")
|
|
155
|
+
return safe if len(safe) <= limit else safe[: limit - 3] + "..."
|