cap-sdk-python 2.6.1__tar.gz → 2.8.4__tar.gz

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 (52) hide show
  1. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/PKG-INFO +8 -1
  2. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/README.md +7 -0
  3. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/client.py +1 -2
  4. cap_sdk_python-2.8.4/cap/constants.py +3 -0
  5. cap_sdk_python-2.8.4/cap/pb/cordum/agent/v1/alert_pb2.py +50 -0
  6. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/heartbeat_pb2.py +2 -2
  7. cap_sdk_python-2.8.4/cap/pb/cordum/agent/v1/safety_pb2.py +68 -0
  8. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/runtime.py +118 -3
  9. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/testing.py +2 -3
  10. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/validate.py +32 -0
  11. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/worker.py +8 -3
  12. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap_sdk_python.egg-info/PKG-INFO +8 -1
  13. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap_sdk_python.egg-info/SOURCES.txt +2 -0
  14. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/pyproject.toml +1 -1
  15. cap_sdk_python-2.8.4/tests/test_redis_tls.py +154 -0
  16. cap_sdk_python-2.6.1/cap/pb/cordum/agent/v1/alert_pb2.py +0 -44
  17. cap_sdk_python-2.6.1/cap/pb/cordum/agent/v1/safety_pb2.py +0 -68
  18. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/__init__.py +0 -0
  19. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/bus.py +0 -0
  20. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/errors.py +0 -0
  21. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/heartbeat.py +0 -0
  22. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/metrics.py +0 -0
  23. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/middleware.py +0 -0
  24. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/__init__.py +0 -0
  25. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/__init__.py +0 -0
  26. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/__init__.py +0 -0
  27. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/__init__.py +0 -0
  28. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/alert_pb2_grpc.py +0 -0
  29. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/buspacket_pb2.py +0 -0
  30. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/buspacket_pb2_grpc.py +0 -0
  31. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/handshake_pb2.py +0 -0
  32. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/handshake_pb2_grpc.py +0 -0
  33. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/heartbeat_pb2_grpc.py +0 -0
  34. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/job_pb2.py +0 -0
  35. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/job_pb2_grpc.py +0 -0
  36. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/pb/cordum/agent/v1/safety_pb2_grpc.py +0 -0
  37. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/progress.py +0 -0
  38. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap/subjects.py +0 -0
  39. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap_sdk_python.egg-info/dependency_links.txt +0 -0
  40. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap_sdk_python.egg-info/requires.txt +0 -0
  41. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/cap_sdk_python.egg-info/top_level.txt +0 -0
  42. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/setup.cfg +0 -0
  43. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_conformance.py +0 -0
  44. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_errors.py +0 -0
  45. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_heartbeat.py +0 -0
  46. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_metrics.py +0 -0
  47. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_middleware.py +0 -0
  48. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_progress.py +0 -0
  49. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_runtime.py +0 -0
  50. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_sdk.py +0 -0
  51. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_testing.py +0 -0
  52. {cap_sdk_python-2.6.1 → cap_sdk_python-2.8.4}/tests/test_validate.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cap-sdk-python
3
- Version: 2.6.1
3
+ Version: 2.8.4
4
4
  Summary: CAP (Cordum Agent Protocol) Python SDK
5
5
  Author-email: Cordum <eng@cordum.io>
6
6
  License-Expression: Apache-2.0
@@ -168,6 +168,13 @@ agent.use(timing)
168
168
  Middleware executes in registration order (FIFO). Each can inspect context,
169
169
  measure timing, or short-circuit by returning without calling `next_fn`.
170
170
 
171
+ ### Redis TLS
172
+ The Python SDK provides `redis_ssl_context_from_env()` to build an `SSLContext` for secure Redis connections. It reads:
173
+ - `REDIS_TLS_CA` (or `SSL_CERT_FILE` fallback): Path to CA certificate.
174
+ - `REDIS_TLS_CERT` / `REDIS_TLS_KEY`: Path to client certificate/key pair.
175
+ - `REDIS_TLS_SERVER_NAME`: SNI server name override.
176
+ - `REDIS_TLS_INSECURE`: Set to `1` or `true` to skip certificate verification (dev only).
177
+
171
178
  ### Environment
172
179
  - `NATS_URL` (default `nats://127.0.0.1:4222`)
173
180
  - `REDIS_URL` (default `redis://127.0.0.1:6379/0`)
@@ -147,6 +147,13 @@ agent.use(timing)
147
147
  Middleware executes in registration order (FIFO). Each can inspect context,
148
148
  measure timing, or short-circuit by returning without calling `next_fn`.
149
149
 
150
+ ### Redis TLS
151
+ The Python SDK provides `redis_ssl_context_from_env()` to build an `SSLContext` for secure Redis connections. It reads:
152
+ - `REDIS_TLS_CA` (or `SSL_CERT_FILE` fallback): Path to CA certificate.
153
+ - `REDIS_TLS_CERT` / `REDIS_TLS_KEY`: Path to client certificate/key pair.
154
+ - `REDIS_TLS_SERVER_NAME`: SNI server name override.
155
+ - `REDIS_TLS_INSECURE`: Set to `1` or `true` to skip certificate verification (dev only).
156
+
150
157
  ### Environment
151
158
  - `NATS_URL` (default `nats://127.0.0.1:4222`)
152
159
  - `REDIS_URL` (default `redis://127.0.0.1:6379/0`)
@@ -5,10 +5,9 @@ from cryptography.hazmat.primitives import hashes
5
5
  from typing import Optional
6
6
 
7
7
 
8
+ from cap.constants import DEFAULT_PROTOCOL_VERSION
8
9
  from cap.subjects import SUBJECT_SUBMIT
9
10
 
10
- DEFAULT_PROTOCOL_VERSION = 1
11
-
12
11
 
