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/worker.py
CHANGED
|
@@ -1,144 +1,295 @@
|
|
|
1
1
|
import asyncio
|
|
2
2
|
import logging
|
|
3
3
|
import time
|
|
4
|
-
from
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from typing import Awaitable, Callable, Dict, Optional, Protocol, Sequence
|
|
5
6
|
|
|
6
7
|
from google.protobuf import timestamp_pb2
|
|
7
8
|
|
|
8
9
|
from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
|
|
9
10
|
from cryptography.hazmat.primitives.asymmetric import ec
|
|
10
|
-
from cryptography.hazmat.primitives import hashes
|
|
11
11
|
|
|
12
12
|
from cap.subjects import SUBJECT_RESULT
|
|
13
|
-
from cap.errors import MalformedPacketError, SignatureInvalidError
|
|
14
13
|
from cap.constants import DEFAULT_PROTOCOL_VERSION
|
|
15
|
-
from cap.metrics import MetricsHook, NoopMetrics
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
14
|
+
from cap.metrics import MetricsHook, NoopMetrics, safe_metrics_call
|
|
15
|
+
from cap.packet_boundary import (
|
|
16
|
+
decode_packet,
|
|
17
|
+
finalize_packet,
|
|
18
|
+
verify_packet as _verify_packet,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
_HANDLER_FAILED_MESSAGE = "handler failed"
|
|
23
|
+
_LOG_FIELD_LIMIT = 256
|
|
24
|
+
JobHandler = Callable[[job_pb2.JobRequest], Awaitable[job_pb2.JobResult]]
|
|
25
|
+
Middleware = Callable[[job_pb2.JobRequest, JobHandler], Awaitable[job_pb2.JobResult]]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class _Message(Protocol):
|
|
29
|
+
data: bytes
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _NATSConnection(Protocol):
|
|
33
|
+
async def publish(self, subject: str, data: bytes) -> None: ...
|
|
34
|
+
async def subscribe(self, subject: str, *, queue: str,
|
|
35
|
+
cb: Callable[[_Message], Awaitable[None]]) -> object: ...
|
|
36
|
+
async def drain(self) -> None: ...
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
ConnectFn = Callable[..., Awaitable[_NATSConnection]]
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class _WorkerContext:
|
|
43
|
+
connection: _NATSConnection
|
|
44
|
+
handler: JobHandler
|
|
45
|
+
public_keys: Optional[Dict[str, ec.EllipticCurvePublicKey]]
|
|
46
|
+
private_key: Optional[ec.EllipticCurvePrivateKey]
|
|
47
|
+
sender_id: str
|
|
48
|
+
middlewares: Optional[Sequence[Middleware]]
|
|
49
|
+
logger: logging.Logger
|
|
50
|
+
metrics: MetricsHook
|
|
51
|
+
session_token: Optional[str]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _bounded_log_field(value: str) -> str:
|
|
55
|
+
sanitized = value.replace("\r", "\\r").replace("\n", "\\n")
|
|
56
|
+
if len(sanitized) <= _LOG_FIELD_LIMIT:
|
|
57
|
+
return sanitized
|
|
58
|
+
return sanitized[: _LOG_FIELD_LIMIT - 3] + "..."
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _decode_packet(message: _Message, context: _WorkerContext) -> Optional[buspacket_pb2.BusPacket]:
|
|
62
|
+
return decode_packet(message.data, context.public_keys, context.logger)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _middleware_chain(handler: JobHandler, middlewares: Optional[Sequence[Middleware]]) -> JobHandler:
|
|
66
|
+
wrapped = handler
|
|
67
|
+
if not middlewares:
|
|
68
|
+
return wrapped
|
|
69
|
+
for middleware in reversed(middlewares):
|
|
70
|
+
next_handler = wrapped
|
|
71
|
+
|
|
72
|
+
async def invoke(
|
|
73
|
+
request: job_pb2.JobRequest,
|
|
74
|
+
current: Middleware = middleware,
|
|
75
|
+
following: JobHandler = next_handler,
|
|
76
|
+
) -> job_pb2.JobResult:
|
|
77
|
+
return await current(request, following)
|
|
78
|
+
|
|
79
|
+
wrapped = invoke
|
|
80
|
+
return wrapped
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _log_handler_failure(
|
|
84
|
+
context: _WorkerContext,
|
|
85
|
+
packet: buspacket_pb2.BusPacket,
|
|
86
|
+
request: job_pb2.JobRequest,
|
|
87
|
+
error: Exception,
|
|
88
|
+
) -> None:
|
|
89
|
+
try:
|
|
90
|
+
context.logger.warning(
|
|
91
|
+
"job handler failed",
|
|
92
|
+
extra={
|
|
93
|
+
"job_id": _bounded_log_field(request.job_id),
|
|
94
|
+
"trace_id": _bounded_log_field(packet.trace_id),
|
|
95
|
+
"exception_type": _bounded_log_field(type(error).__name__),
|
|
96
|
+
},
|
|
97
|
+
)
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _failed_result(job_id: str, message: str) -> job_pb2.JobResult:
|
|
103
|
+
return job_pb2.JobResult(
|
|
104
|
+
job_id=job_id,
|
|
105
|
+
status=job_pb2.JOB_STATUS_FAILED,
|
|
106
|
+
error_message=message,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
async def _execute_handler(
|
|
111
|
+
context: _WorkerContext,
|
|
112
|
+
packet: buspacket_pb2.BusPacket,
|
|
113
|
+
request: job_pb2.JobRequest,
|
|
114
|
+
) -> job_pb2.JobResult:
|
|
115
|
+
wrapped = _middleware_chain(context.handler, context.middlewares)
|
|
116
|
+
try:
|
|
117
|
+
result = await wrapped(request)
|
|
118
|
+
except asyncio.CancelledError:
|
|
119
|
+
raise
|
|
120
|
+
except (KeyboardInterrupt, SystemExit):
|
|
121
|
+
raise
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
_log_handler_failure(context, packet, request, exc)
|
|
124
|
+
return _failed_result(request.job_id, _HANDLER_FAILED_MESSAGE)
|
|
125
|
+
if result is None:
|
|
126
|
+
return _failed_result(request.job_id, "handler returned null")
|
|
127
|
+
return result
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _normalize_result(
|
|
131
|
+
result: job_pb2.JobResult,
|
|
132
|
+
request: job_pb2.JobRequest,
|
|
133
|
+
sender_id: str,
|
|
134
|
+
) -> None:
|
|
135
|
+
if not result.job_id:
|
|
136
|
+
result.job_id = request.job_id
|
|
137
|
+
if not result.worker_id:
|
|
138
|
+
result.worker_id = sender_id
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _result_packet(
|
|
142
|
+
source: buspacket_pb2.BusPacket,
|
|
143
|
+
result: job_pb2.JobResult,
|
|
144
|
+
sender_id: str,
|
|
145
|
+
private_key: Optional[ec.EllipticCurvePrivateKey],
|
|
146
|
+
*,
|
|
147
|
+
session_token: Optional[str] = None,
|
|
148
|
+
) -> buspacket_pb2.BusPacket:
|
|
149
|
+
timestamp = timestamp_pb2.Timestamp()
|
|
150
|
+
timestamp.GetCurrentTime()
|
|
151
|
+
packet = buspacket_pb2.BusPacket(
|
|
152
|
+
trace_id=source.trace_id,
|
|
153
|
+
sender_id=sender_id,
|
|
154
|
+
protocol_version=DEFAULT_PROTOCOL_VERSION,
|
|
155
|
+
)
|
|
156
|
+
packet.created_at.CopyFrom(timestamp)
|
|
157
|
+
packet.job_result.CopyFrom(result)
|
|
158
|
+
return finalize_packet(packet, private_key, session_token=session_token)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
async def _handle_message(message: _Message, context: _WorkerContext) -> None:
|
|
162
|
+
packet = _decode_packet(message, context)
|
|
163
|
+
if packet is None:
|
|
164
|
+
return
|
|
165
|
+
request = packet.job_request
|
|
166
|
+
if not request.job_id:
|
|
167
|
+
return
|
|
168
|
+
safe_metrics_call(
|
|
169
|
+
context.logger,
|
|
170
|
+
lambda: context.metrics.on_job_received(request.job_id, request.topic),
|
|
171
|
+
)
|
|
172
|
+
started_at = time.monotonic()
|
|
173
|
+
result = await _execute_handler(context, packet, request)
|
|
174
|
+
elapsed_ms = int((time.monotonic() - started_at) * 1000)
|
|
175
|
+
_normalize_result(result, request, context.sender_id)
|
|
176
|
+
outgoing = _result_packet(
|
|
177
|
+
packet,
|
|
178
|
+
result,
|
|
179
|
+
context.sender_id,
|
|
180
|
+
context.private_key,
|
|
181
|
+
session_token=context.session_token,
|
|
182
|
+
)
|
|
183
|
+
await context.connection.publish(
|
|
184
|
+
SUBJECT_RESULT, outgoing.SerializeToString(deterministic=True)
|
|
185
|
+
)
|
|
186
|
+
if result.status == job_pb2.JOB_STATUS_FAILED:
|
|
187
|
+
metric = lambda: context.metrics.on_job_failed(
|
|
188
|
+
result.job_id, result.error_message
|
|
189
|
+
)
|
|
190
|
+
else:
|
|
191
|
+
metric = lambda: context.metrics.on_job_completed(
|
|
192
|
+
result.job_id, elapsed_ms, "SUCCEEDED"
|
|
193
|
+
)
|
|
194
|
+
safe_metrics_call(context.logger, metric)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _log_cleanup_failure(logger: logging.Logger, error: BaseException) -> None:
|
|
198
|
+
try:
|
|
199
|
+
logger.error(
|
|
200
|
+
"worker connection drain failed",
|
|
201
|
+
extra={"exception_type": _bounded_log_field(type(error).__name__)},
|
|
202
|
+
)
|
|
203
|
+
except BaseException:
|
|
204
|
+
# Cleanup diagnostics must never replace the operation's primary error.
|
|
205
|
+
pass
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _warn_static_session_token(logger: logging.Logger) -> None:
|
|
209
|
+
try:
|
|
210
|
+
logger.warning(
|
|
211
|
+
"run_worker session_token is static compatibility only; "
|
|
212
|
+
"use Agent worker trust for authenticated renewal"
|
|
213
|
+
)
|
|
214
|
+
except Exception:
|
|
215
|
+
pass
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
async def _drain_connection(
|
|
219
|
+
connection: _NATSConnection,
|
|
220
|
+
logger: logging.Logger,
|
|
221
|
+
primary_error: Optional[BaseException],
|
|
222
|
+
) -> None:
|
|
223
|
+
try:
|
|
224
|
+
await connection.drain()
|
|
225
|
+
except BaseException as exc:
|
|
226
|
+
if primary_error is None:
|
|
227
|
+
raise
|
|
228
|
+
_log_cleanup_failure(logger, exc)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
async def _serve(
|
|
232
|
+
connection: _NATSConnection,
|
|
233
|
+
subject: str,
|
|
234
|
+
callback: Callable[[_Message], Awaitable[None]],
|
|
235
|
+
logger: logging.Logger,
|
|
236
|
+
) -> None:
|
|
237
|
+
primary_error: Optional[BaseException] = None
|
|
238
|
+
try:
|
|
239
|
+
await connection.subscribe(subject, queue=subject, cb=callback)
|
|
240
|
+
while True:
|
|
241
|
+
await asyncio.sleep(1)
|
|
242
|
+
except BaseException as exc:
|
|
243
|
+
primary_error = exc
|
|
244
|
+
raise
|
|
245
|
+
finally:
|
|
246
|
+
await _drain_connection(connection, logger, primary_error)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
async def run_worker(
|
|
250
|
+
nats_url: str,
|
|
251
|
+
subject: str,
|
|
252
|
+
handler: JobHandler,
|
|
253
|
+
public_keys: Optional[Dict[str, ec.EllipticCurvePublicKey]] = None,
|
|
254
|
+
private_key: Optional[ec.EllipticCurvePrivateKey] = None,
|
|
255
|
+
sender_id: str = "cap-worker",
|
|
256
|
+
connect_fn: Optional[ConnectFn] = None,
|
|
257
|
+
middlewares: Optional[Sequence[Middleware]] = None,
|
|
258
|
+
logger: Optional[logging.Logger] = None,
|
|
259
|
+
metrics: Optional[MetricsHook] = None,
|
|
260
|
+
*,
|
|
261
|
+
session_token: Optional[str] = None,
|
|
262
|
+
) -> None:
|
|
263
|
+
"""Run the legacy worker helper until cancelled, then drain NATS.
|
|
264
|
+
|
|
265
|
+
``session_token`` is static caller-managed compatibility, not trust lifecycle.
|
|
266
|
+
Use :class:`cap.runtime.Agent` for authenticated minting and renewal.
|
|
43
267
|
"""
|
|
44
268
|
if logger is None:
|
|
45
269
|
logger = logging.getLogger("cap.worker")
|
|
270
|
+
if session_token:
|
|
271
|
+
_warn_static_session_token(logger)
|
|
46
272
|
if metrics is None:
|
|
47
273
|
metrics = NoopMetrics()
|
|
48
|
-
|
|
49
|
-
# Allow injection for tests; defaults to nats.connect.
|
|
50
274
|
if connect_fn is None:
|
|
51
275
|
try:
|
|
52
276
|
import nats # type: ignore
|
|
53
277
|
except ImportError as exc:
|
|
54
278
|
raise RuntimeError("nats-py is required to connect to NATS") from exc
|
|
55
279
|
connect_fn = nats.connect
|
|
280
|
+
connection = await connect_fn(servers=nats_url, name=sender_id)
|
|
281
|
+
context = _WorkerContext(
|
|
282
|
+
connection=connection,
|
|
283
|
+
handler=handler,
|
|
284
|
+
public_keys=public_keys,
|
|
285
|
+
private_key=private_key,
|
|
286
|
+
sender_id=sender_id,
|
|
287
|
+
middlewares=middlewares,
|
|
288
|
+
logger=logger,
|
|
289
|
+
metrics=metrics,
|
|
290
|
+
session_token=session_token,
|
|
291
|
+
)
|
|
292
|
+
async def on_msg(message: _Message) -> None:
|
|
293
|
+
await _handle_message(message, context)
|
|
56
294
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
async def on_msg(msg):
|
|
60
|
-
packet = buspacket_pb2.BusPacket()
|
|
61
|
-
try:
|
|
62
|
-
packet.ParseFromString(msg.data)
|
|
63
|
-
except Exception as exc:
|
|
64
|
-
logger.warning("%s", MalformedPacketError(str(exc)))
|
|
65
|
-
return
|
|
66
|
-
|
|
67
|
-
if public_keys:
|
|
68
|
-
public_key = public_keys.get(packet.sender_id)
|
|
69
|
-
if not public_key:
|
|
70
|
-
logger.warning("no public key found", extra={"sender_id": packet.sender_id})
|
|
71
|
-
return
|
|
72
|
-
|
|
73
|
-
signature = packet.signature
|
|
74
|
-
packet.ClearField("signature")
|
|
75
|
-
unsigned_data = packet.SerializeToString(deterministic=True)
|
|
76
|
-
packet.signature = signature
|
|
77
|
-
try:
|
|
78
|
-
public_key.verify(signature, unsigned_data, ec.ECDSA(hashes.SHA256()))
|
|
79
|
-
except Exception:
|
|
80
|
-
logger.warning("invalid signature: %s", SignatureInvalidError(f"sender {packet.sender_id}"), extra={"sender_id": packet.sender_id})
|
|
81
|
-
return
|
|
82
|
-
|
|
83
|
-
req = packet.job_request
|
|
84
|
-
if not req.job_id:
|
|
85
|
-
return
|
|
86
|
-
metrics.on_job_received(req.job_id, req.topic)
|
|
87
|
-
start_time = time.monotonic()
|
|
88
|
-
# Apply middleware chain
|
|
89
|
-
wrapped = handler
|
|
90
|
-
if middlewares:
|
|
91
|
-
for mw in reversed(middlewares):
|
|
92
|
-
_next = wrapped
|
|
93
|
-
wrapped = (lambda m, n: (lambda r: m(r, n)))(mw, _next)
|
|
94
|
-
try:
|
|
95
|
-
res = await wrapped(req)
|
|
96
|
-
if res is None:
|
|
97
|
-
res = job_pb2.JobResult(
|
|
98
|
-
job_id=req.job_id,
|
|
99
|
-
status=job_pb2.JOB_STATUS_FAILED,
|
|
100
|
-
error_message="handler returned null",
|
|
101
|
-
)
|
|
102
|
-
except (KeyboardInterrupt, SystemExit):
|
|
103
|
-
raise # Let critical signals propagate
|
|
104
|
-
except Exception as exc:
|
|
105
|
-
# Top-level job handler: catch all to prevent worker crash.
|
|
106
|
-
# Individual exceptions are already handled in the call chain;
|
|
107
|
-
# this catches anything unexpected so the worker stays alive.
|
|
108
|
-
self.logger.warning("job handler failed: %s", exc, exc_info=True)
|
|
109
|
-
res = job_pb2.JobResult(
|
|
110
|
-
job_id=req.job_id,
|
|
111
|
-
status=job_pb2.JOB_STATUS_FAILED,
|
|
112
|
-
error_message=str(exc),
|
|
113
|
-
)
|
|
114
|
-
if not res.job_id:
|
|
115
|
-
res.job_id = req.job_id
|
|
116
|
-
if not res.worker_id:
|
|
117
|
-
res.worker_id = sender_id
|
|
118
|
-
elapsed_ms = int((time.monotonic() - start_time) * 1000)
|
|
119
|
-
if res.status == job_pb2.JOB_STATUS_FAILED:
|
|
120
|
-
metrics.on_job_failed(res.job_id, res.error_message)
|
|
121
|
-
else:
|
|
122
|
-
metrics.on_job_completed(res.job_id, elapsed_ms, "SUCCEEDED")
|
|
123
|
-
ts = timestamp_pb2.Timestamp()
|
|
124
|
-
ts.GetCurrentTime()
|
|
125
|
-
out = buspacket_pb2.BusPacket()
|
|
126
|
-
out.trace_id = packet.trace_id
|
|
127
|
-
out.sender_id = sender_id
|
|
128
|
-
out.protocol_version = DEFAULT_PROTOCOL_VERSION
|
|
129
|
-
out.created_at.CopyFrom(ts)
|
|
130
|
-
out.job_result.CopyFrom(res)
|
|
131
|
-
|
|
132
|
-
if private_key:
|
|
133
|
-
unsigned_data = out.SerializeToString(deterministic=True)
|
|
134
|
-
signature = private_key.sign(unsigned_data, ec.ECDSA(hashes.SHA256()))
|
|
135
|
-
out.signature = signature
|
|
136
|
-
|
|
137
|
-
await nc.publish(SUBJECT_RESULT, out.SerializeToString(deterministic=True))
|
|
138
|
-
|
|
139
|
-
await nc.subscribe(subject, queue=subject, cb=on_msg)
|
|
140
|
-
try:
|
|
141
|
-
while True:
|
|
142
|
-
await asyncio.sleep(1)
|
|
143
|
-
finally:
|
|
144
|
-
await nc.drain()
|
|
295
|
+
await _serve(connection, subject, on_msg, logger)
|
cap/worker_trust.py
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Authenticated worker trust-handshake client API and immutable models."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from datetime import datetime, timedelta, timezone
|
|
5
|
+
from enum import Enum
|
|
6
|
+
from types import MappingProxyType
|
|
7
|
+
from typing import Mapping
|
|
8
|
+
|
|
9
|
+
from cryptography.hazmat.primitives.asymmetric import ec
|
|
10
|
+
|
|
11
|
+
from cap.pb.cordum.agent.v1 import buspacket_pb2, handshake_pb2
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
WORKER_HANDSHAKE_AUDIENCE = "cordum-scheduler"
|
|
15
|
+
WORKER_HANDSHAKE_PROTOCOL_VERSION = 1
|
|
16
|
+
WORKER_HANDSHAKE_NONCE_SIZE = 32
|
|
17
|
+
WORKER_HANDSHAKE_MAX_PACKET_SIZE = 64 * 1024
|
|
18
|
+
WORKER_HANDSHAKE_MAX_IDENTITY_LENGTH = 256
|
|
19
|
+
WORKER_HANDSHAKE_MAX_SESSION_TOKEN_SIZE = 16 * 1024
|
|
20
|
+
WORKER_HANDSHAKE_MAX_SKEW = timedelta(minutes=1)
|
|
21
|
+
WORKER_HANDSHAKE_MAX_LIFETIME = timedelta(minutes=1)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class WorkerTrustMode(str, Enum):
|
|
25
|
+
"""Admission policy after an authenticated handshake failure."""
|
|
26
|
+
|
|
27
|
+
OFF = "off"
|
|
28
|
+
WARN = "warn"
|
|
29
|
+
ENFORCE = "enforce"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class WorkerTrustError(ValueError):
|
|
33
|
+
"""Base class for worker-trust client failures."""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class WorkerTrustModeError(WorkerTrustError):
|
|
37
|
+
"""Raised for an unknown or implicit trust mode."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class WorkerTrustConfigError(WorkerTrustError):
|
|
41
|
+
"""Raised for partial or unsafe trust configuration."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class WorkerHandshakePacketError(WorkerTrustError):
|
|
45
|
+
"""Raised for a malformed trust packet."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class WorkerHandshakeBindingError(WorkerTrustError):
|
|
49
|
+
"""Raised when authenticated correlation differs."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class WorkerHandshakeExpiredError(WorkerTrustError):
|
|
53
|
+
"""Raised when a signed packet falls outside its validity window."""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class WorkerHandshakeRejectionError(WorkerTrustError):
|
|
57
|
+
"""Opaque scheduler rejection carrying only the protocol reason enum."""
|
|
58
|
+
|
|
59
|
+
def __init__(self, reason: int) -> None:
|
|
60
|
+
super().__init__("worker handshake rejected")
|
|
61
|
+
self.reason = reason
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class WorkerTrustConfig:
|
|
66
|
+
worker_id: str
|
|
67
|
+
expected_agent_id: str
|
|
68
|
+
tenant_id: str
|
|
69
|
+
audience: str
|
|
70
|
+
proof_key_id: str
|
|
71
|
+
proof_private_key: ec.EllipticCurvePrivateKey
|
|
72
|
+
expected_scheduler_id: str
|
|
73
|
+
scheduler_public_keys: Mapping[str, ec.EllipticCurvePublicKey]
|
|
74
|
+
sdk_version: str
|
|
75
|
+
|
|
76
|
+
def __post_init__(self) -> None:
|
|
77
|
+
source = self.scheduler_public_keys
|
|
78
|
+
copied = MappingProxyType(dict(source)) if isinstance(source, Mapping) else MappingProxyType({})
|
|
79
|
+
object.__setattr__(self, "scheduler_public_keys", copied)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class WorkerHandshakeRequestOptions:
|
|
84
|
+
request_id: str
|
|
85
|
+
trace_id: str
|
|
86
|
+
purpose: int
|
|
87
|
+
client_nonce: bytes
|
|
88
|
+
created_at: datetime
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class WorkerHandshakeSession:
|
|
93
|
+
token: str
|
|
94
|
+
issued_at: datetime
|
|
95
|
+
expires_at: datetime
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True, init=False)
|
|
99
|
+
class VerifiedWorkerHandshakeChallenge:
|
|
100
|
+
"""Opaque scheduler-authenticated challenge with defensive-copy access."""
|
|
101
|
+
|
|
102
|
+
_request_bytes: bytes
|
|
103
|
+
_response_bytes: bytes
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def _create(cls, request, response):
|
|
107
|
+
value = object.__new__(cls)
|
|
108
|
+
object.__setattr__(value, "_request_bytes", _serialize(request))
|
|
109
|
+
object.__setattr__(value, "_response_bytes", _serialize(response))
|
|
110
|
+
return value
|
|
111
|
+
|
|
112
|
+
def message(self) -> handshake_pb2.WorkerHandshakeChallenge:
|
|
113
|
+
return _verified_packets(self)[1].worker_handshake_challenge
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def parse_worker_trust_mode(raw: str) -> WorkerTrustMode:
|
|
117
|
+
"""Parse only explicit off, warn, or enforce values."""
|
|
118
|
+
|
|
119
|
+
normalized = raw.strip().lower() if isinstance(raw, str) else ""
|
|
120
|
+
try:
|
|
121
|
+
return WorkerTrustMode(normalized)
|
|
122
|
+
except ValueError as exc:
|
|
123
|
+
raise WorkerTrustModeError("invalid worker trust mode: {!r}".format(raw)) from exc
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def validate_worker_trust_config(config: WorkerTrustConfig) -> None:
|
|
127
|
+
"""Reject partial identities and unpinned/non-P256 trust roots."""
|
|
128
|
+
|
|
129
|
+
if not isinstance(config, WorkerTrustConfig):
|
|
130
|
+
raise WorkerTrustConfigError("worker trust configuration is required")
|
|
131
|
+
values = (
|
|
132
|
+
config.worker_id, config.expected_agent_id, config.tenant_id,
|
|
133
|
+
config.audience, config.proof_key_id, config.expected_scheduler_id,
|
|
134
|
+
config.sdk_version,
|
|
135
|
+
)
|
|
136
|
+
if not all(_canonical_text(value) for value in values):
|
|
137
|
+
raise WorkerTrustConfigError("worker trust identity is invalid")
|
|
138
|
+
if config.audience != WORKER_HANDSHAKE_AUDIENCE:
|
|
139
|
+
raise WorkerTrustConfigError("worker trust audience is invalid")
|
|
140
|
+
_require_p256_private(config.proof_private_key)
|
|
141
|
+
if not config.scheduler_public_keys:
|
|
142
|
+
raise WorkerTrustConfigError("scheduler trust keys are required")
|
|
143
|
+
for key_id, key in config.scheduler_public_keys.items():
|
|
144
|
+
if not _canonical_text(key_id):
|
|
145
|
+
raise WorkerTrustConfigError("scheduler key ID is invalid")
|
|
146
|
+
_require_p256_public(key)
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _verified_packets(verified):
|
|
150
|
+
if not isinstance(verified, VerifiedWorkerHandshakeChallenge):
|
|
151
|
+
raise WorkerHandshakeBindingError("challenge is unverified")
|
|
152
|
+
request = buspacket_pb2.BusPacket.FromString(verified._request_bytes)
|
|
153
|
+
response = buspacket_pb2.BusPacket.FromString(verified._response_bytes)
|
|
154
|
+
return request, response
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _timestamp_datetime(value, field):
|
|
158
|
+
try:
|
|
159
|
+
value.ToDatetime()
|
|
160
|
+
return value.ToDatetime(tzinfo=timezone.utc)
|
|
161
|
+
except (AttributeError, ValueError, OverflowError) as exc:
|
|
162
|
+
raise WorkerHandshakePacketError("{} is invalid".format(field)) from exc
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _utc(value):
|
|
166
|
+
if not isinstance(value, datetime) or value.tzinfo is None:
|
|
167
|
+
raise WorkerHandshakePacketError("timestamp must be timezone-aware")
|
|
168
|
+
return value.astimezone(timezone.utc)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _canonical_text(value):
|
|
172
|
+
return (isinstance(value, str) and
|
|
173
|
+
0 < len(value) <= WORKER_HANDSHAKE_MAX_IDENTITY_LENGTH and
|
|
174
|
+
all(0x21 <= ord(char) <= 0x7e for char in value))
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _valid_session_token(value):
|
|
178
|
+
return (isinstance(value, str) and
|
|
179
|
+
0 < len(value) <= WORKER_HANDSHAKE_MAX_SESSION_TOKEN_SIZE and
|
|
180
|
+
all(0x21 <= ord(char) <= 0x7e for char in value))
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _require_p256_private(key):
|
|
184
|
+
if (not isinstance(key, ec.EllipticCurvePrivateKey) or
|
|
185
|
+
not isinstance(key.curve, ec.SECP256R1)):
|
|
186
|
+
raise WorkerTrustConfigError("worker proof key must use P-256")
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _require_p256_public(key):
|
|
190
|
+
if (not isinstance(key, ec.EllipticCurvePublicKey) or
|
|
191
|
+
not isinstance(key.curve, ec.SECP256R1)):
|
|
192
|
+
raise WorkerTrustConfigError("scheduler trust key must use P-256")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _serialize(packet):
|
|
196
|
+
return packet.SerializeToString(deterministic=True)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _p256_algorithm():
|
|
200
|
+
return handshake_pb2.WORKER_HANDSHAKE_PROOF_ALGORITHM_ECDSA_P256_SHA256
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _issue_purpose():
|
|
204
|
+
return handshake_pb2.WORKER_HANDSHAKE_PURPOSE_ISSUE
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _renew_purpose():
|
|
208
|
+
return handshake_pb2.WORKER_HANDSHAKE_PURPOSE_RENEW
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
from cap.worker_trust_build import build_authenticate, build_challenge_request # noqa: E402
|
|
212
|
+
from cap.worker_trust_verify import verify_challenge, verify_result # noqa: E402
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
__all__ = [
|
|
216
|
+
"WORKER_HANDSHAKE_AUDIENCE", "WorkerHandshakeBindingError",
|
|
217
|
+
"WorkerHandshakeExpiredError", "WorkerHandshakePacketError",
|
|
218
|
+
"WorkerHandshakeRejectionError", "WorkerHandshakeRequestOptions",
|
|
219
|
+
"WorkerHandshakeSession", "WorkerTrustConfig", "WorkerTrustConfigError",
|
|
220
|
+
"WorkerTrustError", "WorkerTrustMode", "WorkerTrustModeError",
|
|
221
|
+
"build_authenticate", "build_challenge_request", "parse_worker_trust_mode",
|
|
222
|
+
"validate_worker_trust_config", "verify_challenge", "verify_result",
|
|
223
|
+
]
|