13
12
  async def submit_job(
14
13
  nc,
@@ -0,0 +1,3 @@
1
+ """Shared constants for the CAP Python SDK."""
2
+
3
+ DEFAULT_PROTOCOL_VERSION = 1
@@ -0,0 +1,50 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: cordum/agent/v1/alert.proto
5
+ # Protobuf Python Version: 6.31.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 6,
15
+ 31,
16
+ 1,
17
+ '',
18
+ 'cordum/agent/v1/alert.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from cordum.agent.v1 import job_pb2 as cordum_dot_agent_dot_v1_dot_job__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x63ordum/agent/v1/alert.proto\x12\x0f\x63ordum.agent.v1\x1a\x19\x63ordum/agent/v1/job.proto\"\xd9\x02\n\x0bSystemAlert\x12\x11\n\x05level\x18\x01 \x01(\tB\x02\x18\x01\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x15\n\tcomponent\x18\x03 \x01(\tB\x02\x18\x01\x12\x10\n\x04\x63ode\x18\x04 \x01(\tB\x02\x18\x01\x12\x30\n\x08severity\x18\x05 \x01(\x0e\x32\x1e.cordum.agent.v1.AlertSeverity\x12\x33\n\x0f\x65rror_code_enum\x18\x06 \x01(\x0e\x32\x1a.cordum.agent.v1.ErrorCode\x12\x18\n\x10source_component\x18\x07 \x01(\t\x12:\n\x07\x64\x65tails\x18\x08 \x03(\x0b\x32).cordum.agent.v1.SystemAlert.DetailsEntry\x12\x10\n\x08trace_id\x18\t \x01(\t\x1a.\n\x0c\x44\x65tailsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x9b\x01\n\rAlertSeverity\x12\x1e\n\x1a\x41LERT_SEVERITY_UNSPECIFIED\x10\x00\x12\x17\n\x13\x41LERT_SEVERITY_INFO\x10\x01\x12\x1a\n\x16\x41LERT_SEVERITY_WARNING\x10\x02\x12\x18\n\x14\x41LERT_SEVERITY_ERROR\x10\x03\x12\x1b\n\x17\x41LERT_SEVERITY_CRITICAL\x10\x04\x42\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'cordum.agent.v1.alert_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'\n\026io.cordum.cap.agent.v1P\001Z+github.com/cordum-io/cap/v2/cordum/agent/v1\252\002\017Cordum.Agent.V1\312\002\017cordum\\Agent\\V1\352\002\021Cordum::Agent::V1'
36
+ _globals['_SYSTEMALERT_DETAILSENTRY']._loaded_options = None
37
+ _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_options = b'8\001'
38
+ _globals['_SYSTEMALERT'].fields_by_name['level']._loaded_options = None
39
+ _globals['_SYSTEMALERT'].fields_by_name['level']._serialized_options = b'\030\001'
40
+ _globals['_SYSTEMALERT'].fields_by_name['component']._loaded_options = None
41
+ _globals['_SYSTEMALERT'].fields_by_name['component']._serialized_options = b'\030\001'
42
+ _globals['_SYSTEMALERT'].fields_by_name['code']._loaded_options = None
43
+ _globals['_SYSTEMALERT'].fields_by_name['code']._serialized_options = b'\030\001'
44
+ _globals['_ALERTSEVERITY']._serialized_start=424
45
+ _globals['_ALERTSEVERITY']._serialized_end=579
46
+ _globals['_SYSTEMALERT']._serialized_start=76
47
+ _globals['_SYSTEMALERT']._serialized_end=421
48
+ _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_start=375
49
+ _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_end=421
50
+ # @@protoc_insertion_point(module_scope)
@@ -24,7 +24,7 @@ _sym_db = _symbol_database.Default()
24
24
 
25
25
 
26
26
 
27
- DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1f\x63ordum/agent/v1/heartbeat.proto\x12\x0f\x63ordum.agent.v1\"\xe0\x02\n\tHeartbeat\x12\x11\n\tworker_id\x18\x01 \x01(\t\x12\x0e\n\x06region\x18\x02 \x01(\t\x12\x0c\n\x04type\x18\x03 \x01(\t\x12\x10\n\x08\x63pu_load\x18\x04 \x01(\x02\x12\x17\n\x0fgpu_utilization\x18\x05 \x01(\x02\x12\x13\n\x0b\x61\x63tive_jobs\x18\x06 \x01(\x05\x12\x14\n\x0c\x63\x61pabilities\x18\x07 \x03(\t\x12\x0c\n\x04pool\x18\x0b \x01(\t\x12\x19\n\x11max_parallel_jobs\x18\x0c \x01(\x05\x12\x36\n\x06labels\x18\r \x03(\x0b\x32&.cordum.agent.v1.Heartbeat.LabelsEntry\x12\x13\n\x0bmemory_load\x18\x0e \x01(\x02\x12\x14\n\x0cprogress_pct\x18\x0f \x01(\x05\x12\x11\n\tlast_memo\x18\x10 \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1f\x63ordum/agent/v1/heartbeat.proto\x12\x0f\x63ordum.agent.v1\"\xf2\x02\n\tHeartbeat\x12\x11\n\tworker_id\x18\x01 \x01(\t\x12\x0e\n\x06region\x18\x02 \x01(\t\x12\x0c\n\x04type\x18\x03 \x01(\t\x12\x10\n\x08\x63pu_load\x18\x04 \x01(\x02\x12\x17\n\x0fgpu_utilization\x18\x05 \x01(\x02\x12\x13\n\x0b\x61\x63tive_jobs\x18\x06 \x01(\x05\x12\x14\n\x0c\x63\x61pabilities\x18\x07 \x03(\t\x12\x0c\n\x04pool\x18\x0b \x01(\t\x12\x19\n\x11max_parallel_jobs\x18\x0c \x01(\x05\x12\x36\n\x06labels\x18\r \x03(\x0b\x32&.cordum.agent.v1.Heartbeat.LabelsEntry\x12\x13\n\x0bmemory_load\x18\x0e \x01(\x02\x12\x14\n\x0cprogress_pct\x18\x0f \x01(\x05\x12\x11\n\tlast_memo\x18\x10 \x01(\t\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01J\x04\x08\x08\x10\tJ\x04\x08\t\x10\nJ\x04\x08\n\x10\x0b\x42\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
28
28
 
29
29
  _globals = globals()
30
30
  _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
@@ -35,7 +35,7 @@ if not _descriptor._USE_C_DESCRIPTORS:
35
35
  _globals['_HEARTBEAT_LABELSENTRY']._loaded_options = None
36
36
  _globals['_HEARTBEAT_LABELSENTRY']._serialized_options = b'8\001'
37
37
  _globals['_HEARTBEAT']._serialized_start=53
38
- _globals['_HEARTBEAT']._serialized_end=405
38
+ _globals['_HEARTBEAT']._serialized_end=423
39
39
  _globals['_HEARTBEAT_LABELSENTRY']._serialized_start=360
40
40
  _globals['_HEARTBEAT_LABELSENTRY']._serialized_end=405
41
41
  # @@protoc_insertion_point(module_scope)
@@ -0,0 +1,68 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: cordum/agent/v1/safety.proto
5
+ # Protobuf Python Version: 6.31.1
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 6,
15
+ 31,
16
+ 1,
17
+ '',
18
+ 'cordum/agent/v1/safety.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+ from cordum.agent.v1 import job_pb2 as cordum_dot_agent_dot_v1_dot_job__pb2
26
+
27
+
28
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1c\x63ordum/agent/v1/safety.proto\x12\x0f\x63ordum.agent.v1\x1a\x19\x63ordum/agent/v1/job.proto\"\xe0\x03\n\x12PolicyCheckRequest\x12\x0e\n\x06job_id\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12\x0e\n\x06tenant\x18\x03 \x01(\t\x12.\n\x08priority\x18\x04 \x01(\x0e\x32\x1c.cordum.agent.v1.JobPriority\x12\x16\n\x0e\x65stimated_cost\x18\x05 \x01(\x01\x12\'\n\x06\x62udget\x18\x06 \x01(\x0b\x32\x17.cordum.agent.v1.Budget\x12\x14\n\x0cprincipal_id\x18\x07 \x01(\t\x12?\n\x06labels\x18\x08 \x03(\x0b\x32/.cordum.agent.v1.PolicyCheckRequest.LabelsEntry\x12\x11\n\tmemory_id\x18\t \x01(\t\x12\x18\n\x10\x65\x66\x66\x65\x63tive_config\x18\n \x01(\x0c\x12*\n\x04meta\x18\x0b \x01(\x0b\x32\x1c.cordum.agent.v1.JobMetadata\x12\x15\n\rinput_content\x18\x14 \x01(\x0c\x12\x1a\n\x12input_content_type\x18\x15 \x01(\t\x12\x18\n\x10input_size_bytes\x18\x16 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"y\n\x11\x42udgetConstraints\x12\x16\n\x0emax_runtime_ms\x18\x01 \x01(\x03\x12\x13\n\x0bmax_retries\x18\x02 \x01(\x05\x12\x1a\n\x12max_artifact_bytes\x18\x03 \x01(\x03\x12\x1b\n\x13max_concurrent_jobs\x18\x04 \x01(\x05\"j\n\x0eSandboxProfile\x12\x10\n\x08isolated\x18\x01 \x01(\x08\x12\x19\n\x11network_allowlist\x18\x02 \x03(\t\x12\x14\n\x0c\x66s_read_only\x18\x03 \x03(\t\x12\x15\n\rfs_read_write\x18\x04 \x03(\t\"G\n\x14ToolchainConstraints\x12\x15\n\rallowed_tools\x18\x01 \x03(\t\x12\x18\n\x10\x61llowed_commands\x18\x02 \x03(\t\"P\n\x0f\x44iffConstraints\x12\x11\n\tmax_files\x18\x01 \x01(\x05\x12\x11\n\tmax_lines\x18\x02 \x01(\x05\x12\x17\n\x0f\x64\x65ny_path_globs\x18\x03 \x03(\t\"\xfd\x01\n\x11PolicyConstraints\x12\x33\n\x07\x62udgets\x18\x01 \x01(\x0b\x32\".cordum.agent.v1.BudgetConstraints\x12\x30\n\x07sandbox\x18\x02 \x01(\x0b\x32\x1f.cordum.agent.v1.SandboxProfile\x12\x38\n\ttoolchain\x18\x03 \x01(\x0b\x32%.cordum.agent.v1.ToolchainConstraints\x12.\n\x04\x64iff\x18\x04 \x01(\x0b\x32 .cordum.agent.v1.DiffConstraints\x12\x17\n\x0fredaction_level\x18\x05 \x01(\t\"\x8a\x02\n\x11PolicyRemediation\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05title\x18\x02 \x01(\t\x12\x0f\n\x07summary\x18\x03 \x01(\t\x12\x19\n\x11replacement_topic\x18\x04 \x01(\t\x12\x1e\n\x16replacement_capability\x18\x05 \x01(\t\x12\x45\n\nadd_labels\x18\x06 \x03(\x0b\x32\x31.cordum.agent.v1.PolicyRemediation.AddLabelsEntry\x12\x15\n\rremove_labels\x18\x07 \x03(\t\x1a\x30\n\x0e\x41\x64\x64LabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xc2\x02\n\x13PolicyCheckResponse\x12/\n\x08\x64\x65\x63ision\x18\x01 \x01(\x0e\x32\x1d.cordum.agent.v1.DecisionType\x12\x0e\n\x06reason\x18\x02 \x01(\t\x12\x1c\n\x14redacted_context_ptr\x18\x03 \x01(\t\x12\x17\n\x0fpolicy_snapshot\x18\x04 \x01(\t\x12\x0f\n\x07rule_id\x18\x05 \x01(\t\x12\x37\n\x0b\x63onstraints\x18\x06 \x01(\x0b\x32\".cordum.agent.v1.PolicyConstraints\x12\x19\n\x11\x61pproval_required\x18\x07 \x01(\x08\x12\x14\n\x0c\x61pproval_ref\x18\x08 \x01(\t\x12\x38\n\x0cremediations\x18\t \x03(\x0b\x32\".cordum.agent.v1.PolicyRemediation\"\x16\n\x14ListSnapshotsRequest\"*\n\x15ListSnapshotsResponse\x12\x11\n\tsnapshots\x18\x01 \x03(\t*\xc5\x01\n\x0c\x44\x65\x63isionType\x12\x1d\n\x19\x44\x45\x43ISION_TYPE_UNSPECIFIED\x10\x00\x12\x17\n\x13\x44\x45\x43ISION_TYPE_ALLOW\x10\x01\x12\x16\n\x12\x44\x45\x43ISION_TYPE_DENY\x10\x02\x12\x1f\n\x1b\x44\x45\x43ISION_TYPE_REQUIRE_HUMAN\x10\x03\x12\x1a\n\x16\x44\x45\x43ISION_TYPE_THROTTLE\x10\x04\x12(\n$DECISION_TYPE_ALLOW_WITH_CONSTRAINTS\x10\x05\x32\xc6\x03\n\x0cSafetyKernel\x12R\n\x05\x43heck\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12U\n\x08\x45valuate\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12T\n\x07\x45xplain\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12U\n\x08Simulate\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12^\n\rListSnapshots\x12%.cordum.agent.v1.ListSnapshotsRequest\x1a&.cordum.agent.v1.ListSnapshotsResponseB\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
29
+
30
+ _globals = globals()
31
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'cordum.agent.v1.safety_pb2', _globals)
33
+ if not _descriptor._USE_C_DESCRIPTORS:
34
+ _globals['DESCRIPTOR']._loaded_options = None
35
+ _globals['DESCRIPTOR']._serialized_options = b'\n\026io.cordum.cap.agent.v1P\001Z+github.com/cordum-io/cap/v2/cordum/agent/v1\252\002\017Cordum.Agent.V1\312\002\017cordum\\Agent\\V1\352\002\021Cordum::Agent::V1'
36
+ _globals['_POLICYCHECKREQUEST_LABELSENTRY']._loaded_options = None
37
+ _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_options = b'8\001'
38
+ _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._loaded_options = None
39
+ _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_options = b'8\001'
40
+ _globals['_DECISIONTYPE']._serialized_start=1864
41
+ _globals['_DECISIONTYPE']._serialized_end=2061
42
+ _globals['_POLICYCHECKREQUEST']._serialized_start=77
43
+ _globals['_POLICYCHECKREQUEST']._serialized_end=557
44
+ _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_start=512
45
+ _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_end=557
46
+ _globals['_BUDGETCONSTRAINTS']._serialized_start=559
47
+ _globals['_BUDGETCONSTRAINTS']._serialized_end=680
48
+ _globals['_SANDBOXPROFILE']._serialized_start=682
49
+ _globals['_SANDBOXPROFILE']._serialized_end=788
50
+ _globals['_TOOLCHAINCONSTRAINTS']._serialized_start=790
51
+ _globals['_TOOLCHAINCONSTRAINTS']._serialized_end=861
52
+ _globals['_DIFFCONSTRAINTS']._serialized_start=863
53
+ _globals['_DIFFCONSTRAINTS']._serialized_end=943
54
+ _globals['_POLICYCONSTRAINTS']._serialized_start=946
55
+ _globals['_POLICYCONSTRAINTS']._serialized_end=1199
56
+ _globals['_POLICYREMEDIATION']._serialized_start=1202
57
+ _globals['_POLICYREMEDIATION']._serialized_end=1468
58
+ _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_start=1420
59
+ _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_end=1468
60
+ _globals['_POLICYCHECKRESPONSE']._serialized_start=1471
61
+ _globals['_POLICYCHECKRESPONSE']._serialized_end=1793
62
+ _globals['_LISTSNAPSHOTSREQUEST']._serialized_start=1795
63
+ _globals['_LISTSNAPSHOTSREQUEST']._serialized_end=1817
64
+ _globals['_LISTSNAPSHOTSRESPONSE']._serialized_start=1819
65
+ _globals['_LISTSNAPSHOTSRESPONSE']._serialized_end=1861
66
+ _globals['_SAFETYKERNEL']._serialized_start=2064
67
+ _globals['_SAFETYKERNEL']._serialized_end=2518
68
+ # @@protoc_insertion_point(module_scope)
@@ -28,7 +28,7 @@ from cap.errors import InvalidInputError, MalformedPacketError, SignatureInvalid
28
28
  from cap.metrics import MetricsHook, NoopMetrics
29
29
  from cap.heartbeat import heartbeat_loop, heartbeat_payload
30
30
 
31
- DEFAULT_PROTOCOL_VERSION = 1
31
+ from cap.constants import DEFAULT_PROTOCOL_VERSION # noqa: E402 — must be after conditional imports
32
32
 
33
33
 
34
34
  class BlobStore(Protocol):
@@ -44,13 +44,105 @@ class BlobStore(Protocol):
44
44
  ...
45
45
 
46
46
 
47
+ def redis_ssl_context_from_env() -> Optional["ssl.SSLContext"]:
48
+ """Build an :class:`ssl.SSLContext` from ``REDIS_TLS_*`` env vars.
49
+
50
+ Matches the Go SDK's ``RedisTLSConfigFromEnv()`` pattern. Supports:
51
+
52
+ * ``REDIS_TLS_CA`` (or ``SSL_CERT_FILE`` fallback) -- CA certificate path
53
+ * ``REDIS_TLS_CERT`` + ``REDIS_TLS_KEY`` -- client certificate pair
54
+ * ``REDIS_TLS_SERVER_NAME`` -- SNI override
55
+ * ``REDIS_TLS_INSECURE`` -- skip certificate verification (dev/test only)
56
+
57
+ Returns ``None`` when no TLS env vars are set.
58
+ """
59
+ import ssl as _ssl
60
+
61
+ ca_path = (os.environ.get("REDIS_TLS_CA") or os.environ.get("SSL_CERT_FILE") or "").strip()
62
+ cert_path = os.environ.get("REDIS_TLS_CERT", "").strip()
63
+ key_path = os.environ.get("REDIS_TLS_KEY", "").strip()
64
+ server_name = os.environ.get("REDIS_TLS_SERVER_NAME", "").strip()
65
+ insecure = os.environ.get("REDIS_TLS_INSECURE", "").strip().lower() in ("1", "true")
66
+
67
+ if not ca_path and not cert_path and not key_path and not server_name and not insecure:
68
+ return None
69
+
70
+ if bool(cert_path) != bool(key_path):
71
+ raise ValueError("REDIS_TLS_CERT and REDIS_TLS_KEY must be set together")
72
+
73
+ if insecure:
74
+ ssl_ctx = _ssl.SSLContext(_ssl.PROTOCOL_TLS_CLIENT)
75
+ ssl_ctx.minimum_version = _ssl.TLSVersion.TLSv1_2
76
+ ssl_ctx.check_hostname = False
77
+ ssl_ctx.verify_mode = _ssl.CERT_NONE
78
+ logging.getLogger("cap.runtime").warning("REDIS_TLS_INSECURE enabled, skipping certificate verification")
79
+ elif ca_path:
80
+ if not os.path.isfile(ca_path):
81
+ raise FileNotFoundError(f"REDIS_TLS_CA file not found: {ca_path}")
82
+ ssl_ctx = _ssl.create_default_context(cafile=ca_path)
83
+ ssl_ctx.minimum_version = _ssl.TLSVersion.TLSv1_2
84
+ else:
85
+ ssl_ctx = _ssl.create_default_context()
86
+ ssl_ctx.minimum_version = _ssl.TLSVersion.TLSv1_2
87
+
88
+ if cert_path and key_path:
89
+ if not os.path.isfile(cert_path):
90
+ raise FileNotFoundError(f"REDIS_TLS_CERT file not found: {cert_path}")
91
+ if not os.path.isfile(key_path):
92
+ raise FileNotFoundError(f"REDIS_TLS_KEY file not found: {key_path}")
93
+ ssl_ctx.load_cert_chain(cert_path, key_path)
94
+
95
+ if server_name:
96
+ ssl_ctx.check_hostname = True
97
+ ssl_ctx.server_hostname = server_name # type: ignore[attr-defined]
98
+
99
+ return ssl_ctx
100
+
101
+
102
+ def _redis_tls_kwargs(redis_url: str) -> dict:
103
+ """Build TLS kwargs for redis-py 7+ from environment variables.
104
+
105
+ Uses ssl_ca_certs/ssl_certfile/ssl_keyfile kwargs (not ssl=SSLContext)
106
+ because redis-py 7 does not accept SSLContext via from_url().
107
+ """
108
+ kwargs: dict = {}
109
+ if redis_url.startswith("rediss://"):
110
+ ca = os.environ.get("REDIS_TLS_CA", "").strip()
111
+ cert = os.environ.get("REDIS_TLS_CERT", "").strip()
112
+ key = os.environ.get("REDIS_TLS_KEY", "").strip()
113
+ if ca:
114
+ kwargs["ssl_ca_certs"] = ca
115
+ if cert:
116
+ kwargs["ssl_certfile"] = cert
117
+ if key:
118
+ kwargs["ssl_keyfile"] = key
119
+ return kwargs
120
+
121
+
122
+ async def ping_redis(redis_url: str) -> None:
123
+ """Connect to Redis and run PING to verify auth and TLS at startup.
124
+
125
+ Raises on failure so connection issues surface immediately instead of
126
+ silently failing on the first blob store read/write.
127
+ """
128
+ if redis_async is None:
129
+ raise RuntimeError("redis is required")
130
+ kwargs = _redis_tls_kwargs(redis_url)
131
+ client = redis_async.from_url(redis_url, **kwargs)
132
+ try:
133
+ await client.ping()
134
+ finally:
135
+ await client.close()
136
+
137
+
47
138
  class RedisBlobStore:
48
139
  """Redis-backed :class:`BlobStore` implementation."""
49
140
 
50
141
  def __init__(self, redis_url: str) -> None:
51
142
  if redis_async is None:
52
143
  raise RuntimeError("redis is required for RedisBlobStore")
53
- self._client = redis_async.from_url(redis_url)
144
+ kwargs = _redis_tls_kwargs(redis_url)
145
+ self._client = redis_async.from_url(redis_url, **kwargs)
54
146
 
55
147
  async def get(self, key: str) -> Optional[bytes]:
56
148
  value = await self._client.get(key)
@@ -258,7 +350,16 @@ class Agent:
258
350
  self._store = RedisBlobStore(self._redis_url)
259
351
 
260
352
  for topic, spec in self._handlers.items():
261
- await self._nc.subscribe(topic, queue=topic, cb=lambda msg, s=spec: asyncio.create_task(self._on_msg(msg, s)))
353
+ async def _on_topic_msg(msg, s=spec):
354
+ asyncio.create_task(self._on_msg(msg, s))
355
+ await self._nc.subscribe(topic, queue=topic, cb=_on_topic_msg)
356
+
357
+ # Subscribe to direct worker subject (worker.<id>.jobs) for scheduler dispatch
358
+ if self._sender_id:
359
+ direct_subject = f"worker.{self._sender_id}.jobs"
360
+ async def _direct_cb(msg):
361
+ asyncio.create_task(self._on_direct_msg(msg))
362
+ await self._nc.subscribe(direct_subject, cb=_direct_cb)
262
363
 
263
364
  if self._heartbeat_task is None or self._heartbeat_task.done():
264
365
  self._heartbeat_cancel_event = asyncio.Event()
@@ -308,6 +409,20 @@ class Agent:
308
409
  finally:
309
410
  await self.close()
310
411
 
412
+ async def _on_direct_msg(self, msg: Any) -> None:
413
+ """Route a direct worker message to the correct handler by topic."""
414
+ packet = buspacket_pb2.BusPacket()
415
+ try:
416
+ packet.ParseFromString(msg.data)
417
+ except Exception:
418
+ return
419
+ topic = packet.job_request.topic if packet.job_request else ""
420
+ spec = self._handlers.get(topic)
421
+ if spec is None:
422
+ self._logger.warning("no handler for topic %s on direct subject", topic)
423
+ return
424
+ await self._on_msg(msg, spec)
425
+
311
426
  async def _on_msg(self, msg: Any, spec: HandlerSpec) -> None:
312
427
  packet = buspacket_pb2.BusPacket()
313
428
  try:
@@ -7,11 +7,10 @@ import asyncio
7
7
  import json
8
8
  from typing import Any, Awaitable, Callable, Dict, List, Optional, Tuple, Type, Union
9
9
 
10
+ from cap.constants import DEFAULT_PROTOCOL_VERSION
10
11
  from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
11
12
  from cap.runtime import Agent, Context, InMemoryBlobStore
12
13
 
13
- DEFAULT_PROTOCOL_VERSION = 1
14
-
15
14
 
16
15
  class MockNATS:
17
16
  """In-memory mock that replaces a real NATS connection for testing."""
@@ -23,7 +22,7 @@ class MockNATS:
23
22
  async def publish(self, subject: str, data: bytes) -> None:
24
23
  await self.published.put((subject, data))
25
24
 
26
- async def subscribe(self, subject: str, queue: str, cb: Any) -> None:
25
+ async def subscribe(self, subject: str, queue: str = "", cb: Any = None) -> None:
27
26
  self.subscriptions[subject] = cb
28
27
 
29
28
  async def connect(self, servers: str, name: str) -> "MockNATS":
@@ -12,6 +12,10 @@ from cap.pb.cordum.agent.v1 import buspacket_pb2, job_pb2
12
12
  # Max known JobPriority enum value.
13
13
  _JOB_PRIORITY_MAX = job_pb2.JOB_PRIORITY_CRITICAL # 3
14
14
 
15
+ # Bounds limits for repeated fields and budget integers.
16
+ MAX_REPEATED_FIELD_SIZE = 1000
17
+ MAX_BUDGET_TOKENS = 10_000_000_000 # 10 billion
18
+
15
19
 
16
20
  @dataclass(frozen=True)
17
21
  class ValidationError:
@@ -37,20 +41,48 @@ def validate_job_request(msg: Any) -> List[ValidationError]:
37
41
  )
38
42
  if msg.step_index < 0:
39
43
  errors.append(ValidationError("step_index", "must not be negative"))
44
+ # Repeated field bounds — prevent DoS via oversized messages.
45
+ if msg.HasField("meta"):
46
+ m = msg.meta
47
+ if len(m.risk_tags) > MAX_REPEATED_FIELD_SIZE:
48
+ errors.append(
49
+ ValidationError("meta.risk_tags", f"exceeds max size ({MAX_REPEATED_FIELD_SIZE})")
50
+ )
51
+ if len(m.requires) > MAX_REPEATED_FIELD_SIZE:
52
+ errors.append(
53
+ ValidationError("meta.requires", f"exceeds max size ({MAX_REPEATED_FIELD_SIZE})")
54
+ )
55
+ if len(msg.labels) > MAX_REPEATED_FIELD_SIZE:
56
+ errors.append(
57
+ ValidationError("labels", f"exceeds max size ({MAX_REPEATED_FIELD_SIZE})")
58
+ )
59
+
40
60
  if msg.HasField("budget"):
41
61
  b = msg.budget
42
62
  if b.max_input_tokens < 0:
43
63
  errors.append(
44
64
  ValidationError("budget.max_input_tokens", "must not be negative")
45
65
  )
66
+ if b.max_input_tokens > MAX_BUDGET_TOKENS:
67
+ errors.append(
68
+ ValidationError("budget.max_input_tokens", f"exceeds max ({MAX_BUDGET_TOKENS})")
69
+ )
46
70
  if b.max_output_tokens < 0:
47
71
  errors.append(
48
72
  ValidationError("budget.max_output_tokens", "must not be negative")
49
73
  )
74
+ if b.max_output_tokens > MAX_BUDGET_TOKENS:
75
+ errors.append(
76
+ ValidationError("budget.max_output_tokens", f"exceeds max ({MAX_BUDGET_TOKENS})")
77
+ )
50
78
  if b.max_total_tokens < 0:
51
79
  errors.append(
52
80
  ValidationError("budget.max_total_tokens", "must not be negative")
53
81
  )
82
+ if b.max_total_tokens > MAX_BUDGET_TOKENS:
83
+ errors.append(
84
+ ValidationError("budget.max_total_tokens", f"exceeds max ({MAX_BUDGET_TOKENS})")
85
+ )
54
86
  if b.deadline_ms < 0:
55
87
  errors.append(
56
88
  ValidationError("budget.deadline_ms", "must not be negative")
@@ -11,10 +11,9 @@ from cryptography.hazmat.primitives import hashes
11
11
 
12
12
  from cap.subjects import SUBJECT_RESULT
13
13
  from cap.errors import MalformedPacketError, SignatureInvalidError
14
+ from cap.constants import DEFAULT_PROTOCOL_VERSION
14
15
  from cap.metrics import MetricsHook, NoopMetrics
15
16
 
16
- DEFAULT_PROTOCOL_VERSION = 1
17
-
18
17
 
19
18
  async def run_worker(nats_url: str, subject: str, handler: Callable[[job_pb2.JobRequest], Awaitable[job_pb2.JobResult]],
20
19
  public_keys: Dict[str, ec.EllipticCurvePublicKey] = None,
@@ -100,7 +99,13 @@ async def run_worker(nats_url: str, subject: str, handler: Callable[[job_pb2.Job
100
99
  status=job_pb2.JOB_STATUS_FAILED,
101
100
  error_message="handler returned null",
102
101
  )
103
- except Exception as exc: # noqa: BLE001
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)
104
109
  res = job_pb2.JobResult(
105
110
  job_id=req.job_id,
106
111
  status=job_pb2.JOB_STATUS_FAILED,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cap-sdk-python
3
- Version: 2.6.1
3
+ Version: 2.8.4
4
4
  Summary: CAP (Cordum Agent Protocol) Python SDK
5
5
  Author-email: Cordum <eng@cordum.io>
6
6
  License-Expression: Apache-2.0
@@ -168,6 +168,13 @@ agent.use(timing)
168
168
  Middleware executes in registration order (FIFO). Each can inspect context,
169
169
  measure timing, or short-circuit by returning without calling `next_fn`.
170
170
 
171
+ ### Redis TLS
172
+ The Python SDK provides `redis_ssl_context_from_env()` to build an `SSLContext` for secure Redis connections. It reads:
173
+ - `REDIS_TLS_CA` (or `SSL_CERT_FILE` fallback): Path to CA certificate.
174
+ - `REDIS_TLS_CERT` / `REDIS_TLS_KEY`: Path to client certificate/key pair.
175
+ - `REDIS_TLS_SERVER_NAME`: SNI server name override.
176
+ - `REDIS_TLS_INSECURE`: Set to `1` or `true` to skip certificate verification (dev only).
177
+
171
178
  ### Environment
172
179
  - `NATS_URL` (default `nats://127.0.0.1:4222`)
173
180
  - `REDIS_URL` (default `redis://127.0.0.1:6379/0`)
@@ -3,6 +3,7 @@ pyproject.toml
3
3
  cap/__init__.py
4
4
  cap/bus.py
5
5
  cap/client.py
6
+ cap/constants.py
6
7
  cap/errors.py
7
8
  cap/heartbeat.py
8
9
  cap/metrics.py
@@ -40,6 +41,7 @@ tests/test_heartbeat.py
40
41
  tests/test_metrics.py
41
42
  tests/test_middleware.py
42
43
  tests/test_progress.py
44
+ tests/test_redis_tls.py
43
45
  tests/test_runtime.py
44
46
  tests/test_sdk.py
45
47
  tests/test_testing.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cap-sdk-python"
7
- version = "2.6.1"
7
+ version = "2.8.4"
8
8
  description = "CAP (Cordum Agent Protocol) Python SDK"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -0,0 +1,154 @@
1
+ """Tests for redis_ssl_context_from_env() TLS configuration."""
2
+
3
+ import datetime
4
+ import importlib.util
5
+ import os
6
+ import ssl
7
+ import sys
8
+
9
+ import pytest
10
+ from cryptography import x509
11
+ from cryptography.hazmat.primitives import hashes, serialization
12
+ from cryptography.hazmat.primitives.asymmetric import rsa
13
+ from cryptography.x509.oid import NameOID
14
+
15
+
16
+ def _make_self_signed_pem() -> str:
17
+ """Generate a valid self-signed CA certificate PEM for testing."""
18
+ key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
19
+ now = datetime.datetime.now(datetime.timezone.utc)
20
+ cert = (
21
+ x509.CertificateBuilder()
22
+ .subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "testca")]))
23
+ .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "testca")]))
24
+ .public_key(key.public_key())
25
+ .serial_number(x509.random_serial_number())
26
+ .not_valid_before(now)
27
+ .not_valid_after(now + datetime.timedelta(days=365))
28
+ .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
29
+ .sign(key, hashes.SHA256())
30
+ )
31
+ return cert.public_bytes(serialization.Encoding.PEM).decode()
32
+
33
+
34
+ def _load_redis_ssl_context_from_env():
35
+ """Import redis_ssl_context_from_env from runtime.py directly.
36
+
37
+ Uses importlib to load the module file directly, bypassing the cap
38
+ package __init__.py which triggers protobuf imports that may fail
39
+ due to version mismatches in dev environments.
40
+ """
41
+ runtime_path = os.path.join(
42
+ os.path.dirname(__file__), "..", "cap", "runtime.py",
43
+ )
44
+ spec = importlib.util.spec_from_file_location(
45
+ "_cap_runtime_isolated", runtime_path,
46
+ submodule_search_locations=[],
47
+ )
48
+ mod = importlib.util.module_from_spec(spec)
49
+
50
+ # Stub out protobuf imports that runtime.py needs but may fail
51
+ # due to version mismatches in dev environments.
52
+ import types
53
+ from unittest.mock import MagicMock
54
+
55
+ # Discover all cap.* modules to stub
56
+ cap_dir = os.path.join(os.path.dirname(__file__), "..", "cap")
57
+ stub_mods = ["cap"]
58
+ for entry in os.listdir(cap_dir):
59
+ if entry.endswith(".py") and entry != "__init__.py":
60
+ stub_mods.append(f"cap.{entry[:-3]}")
61
+ elif os.path.isdir(os.path.join(cap_dir, entry)) and not entry.startswith("_"):
62
+ stub_mods.append(f"cap.{entry}")
63
+ # Add deep protobuf paths
64
+ stub_mods.extend([
65
+ "cap.pb.cordum", "cap.pb.cordum.agent",
66
+ "cap.pb.cordum.agent.v1", "cap.pb.cordum.agent.v1.buspacket_pb2",
67
+ "cap.pb.cordum.agent.v1.job_pb2", "cap.pb.cordum.agent.v1.heartbeat_pb2",
68
+ ])
69
+
70
+ saved = {}
71
+ for name in stub_mods:
72
+ saved[name] = sys.modules.get(name)
73
+ if name not in sys.modules:
74
+ sys.modules[name] = MagicMock()
75
+
76
+ try:
77
+ spec.loader.exec_module(mod)
78
+ finally:
79
+ for name, orig in saved.items():
80
+ if orig is None:
81
+ sys.modules.pop(name, None)
82
+ else:
83
+ sys.modules[name] = orig
84
+
85
+ return mod.redis_ssl_context_from_env
86
+
87
+
88
+ @pytest.fixture(autouse=True)
89
+ def _clean_env(monkeypatch):
90
+ """Remove all REDIS_TLS_* and SSL_CERT_FILE env vars before each test."""
91
+ for var in ("REDIS_TLS_CA", "REDIS_TLS_CERT", "REDIS_TLS_KEY",
92
+ "REDIS_TLS_SERVER_NAME", "REDIS_TLS_INSECURE", "SSL_CERT_FILE"):
93
+ monkeypatch.delenv(var, raising=False)
94
+
95
+
96
+ @pytest.fixture
97
+ def fn():
98
+ """Provide the redis_ssl_context_from_env function."""
99
+ return _load_redis_ssl_context_from_env()
100
+
101
+
102
+ def test_returns_none_when_no_env_vars(fn):
103
+ """No TLS env vars set -> returns None."""
104
+ assert fn() is None
105
+
106
+
107
+ def test_creates_context_with_ca(fn, monkeypatch, tmp_path):
108
+ """REDIS_TLS_CA set -> returns SSLContext with CA loaded."""
109
+ ca_file = tmp_path / "ca.pem"
110
+ ca_file.write_text(_make_self_signed_pem())
111
+ monkeypatch.setenv("REDIS_TLS_CA", str(ca_file))
112
+
113
+ ctx = fn()
114
+ assert ctx is not None
115
+ assert isinstance(ctx, ssl.SSLContext)
116
+
117
+
118
+ def test_raises_when_cert_without_key(fn, monkeypatch, tmp_path):
119
+ """REDIS_TLS_CERT without REDIS_TLS_KEY -> ValueError."""
120
+ cert_file = tmp_path / "cert.pem"
121
+ cert_file.write_text(_make_self_signed_pem())
122
+ monkeypatch.setenv("REDIS_TLS_CERT", str(cert_file))
123
+
124
+ with pytest.raises(ValueError, match="must be set together"):
125
+ fn()
126
+
127
+
128
+ def test_insecure_skips_verification(fn, monkeypatch):
129
+ """REDIS_TLS_INSECURE=true -> check_hostname=False, CERT_NONE."""
130
+ monkeypatch.setenv("REDIS_TLS_INSECURE", "true")
131
+
132
+ ctx = fn()
133
+ assert ctx is not None
134
+ assert ctx.check_hostname is False
135
+ assert ctx.verify_mode == ssl.CERT_NONE
136
+
137
+
138
+ def test_falls_back_to_ssl_cert_file(fn, monkeypatch, tmp_path):
139
+ """SSL_CERT_FILE used when REDIS_TLS_CA not set."""
140
+ ca_file = tmp_path / "system-ca.pem"
141
+ ca_file.write_text(_make_self_signed_pem())
142
+ monkeypatch.setenv("SSL_CERT_FILE", str(ca_file))
143
+
144
+ ctx = fn()
145
+ assert ctx is not None
146
+ assert isinstance(ctx, ssl.SSLContext)
147
+
148
+
149
+ def test_raises_when_ca_file_missing(fn, monkeypatch):
150
+ """REDIS_TLS_CA points to non-existent file -> FileNotFoundError."""
151
+ monkeypatch.setenv("REDIS_TLS_CA", "/nonexistent/ca.pem")
152
+
153
+ with pytest.raises(FileNotFoundError, match="REDIS_TLS_CA"):
154
+ fn()
@@ -1,44 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # Generated by the protocol buffer compiler. DO NOT EDIT!
3
- # NO CHECKED-IN PROTOBUF GENCODE
4
- # source: cordum/agent/v1/alert.proto
5
- # Protobuf Python Version: 6.31.1
6
- """Generated protocol buffer code."""
7
- from google.protobuf import descriptor as _descriptor
8
- from google.protobuf import descriptor_pool as _descriptor_pool
9
- from google.protobuf import runtime_version as _runtime_version
10
- from google.protobuf import symbol_database as _symbol_database
11
- from google.protobuf.internal import builder as _builder
12
- _runtime_version.ValidateProtobufRuntimeVersion(
13
- _runtime_version.Domain.PUBLIC,
14
- 6,
15
- 31,
16
- 1,
17
- '',
18
- 'cordum/agent/v1/alert.proto'
19
- )
20
- # @@protoc_insertion_point(imports)
21
-
22
- _sym_db = _symbol_database.Default()
23
-
24
-
25
- from cordum.agent.v1 import job_pb2 as cordum_dot_agent_dot_v1_dot_job__pb2
26
-
27
-
28
- DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1b\x63ordum/agent/v1/alert.proto\x12\x0f\x63ordum.agent.v1\x1a\x19\x63ordum/agent/v1/job.proto\"\xcd\x02\n\x0bSystemAlert\x12\r\n\x05level\x18\x01 \x01(\t\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x11\n\tcomponent\x18\x03 \x01(\t\x12\x0c\n\x04\x63ode\x18\x04 \x01(\t\x12\x30\n\x08severity\x18\x05 \x01(\x0e\x32\x1e.cordum.agent.v1.AlertSeverity\x12\x33\n\x0f\x65rror_code_enum\x18\x06 \x01(\x0e\x32\x1a.cordum.agent.v1.ErrorCode\x12\x18\n\x10source_component\x18\x07 \x01(\t\x12:\n\x07\x64\x65tails\x18\x08 \x03(\x0b\x32).cordum.agent.v1.SystemAlert.DetailsEntry\x12\x10\n\x08trace_id\x18\t \x01(\t\x1a.\n\x0c\x44\x65tailsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x9b\x01\n\rAlertSeverity\x12\x1e\n\x1a\x41LERT_SEVERITY_UNSPECIFIED\x10\x00\x12\x17\n\x13\x41LERT_SEVERITY_INFO\x10\x01\x12\x1a\n\x16\x41LERT_SEVERITY_WARNING\x10\x02\x12\x18\n\x14\x41LERT_SEVERITY_ERROR\x10\x03\x12\x1b\n\x17\x41LERT_SEVERITY_CRITICAL\x10\x04\x42\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
29
-
30
- _globals = globals()
31
- _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
- _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'cordum.agent.v1.alert_pb2', _globals)
33
- if not _descriptor._USE_C_DESCRIPTORS:
34
- _globals['DESCRIPTOR']._loaded_options = None
35
- _globals['DESCRIPTOR']._serialized_options = b'\n\026io.cordum.cap.agent.v1P\001Z+github.com/cordum-io/cap/v2/cordum/agent/v1\252\002\017Cordum.Agent.V1\312\002\017cordum\\Agent\\V1\352\002\021Cordum::Agent::V1'
36
- _globals['_SYSTEMALERT_DETAILSENTRY']._loaded_options = None
37
- _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_options = b'8\001'
38
- _globals['_ALERTSEVERITY']._serialized_start=412
39
- _globals['_ALERTSEVERITY']._serialized_end=567
40
- _globals['_SYSTEMALERT']._serialized_start=76
41
- _globals['_SYSTEMALERT']._serialized_end=409
42
- _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_start=363
43
- _globals['_SYSTEMALERT_DETAILSENTRY']._serialized_end=409
44
- # @@protoc_insertion_point(module_scope)
@@ -1,68 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
- # Generated by the protocol buffer compiler. DO NOT EDIT!
3
- # NO CHECKED-IN PROTOBUF GENCODE
4
- # source: cordum/agent/v1/safety.proto
5
- # Protobuf Python Version: 6.31.1
6
- """Generated protocol buffer code."""
7
- from google.protobuf import descriptor as _descriptor
8
- from google.protobuf import descriptor_pool as _descriptor_pool
9
- from google.protobuf import runtime_version as _runtime_version
10
- from google.protobuf import symbol_database as _symbol_database
11
- from google.protobuf.internal import builder as _builder
12
- _runtime_version.ValidateProtobufRuntimeVersion(
13
- _runtime_version.Domain.PUBLIC,
14
- 6,
15
- 31,
16
- 1,
17
- '',
18
- 'cordum/agent/v1/safety.proto'
19
- )
20
- # @@protoc_insertion_point(imports)
21
-
22
- _sym_db = _symbol_database.Default()
23
-
24
-
25
- from cordum.agent.v1 import job_pb2 as cordum_dot_agent_dot_v1_dot_job__pb2
26
-
27
-
28
- DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x1c\x63ordum/agent/v1/safety.proto\x12\x0f\x63ordum.agent.v1\x1a\x19\x63ordum/agent/v1/job.proto\"\x93\x03\n\x12PolicyCheckRequest\x12\x0e\n\x06job_id\x18\x01 \x01(\t\x12\r\n\x05topic\x18\x02 \x01(\t\x12\x0e\n\x06tenant\x18\x03 \x01(\t\x12.\n\x08priority\x18\x04 \x01(\x0e\x32\x1c.cordum.agent.v1.JobPriority\x12\x16\n\x0e\x65stimated_cost\x18\x05 \x01(\x01\x12\'\n\x06\x62udget\x18\x06 \x01(\x0b\x32\x17.cordum.agent.v1.Budget\x12\x14\n\x0cprincipal_id\x18\x07 \x01(\t\x12?\n\x06labels\x18\x08 \x03(\x0b\x32/.cordum.agent.v1.PolicyCheckRequest.LabelsEntry\x12\x11\n\tmemory_id\x18\t \x01(\t\x12\x18\n\x10\x65\x66\x66\x65\x63tive_config\x18\n \x01(\x0c\x12*\n\x04meta\x18\x0b \x01(\x0b\x32\x1c.cordum.agent.v1.JobMetadata\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"y\n\x11\x42udgetConstraints\x12\x16\n\x0emax_runtime_ms\x18\x01 \x01(\x03\x12\x13\n\x0bmax_retries\x18\x02 \x01(\x05\x12\x1a\n\x12max_artifact_bytes\x18\x03 \x01(\x03\x12\x1b\n\x13max_concurrent_jobs\x18\x04 \x01(\x05\"j\n\x0eSandboxProfile\x12\x10\n\x08isolated\x18\x01 \x01(\x08\x12\x19\n\x11network_allowlist\x18\x02 \x03(\t\x12\x14\n\x0c\x66s_read_only\x18\x03 \x03(\t\x12\x15\n\rfs_read_write\x18\x04 \x03(\t\"G\n\x14ToolchainConstraints\x12\x15\n\rallowed_tools\x18\x01 \x03(\t\x12\x18\n\x10\x61llowed_commands\x18\x02 \x03(\t\"P\n\x0f\x44iffConstraints\x12\x11\n\tmax_files\x18\x01 \x01(\x05\x12\x11\n\tmax_lines\x18\x02 \x01(\x05\x12\x17\n\x0f\x64\x65ny_path_globs\x18\x03 \x03(\t\"\xfd\x01\n\x11PolicyConstraints\x12\x33\n\x07\x62udgets\x18\x01 \x01(\x0b\x32\".cordum.agent.v1.BudgetConstraints\x12\x30\n\x07sandbox\x18\x02 \x01(\x0b\x32\x1f.cordum.agent.v1.SandboxProfile\x12\x38\n\ttoolchain\x18\x03 \x01(\x0b\x32%.cordum.agent.v1.ToolchainConstraints\x12.\n\x04\x64iff\x18\x04 \x01(\x0b\x32 .cordum.agent.v1.DiffConstraints\x12\x17\n\x0fredaction_level\x18\x05 \x01(\t\"\x8a\x02\n\x11PolicyRemediation\x12\n\n\x02id\x18\x01 \x01(\t\x12\r\n\x05title\x18\x02 \x01(\t\x12\x0f\n\x07summary\x18\x03 \x01(\t\x12\x19\n\x11replacement_topic\x18\x04 \x01(\t\x12\x1e\n\x16replacement_capability\x18\x05 \x01(\t\x12\x45\n\nadd_labels\x18\x06 \x03(\x0b\x32\x31.cordum.agent.v1.PolicyRemediation.AddLabelsEntry\x12\x15\n\rremove_labels\x18\x07 \x03(\t\x1a\x30\n\x0e\x41\x64\x64LabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xc2\x02\n\x13PolicyCheckResponse\x12/\n\x08\x64\x65\x63ision\x18\x01 \x01(\x0e\x32\x1d.cordum.agent.v1.DecisionType\x12\x0e\n\x06reason\x18\x02 \x01(\t\x12\x1c\n\x14redacted_context_ptr\x18\x03 \x01(\t\x12\x17\n\x0fpolicy_snapshot\x18\x04 \x01(\t\x12\x0f\n\x07rule_id\x18\x05 \x01(\t\x12\x37\n\x0b\x63onstraints\x18\x06 \x01(\x0b\x32\".cordum.agent.v1.PolicyConstraints\x12\x19\n\x11\x61pproval_required\x18\x07 \x01(\x08\x12\x14\n\x0c\x61pproval_ref\x18\x08 \x01(\t\x12\x38\n\x0cremediations\x18\t \x03(\x0b\x32\".cordum.agent.v1.PolicyRemediation\"\x16\n\x14ListSnapshotsRequest\"*\n\x15ListSnapshotsResponse\x12\x11\n\tsnapshots\x18\x01 \x03(\t*\xc5\x01\n\x0c\x44\x65\x63isionType\x12\x1d\n\x19\x44\x45\x43ISION_TYPE_UNSPECIFIED\x10\x00\x12\x17\n\x13\x44\x45\x43ISION_TYPE_ALLOW\x10\x01\x12\x16\n\x12\x44\x45\x43ISION_TYPE_DENY\x10\x02\x12\x1f\n\x1b\x44\x45\x43ISION_TYPE_REQUIRE_HUMAN\x10\x03\x12\x1a\n\x16\x44\x45\x43ISION_TYPE_THROTTLE\x10\x04\x12(\n$DECISION_TYPE_ALLOW_WITH_CONSTRAINTS\x10\x05\x32\xc6\x03\n\x0cSafetyKernel\x12R\n\x05\x43heck\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12U\n\x08\x45valuate\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12T\n\x07\x45xplain\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12U\n\x08Simulate\x12#.cordum.agent.v1.PolicyCheckRequest\x1a$.cordum.agent.v1.PolicyCheckResponse\x12^\n\rListSnapshots\x12%.cordum.agent.v1.ListSnapshotsRequest\x1a&.cordum.agent.v1.ListSnapshotsResponseB\x7f\n\x16io.cordum.cap.agent.v1P\x01Z+github.com/cordum-io/cap/v2/cordum/agent/v1\xaa\x02\x0f\x43ordum.Agent.V1\xca\x02\x0f\x63ordum\\Agent\\V1\xea\x02\x11\x43ordum::Agent::V1b\x06proto3')
29
-
30
- _globals = globals()
31
- _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
32
- _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'cordum.agent.v1.safety_pb2', _globals)
33
- if not _descriptor._USE_C_DESCRIPTORS:
34
- _globals['DESCRIPTOR']._loaded_options = None
35
- _globals['DESCRIPTOR']._serialized_options = b'\n\026io.cordum.cap.agent.v1P\001Z+github.com/cordum-io/cap/v2/cordum/agent/v1\252\002\017Cordum.Agent.V1\312\002\017cordum\\Agent\\V1\352\002\021Cordum::Agent::V1'
36
- _globals['_POLICYCHECKREQUEST_LABELSENTRY']._loaded_options = None
37
- _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_options = b'8\001'
38
- _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._loaded_options = None
39
- _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_options = b'8\001'
40
- _globals['_DECISIONTYPE']._serialized_start=1787
41
- _globals['_DECISIONTYPE']._serialized_end=1984
42
- _globals['_POLICYCHECKREQUEST']._serialized_start=77
43
- _globals['_POLICYCHECKREQUEST']._serialized_end=480
44
- _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_start=435
45
- _globals['_POLICYCHECKREQUEST_LABELSENTRY']._serialized_end=480
46
- _globals['_BUDGETCONSTRAINTS']._serialized_start=482
47
- _globals['_BUDGETCONSTRAINTS']._serialized_end=603
48
- _globals['_SANDBOXPROFILE']._serialized_start=605
49
- _globals['_SANDBOXPROFILE']._serialized_end=711
50
- _globals['_TOOLCHAINCONSTRAINTS']._serialized_start=713
51
- _globals['_TOOLCHAINCONSTRAINTS']._serialized_end=784
52
- _globals['_DIFFCONSTRAINTS']._serialized_start=786
53
- _globals['_DIFFCONSTRAINTS']._serialized_end=866
54
- _globals['_POLICYCONSTRAINTS']._serialized_start=869
55
- _globals['_POLICYCONSTRAINTS']._serialized_end=1122
56
- _globals['_POLICYREMEDIATION']._serialized_start=1125
57
- _globals['_POLICYREMEDIATION']._serialized_end=1391
58
- _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_start=1343
59
- _globals['_POLICYREMEDIATION_ADDLABELSENTRY']._serialized_end=1391
60
- _globals['_POLICYCHECKRESPONSE']._serialized_start=1394
61
- _globals['_POLICYCHECKRESPONSE']._serialized_end=1716
62
- _globals['_LISTSNAPSHOTSREQUEST']._serialized_start=1718
63
- _globals['_LISTSNAPSHOTSREQUEST']._serialized_end=1740
64
- _globals['_LISTSNAPSHOTSRESPONSE']._serialized_start=1742
65
- _globals['_LISTSNAPSHOTSRESPONSE']._serialized_end=1784
66
- _globals['_SAFETYKERNEL']._serialized_start=1987
67
- _globals['_SAFETYKERNEL']._serialized_end=2441
68
- # @@protoc_insertion_point(module_scope)
File without changes