kuflow-temporal-worker 3.0.0__tar.gz → 3.2.0__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.
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/PKG-INFO +9 -7
- kuflow_temporal_worker-3.2.0/VERSION +1 -0
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/_authentication.py +2 -1
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/_connection.py +36 -34
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/_connection_config.py +6 -20
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/__init__.py +34 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_cache.py +125 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_crypto.py +67 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_instrumentation.py +108 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_interceptor.py +188 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_payload_codec.py +120 -0
- kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_payload_converter.py +74 -0
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/_worker_information_notifier.py +6 -6
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/pyproject.toml +17 -10
- kuflow_temporal_worker-3.0.0/VERSION +0 -1
- kuflow_temporal_worker-3.0.0/setup.py +0 -30
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/README.md +0 -0
- {kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/__init__.py +0 -0
|
@@ -1,21 +1,23 @@
|
|
|
1
|
-
Metadata-Version: 2.
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
2
|
Name: kuflow-temporal-worker
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.2.0
|
|
4
4
|
Summary: KuFlow utilities to use Temporal.io
|
|
5
|
-
Home-page: https://kuflow.com/
|
|
6
5
|
License: MIT
|
|
7
6
|
Author: KuFlow S.L.
|
|
8
7
|
Author-email: kuflow@kuflow.com
|
|
9
|
-
Requires-Python: >=3.
|
|
8
|
+
Requires-Python: >=3.9,<4.0
|
|
10
9
|
Classifier: License :: OSI Approved :: MIT License
|
|
11
10
|
Classifier: Programming Language :: Python :: 3
|
|
12
|
-
Classifier: Programming Language :: Python :: 3.8
|
|
13
11
|
Classifier: Programming Language :: Python :: 3.9
|
|
14
12
|
Classifier: Programming Language :: Python :: 3.10
|
|
15
13
|
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
-
|
|
17
|
-
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Requires-Dist: cryptography (>=38.0.1,<39.0.0)
|
|
17
|
+
Requires-Dist: kuflow-temporal-common (>=3.2.0,<4.0.0)
|
|
18
|
+
Requires-Dist: temporalio (>=1.10.0,<1.11.0)
|
|
18
19
|
Project-URL: Documentation, https://docs.kuflow.com/
|
|
20
|
+
Project-URL: Homepage, https://kuflow.com/
|
|
19
21
|
Project-URL: Repository, https://github.com/kuflow/kuflow-sdk-python
|
|
20
22
|
Description-Content-Type: text/markdown
|
|
21
23
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.2.0
|
{kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/_connection.py
RENAMED
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
#
|
|
24
24
|
|
|
25
25
|
import dataclasses
|
|
26
|
-
from typing import
|
|
26
|
+
from typing import Optional
|
|
27
27
|
|
|
28
28
|
import temporalio.activity
|
|
29
29
|
import temporalio.common
|
|
@@ -34,13 +34,21 @@ from temporalio.client import Client, TLSConfig
|
|
|
34
34
|
from temporalio.worker import Worker
|
|
35
35
|
|
|
36
36
|
from kuflow_rest import models
|
|
37
|
-
from kuflow_temporal_common import
|
|
37
|
+
from kuflow_temporal_common import (
|
|
38
|
+
KuFlowModelJSONEncoder,
|
|
39
|
+
KuFlowModelJSONTypeConverter,
|
|
40
|
+
)
|
|
38
41
|
|
|
39
42
|
from ._authentication import KuFlowAuthorizationTokenProvider
|
|
40
43
|
from ._connection_config import (
|
|
41
44
|
KuFlowConfig,
|
|
42
45
|
TemporalConfig,
|
|
43
46
|
)
|
|
47
|
+
from ._encryption import (
|
|
48
|
+
KuFlowEncryptionInterceptor,
|
|
49
|
+
KuFlowEncryptionPayloadCodec,
|
|
50
|
+
KuFlowEncryptionPayloadConverter,
|
|
51
|
+
)
|
|
44
52
|
from ._worker_information_notifier import KuFlowWorkerInformationNotifier
|
|
45
53
|
|
|
46
54
|
|
|
@@ -56,8 +64,8 @@ class KuFlowTemporalConnection:
|
|
|
56
64
|
self._kuFlow_worker_information_notifier: Optional[KuFlowWorkerInformationNotifier] = None
|
|
57
65
|
self._client: Optional[Client] = None
|
|
58
66
|
self._worker: Optional[Worker] = None
|
|
59
|
-
self._workflow_types:
|
|
60
|
-
self._activity_types:
|
|
67
|
+
self._workflow_types: set[str] = set()
|
|
68
|
+
self._activity_types: set[str] = set()
|
|
61
69
|
|
|
62
70
|
async def connect(self) -> Client:
|
|
63
71
|
"""Connect to a Temporal server"""
|
|
@@ -75,10 +83,16 @@ class KuFlowTemporalConnection:
|
|
|
75
83
|
|
|
76
84
|
self._temporal.client.rpc_metadata = self._kuflow_authorization_token_provider.initialize_rpc_auth_metadata()
|
|
77
85
|
|
|
78
|
-
self._register_encoding_payload_converter()
|
|
79
|
-
|
|
80
86
|
client_config = self._temporal.client.__dict__.copy()
|
|
81
87
|
client_config.pop("target_host", None)
|
|
88
|
+
client_config["data_converter"] = dataclasses.replace(
|
|
89
|
+
temporalio.converter.DataConverter.default,
|
|
90
|
+
payload_converter_class=KuFlowConverterClass,
|
|
91
|
+
payload_codec=KuFlowEncryptionPayloadCodec(
|
|
92
|
+
rest_client=self._kuflow.rest_client,
|
|
93
|
+
),
|
|
94
|
+
)
|
|
95
|
+
client_config["interceptors"] = [KuFlowEncryptionInterceptor()]
|
|
82
96
|
|
|
83
97
|
target_host = self._temporal.client.target_host or "engine.kuflow.com:443"
|
|
84
98
|
|
|
@@ -100,6 +114,7 @@ class KuFlowTemporalConnection:
|
|
|
100
114
|
client = await self.connect()
|
|
101
115
|
|
|
102
116
|
worker_config = self._temporal.worker.__dict__.copy()
|
|
117
|
+
worker_config["interceptors"] = []
|
|
103
118
|
|
|
104
119
|
self._worker = Worker(client, **worker_config)
|
|
105
120
|
|
|
@@ -138,34 +153,6 @@ class KuFlowTemporalConnection:
|
|
|
138
153
|
|
|
139
154
|
await worker.run()
|
|
140
155
|
|
|
141
|
-
def _register_encoding_payload_converter(self):
|
|
142
|
-
additional_converter_classes = [KuFlowComposableEncodingPayloadConverter]
|
|
143
|
-
|
|
144
|
-
converters = list(temporalio.converter.DefaultPayloadConverter.default_encoding_payload_converters)
|
|
145
|
-
|
|
146
|
-
converters_by_encoding: Dict[str, List[temporalio.converter.EncodingPayloadConverter]] = {}
|
|
147
|
-
|
|
148
|
-
for converter_class in additional_converter_classes:
|
|
149
|
-
converter = converter_class()
|
|
150
|
-
|
|
151
|
-
converters_encoding = converters_by_encoding.get(converter.encoding, None)
|
|
152
|
-
if converters_encoding is None:
|
|
153
|
-
converters_encoding = [it for it in converters if it.encoding == converter.encoding]
|
|
154
|
-
|
|
155
|
-
converters_encoding.insert(0, converter)
|
|
156
|
-
converters_by_encoding[converter.encoding] = converters_encoding
|
|
157
|
-
|
|
158
|
-
for encoding in converters_by_encoding:
|
|
159
|
-
composite_converter = CompositeEncodingPayloadConverter(
|
|
160
|
-
encoding=encoding, converters=converters_by_encoding[encoding]
|
|
161
|
-
)
|
|
162
|
-
|
|
163
|
-
converters = [it if it.encoding != encoding else composite_converter for it in converters]
|
|
164
|
-
|
|
165
|
-
temporalio.converter.DefaultPayloadConverter.default_encoding_payload_converters = tuple(converters)
|
|
166
|
-
|
|
167
|
-
self._temporal.client.data_converter = dataclasses.replace(temporalio.converter.DataConverter.default)
|
|
168
|
-
|
|
169
156
|
def _apply_default_configurations(self):
|
|
170
157
|
authentication = models.Authentication(
|
|
171
158
|
type=models.AuthenticationType.ENGINE_CERTIFICATE,
|
|
@@ -184,3 +171,18 @@ class KuFlowTemporalConnection:
|
|
|
184
171
|
self._temporal.client.namespace = authentication.engine_certificate.namespace
|
|
185
172
|
|
|
186
173
|
self._temporal.client.namespace = self._temporal.client.namespace or "default"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class KuFlowConverterClass(temporalio.converter.CompositePayloadConverter):
|
|
177
|
+
def __init__(self) -> None:
|
|
178
|
+
super().__init__(
|
|
179
|
+
temporalio.converter.BinaryNullPayloadConverter(),
|
|
180
|
+
temporalio.converter.BinaryPlainPayloadConverter(),
|
|
181
|
+
temporalio.converter.JSONProtoPayloadConverter(),
|
|
182
|
+
temporalio.converter.BinaryProtoPayloadConverter(),
|
|
183
|
+
KuFlowEncryptionPayloadConverter(
|
|
184
|
+
delegate=temporalio.converter.JSONPlainPayloadConverter(
|
|
185
|
+
encoder=KuFlowModelJSONEncoder, custom_type_converters=[KuFlowModelJSONTypeConverter()]
|
|
186
|
+
)
|
|
187
|
+
),
|
|
188
|
+
)
|
|
@@ -24,15 +24,15 @@
|
|
|
24
24
|
|
|
25
25
|
|
|
26
26
|
import concurrent.futures
|
|
27
|
+
from collections.abc import Awaitable, Mapping, Sequence
|
|
27
28
|
from dataclasses import dataclass, field
|
|
28
29
|
from datetime import timedelta
|
|
29
|
-
from typing import
|
|
30
|
+
from typing import Callable, Optional, Union
|
|
30
31
|
|
|
31
32
|
import temporalio.common
|
|
32
|
-
import temporalio.converter
|
|
33
33
|
import temporalio.runtime
|
|
34
34
|
import temporalio.workflow
|
|
35
|
-
from temporalio.client import HttpConnectProxyConfig,
|
|
35
|
+
from temporalio.client import HttpConnectProxyConfig, KeepAliveConfig, RetryConfig, TLSConfig
|
|
36
36
|
from temporalio.worker import SharedStateManager, UnsandboxedWorkflowRunner, WorkflowRunner
|
|
37
37
|
from temporalio.worker.workflow_sandbox import SandboxedWorkflowRunner
|
|
38
38
|
|
|
@@ -86,10 +86,10 @@ class KuFlowConfig:
|
|
|
86
86
|
installation_id: Optional[str] = None
|
|
87
87
|
"""Installation id"""
|
|
88
88
|
|
|
89
|
-
robot_ids: Optional[
|
|
89
|
+
robot_ids: Optional[list[str]] = None
|
|
90
90
|
"""Robot ids"""
|
|
91
91
|
|
|
92
|
-
tenant_id: Optional[
|
|
92
|
+
tenant_id: Optional[list[str]] = None
|
|
93
93
|
"""Tenant ids"""
|
|
94
94
|
|
|
95
95
|
|
|
@@ -103,16 +103,6 @@ class TemporalClientConfig:
|
|
|
103
103
|
namespace: Optional[str] = None
|
|
104
104
|
"""Namespace to use for client calls."""
|
|
105
105
|
|
|
106
|
-
data_converter: temporalio.converter.DataConverter = temporalio.converter.DataConverter.default
|
|
107
|
-
"""Data converter to use for all data conversions to/from payloads."""
|
|
108
|
-
|
|
109
|
-
interceptors: Sequence[Interceptor] = field(default_factory=list)
|
|
110
|
-
"""Set of interceptors that are chained together to allow intercepting of client calls. The earlier interceptors
|
|
111
|
-
wrap the later ones.
|
|
112
|
-
|
|
113
|
-
Any interceptors that also implement :py:class:`temporalio.worker.Interceptor` will be used as worker interceptors
|
|
114
|
-
too so they should not be given when creating a worker."""
|
|
115
|
-
|
|
116
106
|
default_workflow_query_reject_condition: Optional[temporalio.common.QueryRejectCondition] = None
|
|
117
107
|
"""The default rejection condition for workflow queries if not set during query. See :py:meth:`WorkflowHandle.query`
|
|
118
108
|
for details on the rejection condition."""
|
|
@@ -157,7 +147,7 @@ class TemporalWorkerConfig:
|
|
|
157
147
|
"""Set of activity callables decorated with :py:func:`@activity.defn<temporalio.activity.defn>`. Activities may be
|
|
158
148
|
async functions or non-async functions. """
|
|
159
149
|
|
|
160
|
-
workflows: Sequence[
|
|
150
|
+
workflows: Sequence[type] = field(default_factory=list)
|
|
161
151
|
"""Set of workflow classes decorated with :py:func:`@workflow.defn<temporalio.workflow.defn>`."""
|
|
162
152
|
|
|
163
153
|
activity_executor: Optional[concurrent.futures.Executor] = None
|
|
@@ -177,10 +167,6 @@ class TemporalWorkerConfig:
|
|
|
177
167
|
unsandboxed_workflow_runner: WorkflowRunner = UnsandboxedWorkflowRunner()
|
|
178
168
|
"""Runner for workflows that opt-out of sandboxing."""
|
|
179
169
|
|
|
180
|
-
interceptors: Sequence[Interceptor] = field(default_factory=list)
|
|
181
|
-
"""Collection of interceptors for this worker. Any interceptors already on the client that also implement
|
|
182
|
-
:py:class:`Interceptor` are prepended to this list and should not be explicitly given here."""
|
|
183
|
-
|
|
184
170
|
build_id: Optional[str] = None
|
|
185
171
|
"""Unique identifier for the current runtime. This is best set as a hash of all code and should change only when
|
|
186
172
|
code does. If unset, a best-effort identifier is generated."""
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
from ._kuflow_encryption_interceptor import KuFlowEncryptionInterceptor
|
|
26
|
+
from ._kuflow_encryption_payload_codec import KuFlowEncryptionPayloadCodec
|
|
27
|
+
from ._kuflow_encryption_payload_converter import KuFlowEncryptionPayloadConverter
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
__all__ = [
|
|
31
|
+
"KuFlowEncryptionInterceptor",
|
|
32
|
+
"KuFlowEncryptionPayloadCodec",
|
|
33
|
+
"KuFlowEncryptionPayloadConverter",
|
|
34
|
+
]
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
import asyncio
|
|
26
|
+
import logging
|
|
27
|
+
from collections import defaultdict
|
|
28
|
+
from collections.abc import Awaitable
|
|
29
|
+
from datetime import timedelta
|
|
30
|
+
from typing import Callable, Generic, Optional, TypeVar
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
V = TypeVar("V") # Type for the value
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class CacheEntry(Generic[V]):
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
key: str,
|
|
42
|
+
value: V,
|
|
43
|
+
expire_at: Optional[float] = None,
|
|
44
|
+
):
|
|
45
|
+
self.key = key
|
|
46
|
+
self.value = value
|
|
47
|
+
self.expire_at = expire_at
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class Cache(Generic[V]):
|
|
51
|
+
def __init__(self, ttl: timedelta, cleanup_interval: timedelta = timedelta(minutes=1)):
|
|
52
|
+
"""
|
|
53
|
+
Cache with TTL and minimal locking for high concurrency.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
ttl (timedelta): Time items remain valid after last access.
|
|
57
|
+
cleanup_interval (timedelta, optional): Cleanup interval. Defaults to 1 minute.
|
|
58
|
+
"""
|
|
59
|
+
self._ttl = ttl.total_seconds()
|
|
60
|
+
self._cleanup_interval = cleanup_interval.total_seconds()
|
|
61
|
+
self._cleanup_task = asyncio.create_task(self._cleanup())
|
|
62
|
+
self._cache: dict[str, CacheEntry[V]] = {}
|
|
63
|
+
self._cache_locks = defaultdict(asyncio.Lock)
|
|
64
|
+
|
|
65
|
+
async def get(self, key: str, loader: Callable[[], Awaitable[V]]) -> V:
|
|
66
|
+
# Fast path: check cache without locking
|
|
67
|
+
cache_entry = self._find_cache_entry(key)
|
|
68
|
+
if cache_entry is not None:
|
|
69
|
+
self._put_cache_entry(key, cache_entry.value)
|
|
70
|
+
|
|
71
|
+
return cache_entry.value
|
|
72
|
+
|
|
73
|
+
# Slow path: acquire lock only if not in cache or expired
|
|
74
|
+
async with self._cache_locks[key]:
|
|
75
|
+
# Check again after acquiring lock
|
|
76
|
+
cache_entry = self._find_cache_entry(key)
|
|
77
|
+
if cache_entry is not None:
|
|
78
|
+
return cache_entry.value
|
|
79
|
+
|
|
80
|
+
key_value = await loader()
|
|
81
|
+
|
|
82
|
+
self._put_cache_entry(key, key_value)
|
|
83
|
+
|
|
84
|
+
logger.info(f"Loaded key {key} into cache")
|
|
85
|
+
|
|
86
|
+
return key_value
|
|
87
|
+
|
|
88
|
+
async def close(self):
|
|
89
|
+
"""Cancel cleanup task and clean resources."""
|
|
90
|
+
self._cleanup_task.cancel()
|
|
91
|
+
try:
|
|
92
|
+
await self._cleanup_task
|
|
93
|
+
except asyncio.CancelledError:
|
|
94
|
+
pass
|
|
95
|
+
|
|
96
|
+
def _put_cache_entry(self, key: str, value: V):
|
|
97
|
+
"""Put a cache entry into the cache."""
|
|
98
|
+
expire_at = asyncio.get_event_loop().time() + self._ttl
|
|
99
|
+
self._cache[key] = CacheEntry(key=key, value=value, expire_at=expire_at)
|
|
100
|
+
|
|
101
|
+
def _find_cache_entry(self, key: str) -> Optional[CacheEntry[V]]:
|
|
102
|
+
"""Retrieve the cache entry from the cache if it exists."""
|
|
103
|
+
if key not in self._cache:
|
|
104
|
+
return None
|
|
105
|
+
|
|
106
|
+
cache_entry = self._cache[key]
|
|
107
|
+
if cache_entry.expire_at <= asyncio.get_event_loop().time():
|
|
108
|
+
return None
|
|
109
|
+
|
|
110
|
+
return cache_entry
|
|
111
|
+
|
|
112
|
+
async def _cleanup(self):
|
|
113
|
+
"""Periodically removes expired items."""
|
|
114
|
+
while True:
|
|
115
|
+
await asyncio.sleep(self._cleanup_interval)
|
|
116
|
+
|
|
117
|
+
now = asyncio.get_event_loop().time()
|
|
118
|
+
keys = list(self._cache.keys())
|
|
119
|
+
for key in keys:
|
|
120
|
+
async with self._cache_locks[key]:
|
|
121
|
+
if key in self._cache and self._cache[key].expire_at <= now:
|
|
122
|
+
del self._cache[key]
|
|
123
|
+
del self._cache_locks[key]
|
|
124
|
+
|
|
125
|
+
logger.info(f"Removed key {key} from cache")
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
import os
|
|
26
|
+
from abc import ABC, abstractmethod
|
|
27
|
+
|
|
28
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class Cipher(ABC):
|
|
32
|
+
@property
|
|
33
|
+
@abstractmethod
|
|
34
|
+
def algorithm(self) -> str:
|
|
35
|
+
"""Name of the encryption algorithm."""
|
|
36
|
+
pass
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
async def encrypt(self, key: bytes, plain_text: bytes) -> bytes:
|
|
40
|
+
"""Encrypts the plain text using the given key."""
|
|
41
|
+
pass
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
async def decrypt(self, key: bytes, cipher_text: bytes) -> bytes:
|
|
45
|
+
"""Decrypts the cipher text using the given key."""
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CipherAes256GCM(Cipher):
|
|
50
|
+
@property
|
|
51
|
+
def algorithm(self) -> str:
|
|
52
|
+
return "AES-256-GCM"
|
|
53
|
+
|
|
54
|
+
async def encrypt(self, key: bytes, plain_text: bytes) -> bytes:
|
|
55
|
+
encryptor = AESGCM(key)
|
|
56
|
+
nonce = os.urandom(12)
|
|
57
|
+
|
|
58
|
+
return nonce + encryptor.encrypt(nonce, plain_text, None)
|
|
59
|
+
|
|
60
|
+
async def decrypt(self, key: bytes, cipher_text: bytes) -> bytes:
|
|
61
|
+
encryptor = AESGCM(key)
|
|
62
|
+
|
|
63
|
+
return encryptor.decrypt(cipher_text[:12], cipher_text[12:], None)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class CIPHERS:
|
|
67
|
+
AES_256_GCM = CipherAes256GCM()
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
from collections.abc import Mapping, Sequence
|
|
26
|
+
from typing import Any, Optional
|
|
27
|
+
|
|
28
|
+
import temporalio.api.common.v1
|
|
29
|
+
import temporalio.converter
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
HEADER_KEY_KUFLOW_ENCODING = "x-kuflow-encoding"
|
|
33
|
+
HEADER_KEY_KUFLOW_ENCODING_ENCRYPTED_KEY_ID = "x-kuflow-encoding-encrypted-key-id"
|
|
34
|
+
HEADER_VALUE_KUFLOW_ENCODING_ENCRYPTED = "binary/encrypted?vendor=KuFlow"
|
|
35
|
+
|
|
36
|
+
METADATA_KEY_ENCODING = "encoding"
|
|
37
|
+
METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID = "encoding-encrypted-key-id"
|
|
38
|
+
METADATA_VALUE_KUFLOW_ENCODING_ENCRYPTED = "binary/encrypted?vendor=KuFlow"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class KuFlowEncryptionState:
|
|
42
|
+
key_id: Optional[str] = None
|
|
43
|
+
|
|
44
|
+
def __init__(self, key_id: Optional[str]) -> None:
|
|
45
|
+
self.key_id = key_id
|
|
46
|
+
|
|
47
|
+
def merge(self, other: Optional["KuFlowEncryptionState"]):
|
|
48
|
+
if other.key_id is not None:
|
|
49
|
+
self.key_id = other.key_id
|
|
50
|
+
else:
|
|
51
|
+
self.key_id = None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class KuFlowEncryptionWrapper:
|
|
55
|
+
encryption_state: KuFlowEncryptionState
|
|
56
|
+
|
|
57
|
+
value: Any
|
|
58
|
+
|
|
59
|
+
def __init__(self, encryption_state: KuFlowEncryptionState, value: Any) -> None:
|
|
60
|
+
self.encryption_state = encryption_state
|
|
61
|
+
self.value = value
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def retrieve_encryption_state(headers: Mapping[str, temporalio.api.common.v1.Payload]) -> KuFlowEncryptionState:
|
|
65
|
+
if not is_encryption_required(headers):
|
|
66
|
+
return KuFlowEncryptionState(key_id=None)
|
|
67
|
+
|
|
68
|
+
key_id_payload = headers.get(HEADER_KEY_KUFLOW_ENCODING_ENCRYPTED_KEY_ID)
|
|
69
|
+
key_id = temporalio.converter.PayloadConverter.default.from_payload(key_id_payload)
|
|
70
|
+
|
|
71
|
+
return KuFlowEncryptionState(key_id=key_id)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def is_encryption_required(headers: Mapping[str, temporalio.api.common.v1.Payload]) -> bool:
|
|
75
|
+
header_payload = headers.get(HEADER_KEY_KUFLOW_ENCODING)
|
|
76
|
+
if not header_payload:
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
value = temporalio.converter.PayloadConverter.default.from_payload(header_payload)
|
|
80
|
+
if not value:
|
|
81
|
+
return False
|
|
82
|
+
|
|
83
|
+
return value == HEADER_VALUE_KUFLOW_ENCODING_ENCRYPTED
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def add_encryption_encoding(
|
|
87
|
+
encryption_state: KuFlowEncryptionState,
|
|
88
|
+
headers: Mapping[str, temporalio.api.common.v1.Payload],
|
|
89
|
+
) -> Mapping[str, temporalio.api.common.v1.Payload]:
|
|
90
|
+
if encryption_state.key_id is None:
|
|
91
|
+
return headers
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
**headers,
|
|
95
|
+
HEADER_KEY_KUFLOW_ENCODING: temporalio.converter.PayloadConverter.default.to_payload(
|
|
96
|
+
HEADER_VALUE_KUFLOW_ENCODING_ENCRYPTED
|
|
97
|
+
),
|
|
98
|
+
HEADER_KEY_KUFLOW_ENCODING_ENCRYPTED_KEY_ID: temporalio.converter.PayloadConverter.default.to_payload(
|
|
99
|
+
encryption_state.key_id
|
|
100
|
+
),
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def mark_objects_to_be_encrypted(encryption_state: KuFlowEncryptionState, args: Sequence[Any]) -> Sequence[Any]:
|
|
105
|
+
if encryption_state.key_id is None:
|
|
106
|
+
return args
|
|
107
|
+
|
|
108
|
+
return [KuFlowEncryptionWrapper(encryption_state=encryption_state, value=arg) for arg in args]
|
kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_interceptor.py
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
import dataclasses
|
|
25
|
+
from typing import Any, NoReturn, Optional
|
|
26
|
+
|
|
27
|
+
import temporalio.client
|
|
28
|
+
import temporalio.worker
|
|
29
|
+
import temporalio.workflow
|
|
30
|
+
|
|
31
|
+
from ._kuflow_encryption_instrumentation import (
|
|
32
|
+
KuFlowEncryptionState,
|
|
33
|
+
KuFlowEncryptionWrapper,
|
|
34
|
+
add_encryption_encoding,
|
|
35
|
+
mark_objects_to_be_encrypted,
|
|
36
|
+
retrieve_encryption_state,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class KuFlowEncryptionInterceptor(temporalio.client.Interceptor, temporalio.worker.Interceptor):
|
|
41
|
+
def intercept_activity(
|
|
42
|
+
self, next: temporalio.worker.ActivityInboundInterceptor
|
|
43
|
+
) -> temporalio.worker.ActivityInboundInterceptor:
|
|
44
|
+
"""Implementation of
|
|
45
|
+
:py:meth:`temporalio.worker.Interceptor.intercept_activity`.
|
|
46
|
+
"""
|
|
47
|
+
return KuFlowEncryptionActivityInboundInterceptor(next, self)
|
|
48
|
+
|
|
49
|
+
def workflow_interceptor_class(
|
|
50
|
+
self, input: temporalio.worker.WorkflowInterceptorClassInput
|
|
51
|
+
) -> Optional[type[temporalio.worker.WorkflowInboundInterceptor]]:
|
|
52
|
+
"""Implementation of
|
|
53
|
+
:py:meth:`temporalio.worker.Interceptor.workflow_interceptor_class`.
|
|
54
|
+
"""
|
|
55
|
+
return KuFlowEncryptionWorkflowInboundInterceptor
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class KuFlowEncryptionActivityInboundInterceptor(temporalio.worker.ActivityInboundInterceptor):
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
next: temporalio.worker.ActivityInboundInterceptor,
|
|
62
|
+
root: KuFlowEncryptionInterceptor,
|
|
63
|
+
) -> None:
|
|
64
|
+
super().__init__(next)
|
|
65
|
+
self.root = root
|
|
66
|
+
|
|
67
|
+
async def execute_activity(self, input: temporalio.worker.ExecuteActivityInput) -> Any:
|
|
68
|
+
output = await super().execute_activity(input)
|
|
69
|
+
|
|
70
|
+
encryption_state = retrieve_encryption_state(input.headers)
|
|
71
|
+
|
|
72
|
+
return KuFlowEncryptionWrapper(encryption_state=encryption_state, value=output)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class KuFlowEncryptionWorkflowInboundInterceptor(temporalio.worker.WorkflowInboundInterceptor):
|
|
76
|
+
"""Tracing interceptor for workflow calls.
|
|
77
|
+
|
|
78
|
+
See :py:class:`TracingInterceptor` docs on why one might want to subclass
|
|
79
|
+
this class.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(self, next: temporalio.worker.WorkflowInboundInterceptor) -> None:
|
|
83
|
+
"""Initialize a tracing workflow interceptor."""
|
|
84
|
+
super().__init__(next)
|
|
85
|
+
self.encryption_state = KuFlowEncryptionState(key_id=None)
|
|
86
|
+
|
|
87
|
+
def init(self, outbound: temporalio.worker.WorkflowOutboundInterceptor) -> None:
|
|
88
|
+
"""Implementation of
|
|
89
|
+
:py:meth:`temporalio.worker.WorkflowInboundInterceptor.init`.
|
|
90
|
+
"""
|
|
91
|
+
super().init(KuFlowEncryptionWorkflowOutboundInterceptor(outbound, self))
|
|
92
|
+
|
|
93
|
+
async def execute_workflow(self, input: temporalio.worker.ExecuteWorkflowInput) -> Any:
|
|
94
|
+
"""Implementation of
|
|
95
|
+
:py:meth:`temporalio.worker.WorkflowInboundInterceptor.execute_workflow`.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
encryption_state_current = retrieve_encryption_state(input.headers)
|
|
99
|
+
|
|
100
|
+
self.encryption_state.merge(encryption_state_current)
|
|
101
|
+
|
|
102
|
+
output = await super().execute_workflow(input)
|
|
103
|
+
|
|
104
|
+
return KuFlowEncryptionWrapper(encryption_state=self.encryption_state, value=output)
|
|
105
|
+
|
|
106
|
+
async def handle_query(self, input: temporalio.worker.HandleQueryInput) -> Any:
|
|
107
|
+
"""Implementation of
|
|
108
|
+
:py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_query`.
|
|
109
|
+
"""
|
|
110
|
+
output = await super().handle_query(input)
|
|
111
|
+
|
|
112
|
+
return KuFlowEncryptionWrapper(encryption_state=self.encryption_state, value=output)
|
|
113
|
+
|
|
114
|
+
async def handle_update_handler(self, input: temporalio.worker.HandleUpdateInput) -> Any:
|
|
115
|
+
"""Implementation of
|
|
116
|
+
:py:meth:`temporalio.worker.WorkflowInboundInterceptor.handle_update_handler`.
|
|
117
|
+
"""
|
|
118
|
+
output = await super().handle_update_handler(input)
|
|
119
|
+
|
|
120
|
+
return KuFlowEncryptionWrapper(encryption_state=self.encryption_state, value=output)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class KuFlowEncryptionWorkflowOutboundInterceptor(temporalio.worker.WorkflowOutboundInterceptor):
|
|
124
|
+
def __init__(
|
|
125
|
+
self,
|
|
126
|
+
next: temporalio.worker.WorkflowOutboundInterceptor,
|
|
127
|
+
root: KuFlowEncryptionWorkflowInboundInterceptor,
|
|
128
|
+
) -> None:
|
|
129
|
+
super().__init__(next)
|
|
130
|
+
self.root = root
|
|
131
|
+
|
|
132
|
+
def continue_as_new(self, input: temporalio.worker.ContinueAsNewInput) -> NoReturn:
|
|
133
|
+
headers = input.headers
|
|
134
|
+
args = input.args
|
|
135
|
+
|
|
136
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
137
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
138
|
+
|
|
139
|
+
return super().continue_as_new(dataclasses.replace(input, headers=headers, args=args))
|
|
140
|
+
|
|
141
|
+
async def signal_child_workflow(self, input: temporalio.worker.SignalChildWorkflowInput) -> None:
|
|
142
|
+
headers = input.headers
|
|
143
|
+
args = input.args
|
|
144
|
+
|
|
145
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
146
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
147
|
+
|
|
148
|
+
await super().signal_child_workflow(dataclasses.replace(input, headers=headers, args=args))
|
|
149
|
+
|
|
150
|
+
async def signal_external_workflow(self, input: temporalio.worker.SignalExternalWorkflowInput) -> None:
|
|
151
|
+
headers = input.headers
|
|
152
|
+
args = input.args
|
|
153
|
+
|
|
154
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
155
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
156
|
+
|
|
157
|
+
await super().signal_external_workflow(dataclasses.replace(input, headers=headers, args=args))
|
|
158
|
+
|
|
159
|
+
def start_activity(self, input: temporalio.worker.StartActivityInput) -> temporalio.workflow.ActivityHandle:
|
|
160
|
+
headers = input.headers
|
|
161
|
+
args = input.args
|
|
162
|
+
|
|
163
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
164
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
165
|
+
|
|
166
|
+
return super().start_activity(dataclasses.replace(input, headers=headers, args=args))
|
|
167
|
+
|
|
168
|
+
async def start_child_workflow(
|
|
169
|
+
self, input: temporalio.worker.StartChildWorkflowInput
|
|
170
|
+
) -> temporalio.workflow.ChildWorkflowHandle:
|
|
171
|
+
headers = input.headers
|
|
172
|
+
args = input.args
|
|
173
|
+
|
|
174
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
175
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
176
|
+
|
|
177
|
+
return await super().start_child_workflow(dataclasses.replace(input, headers=headers, args=args))
|
|
178
|
+
|
|
179
|
+
def start_local_activity(
|
|
180
|
+
self, input: temporalio.worker.StartLocalActivityInput
|
|
181
|
+
) -> temporalio.workflow.ActivityHandle:
|
|
182
|
+
headers = input.headers
|
|
183
|
+
args = input.args
|
|
184
|
+
|
|
185
|
+
headers = add_encryption_encoding(self.root.encryption_state, headers)
|
|
186
|
+
args = mark_objects_to_be_encrypted(self.root.encryption_state, args)
|
|
187
|
+
|
|
188
|
+
return super().start_local_activity(dataclasses.replace(input, headers=headers, args=args))
|
kuflow_temporal_worker-3.2.0/kuflow_temporal_worker/_encryption/_kuflow_encryption_payload_codec.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
import base64
|
|
26
|
+
from collections.abc import Iterable
|
|
27
|
+
from datetime import timedelta
|
|
28
|
+
|
|
29
|
+
import temporalio.api.common.v1
|
|
30
|
+
from temporalio.converter import PayloadCodec
|
|
31
|
+
|
|
32
|
+
from kuflow_rest import KuFlowRestClient
|
|
33
|
+
|
|
34
|
+
from ._kuflow_cache import Cache
|
|
35
|
+
from ._kuflow_crypto import CIPHERS
|
|
36
|
+
from ._kuflow_encryption_instrumentation import (
|
|
37
|
+
METADATA_KEY_ENCODING,
|
|
38
|
+
METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID,
|
|
39
|
+
METADATA_VALUE_KUFLOW_ENCODING_ENCRYPTED,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class KuFlowEncryptionPayloadCodec(PayloadCodec):
|
|
44
|
+
rest_client: KuFlowRestClient
|
|
45
|
+
kms_key_cache: Cache[bytes]
|
|
46
|
+
|
|
47
|
+
def __init__(self, rest_client: KuFlowRestClient):
|
|
48
|
+
self.rest_client = rest_client
|
|
49
|
+
self.kms_key_cache = Cache[bytes](ttl=timedelta(hours=1))
|
|
50
|
+
|
|
51
|
+
async def encode(
|
|
52
|
+
self, payloads: Iterable[temporalio.api.common.v1.Payload]
|
|
53
|
+
) -> list[temporalio.api.common.v1.Payload]:
|
|
54
|
+
return [await self.encrypt(payload) for payload in payloads]
|
|
55
|
+
|
|
56
|
+
async def decode(
|
|
57
|
+
self, payloads: Iterable[temporalio.api.common.v1.Payload]
|
|
58
|
+
) -> list[temporalio.api.common.v1.Payload]:
|
|
59
|
+
return [await self.decrypt(payload) for payload in payloads]
|
|
60
|
+
|
|
61
|
+
async def encrypt(self, payload: temporalio.api.common.v1.Payload) -> temporalio.api.common.v1.Payload:
|
|
62
|
+
if payload.metadata is None or payload.metadata.get(METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID) is None:
|
|
63
|
+
return payload
|
|
64
|
+
|
|
65
|
+
key_id = payload.metadata.get(METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID).decode()
|
|
66
|
+
|
|
67
|
+
key_value = await self.retrieve_kms_key_cached(id=key_id)
|
|
68
|
+
|
|
69
|
+
cipher_text_bytes = CIPHERS.AES_256_GCM.encrypt(key_value, payload.SerializeToString())
|
|
70
|
+
|
|
71
|
+
cipher_text_value = base64.b64encode(cipher_text_bytes).decode("utf-8")
|
|
72
|
+
|
|
73
|
+
return temporalio.api.common.v1.Payload(
|
|
74
|
+
metadata={
|
|
75
|
+
METADATA_KEY_ENCODING: METADATA_VALUE_KUFLOW_ENCODING_ENCRYPTED.encode(),
|
|
76
|
+
METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID: key_id.encode(),
|
|
77
|
+
},
|
|
78
|
+
data=f"{CIPHERS.AES_256_GCM.algorithm}:{cipher_text_value}".encode(),
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
async def decrypt(self, payload: temporalio.api.common.v1.Payload) -> temporalio.api.common.v1.Payload:
|
|
82
|
+
if (
|
|
83
|
+
payload.metadata is None
|
|
84
|
+
or payload.metadata.get(METADATA_KEY_ENCODING, b"").decode() != METADATA_VALUE_KUFLOW_ENCODING_ENCRYPTED
|
|
85
|
+
):
|
|
86
|
+
return payload
|
|
87
|
+
|
|
88
|
+
if payload.data is None:
|
|
89
|
+
raise ValueError("Payload data is missing")
|
|
90
|
+
|
|
91
|
+
key_id_bytes = payload.metadata.get(METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID)
|
|
92
|
+
if key_id_bytes is None:
|
|
93
|
+
raise ValueError("Payload key id is missing")
|
|
94
|
+
|
|
95
|
+
key_id = key_id_bytes.decode()
|
|
96
|
+
|
|
97
|
+
key_value = await self.retrieve_kms_key_cached(id=key_id)
|
|
98
|
+
|
|
99
|
+
cipher_text = payload.data.decode()
|
|
100
|
+
|
|
101
|
+
cipher_text_algorithm, cipher_text_value = cipher_text.split(":", 1)
|
|
102
|
+
if cipher_text_algorithm is None or cipher_text_value is None:
|
|
103
|
+
raise ValueError("Invalid ciphered data format")
|
|
104
|
+
|
|
105
|
+
if cipher_text_algorithm != CIPHERS.AES_256_GCM.algorithm:
|
|
106
|
+
raise ValueError(f"Invalid ciphered data algorithm: {cipher_text_algorithm}")
|
|
107
|
+
|
|
108
|
+
cipher_text_value_bytes = base64.b64decode(cipher_text_value)
|
|
109
|
+
|
|
110
|
+
plain_text = CIPHERS.AES_256_GCM.decrypt(key_value, cipher_text_value_bytes)
|
|
111
|
+
|
|
112
|
+
return temporalio.api.common.v1.Payload.FromString(plain_text)
|
|
113
|
+
|
|
114
|
+
async def retrieve_kms_key_cached(self, id: str) -> bytes:
|
|
115
|
+
return await self.kms_key_cache.get(id, lambda: self.retrieve_kms_key(id=id))
|
|
116
|
+
|
|
117
|
+
async def retrieve_kms_key(self, id: str) -> bytes:
|
|
118
|
+
key = self.rest_client.kms.retrieve_kms_key(id=id)
|
|
119
|
+
|
|
120
|
+
return key.value
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
#
|
|
2
|
+
# MIT License
|
|
3
|
+
#
|
|
4
|
+
# Copyright (c) 2022 KuFlow
|
|
5
|
+
#
|
|
6
|
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
# of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
# in the Software without restriction, including without limitation the rights
|
|
9
|
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
# copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
# furnished to do so, subject to the following conditions:
|
|
12
|
+
#
|
|
13
|
+
# The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
# copies or substantial portions of the Software.
|
|
15
|
+
#
|
|
16
|
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
# SOFTWARE.
|
|
23
|
+
#
|
|
24
|
+
|
|
25
|
+
from typing import Any, Optional
|
|
26
|
+
|
|
27
|
+
import temporalio.api.common.v1
|
|
28
|
+
from temporalio.converter import EncodingPayloadConverter
|
|
29
|
+
|
|
30
|
+
from ._kuflow_encryption_instrumentation import (
|
|
31
|
+
METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID,
|
|
32
|
+
KuFlowEncryptionState,
|
|
33
|
+
KuFlowEncryptionWrapper,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class KuFlowEncryptionPayloadConverter(EncodingPayloadConverter):
|
|
38
|
+
delegate: EncodingPayloadConverter
|
|
39
|
+
|
|
40
|
+
def __init__(self, delegate: EncodingPayloadConverter) -> None:
|
|
41
|
+
self.delegate = delegate
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def encoding(self) -> str:
|
|
45
|
+
"""See base class."""
|
|
46
|
+
return self.delegate.encoding
|
|
47
|
+
|
|
48
|
+
def to_payload(self, value: Any) -> Optional[temporalio.api.common.v1.Payload]:
|
|
49
|
+
"""See base class."""
|
|
50
|
+
encryption_state: Optional[KuFlowEncryptionState] = None
|
|
51
|
+
if isinstance(value, KuFlowEncryptionWrapper):
|
|
52
|
+
encryption_state = value.encryption_state
|
|
53
|
+
value = value.value
|
|
54
|
+
|
|
55
|
+
payload = self.delegate.to_payload(value)
|
|
56
|
+
|
|
57
|
+
if payload is not None and encryption_state.key_id is not None:
|
|
58
|
+
payload = temporalio.api.common.v1.Payload(
|
|
59
|
+
metadata={
|
|
60
|
+
**payload.metadata,
|
|
61
|
+
METADATA_KEY_ENCODING_ENCRYPTED_KEY_ID: encryption_state.key_id.encode(),
|
|
62
|
+
},
|
|
63
|
+
data=payload.data,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
return payload
|
|
67
|
+
|
|
68
|
+
def from_payload(
|
|
69
|
+
self,
|
|
70
|
+
payload: temporalio.api.common.v1.Payload,
|
|
71
|
+
type_hint: Optional[type] = None,
|
|
72
|
+
) -> Any:
|
|
73
|
+
"""See base class."""
|
|
74
|
+
return self.delegate.from_payload(payload, type_hint)
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
import asyncio
|
|
26
26
|
import logging
|
|
27
27
|
import socket
|
|
28
|
-
from typing import Any,
|
|
28
|
+
from typing import Any, Optional
|
|
29
29
|
|
|
30
30
|
from azure.core.pipeline import PipelineResponse
|
|
31
31
|
from temporalio.client import Client
|
|
@@ -51,8 +51,8 @@ class KuFlowWorkerInformationNotifier:
|
|
|
51
51
|
temporal_config: TemporalConfig,
|
|
52
52
|
temporal_client: Client,
|
|
53
53
|
temporal_worker: Worker,
|
|
54
|
-
temporal_workflow_types: Optional[
|
|
55
|
-
temporal_activity_types: Optional[
|
|
54
|
+
temporal_workflow_types: Optional[set[str]] = None,
|
|
55
|
+
temporal_activity_types: Optional[set[str]] = None,
|
|
56
56
|
backoff: Optional[KuFlowWorkerInformationNotifierBackoff] = None,
|
|
57
57
|
):
|
|
58
58
|
if temporal_workflow_types is None:
|
|
@@ -67,8 +67,8 @@ class KuFlowWorkerInformationNotifier:
|
|
|
67
67
|
self._temporal_config = temporal_config
|
|
68
68
|
self._temporal_client = temporal_client
|
|
69
69
|
self._temporal_worker = temporal_worker
|
|
70
|
-
self._temporal_workflow_types:
|
|
71
|
-
self._temporal_activity_types:
|
|
70
|
+
self._temporal_workflow_types: set[str] = temporal_workflow_types
|
|
71
|
+
self._temporal_activity_types: set[str] = temporal_activity_types
|
|
72
72
|
self._backoff = backoff
|
|
73
73
|
|
|
74
74
|
self._delay_window_in_seconds = 5 * 60 # 5 min
|
|
@@ -100,7 +100,7 @@ class KuFlowWorkerInformationNotifier:
|
|
|
100
100
|
try:
|
|
101
101
|
http_response: Any = {}
|
|
102
102
|
|
|
103
|
-
def cls(pipeline_response: PipelineResponse, worker: models.Worker, ignored:
|
|
103
|
+
def cls(pipeline_response: PipelineResponse, worker: models.Worker, ignored: dict[str, Any]):
|
|
104
104
|
nonlocal http_response
|
|
105
105
|
|
|
106
106
|
http_response = pipeline_response.http_response
|
|
@@ -1,24 +1,31 @@
|
|
|
1
|
-
[
|
|
1
|
+
[project]
|
|
2
2
|
name = "kuflow-temporal-worker"
|
|
3
|
-
version = "3.0.0"
|
|
4
3
|
description = "KuFlow utilities to use Temporal.io"
|
|
5
4
|
license = "MIT"
|
|
6
|
-
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [{name = "KuFlow S.L.", email = "kuflow@kuflow.com"}]
|
|
7
|
+
dynamic = ["version", "dependencies"]
|
|
8
|
+
requires-python = '>=3.9,<4.0'
|
|
9
|
+
|
|
10
|
+
[project.urls]
|
|
7
11
|
homepage = "https://kuflow.com/"
|
|
8
|
-
documentation = "https://docs.kuflow.com/"
|
|
9
12
|
repository = "https://github.com/kuflow/kuflow-sdk-python"
|
|
10
|
-
|
|
11
|
-
include = ["VERSION", "README.md", "CHANGELOG.md"]
|
|
12
|
-
packages = [{ include = "kuflow_temporal_worker" }]
|
|
13
|
+
documentation = "https://docs.kuflow.com/"
|
|
13
14
|
|
|
14
15
|
[build-system]
|
|
15
16
|
requires = ["poetry_core>=1.0.0"]
|
|
16
17
|
build-backend = "poetry.core.masonry.api"
|
|
17
18
|
|
|
19
|
+
[tool.poetry]
|
|
20
|
+
version = "3.2.0"
|
|
21
|
+
include = ["VERSION", "README.md", "CHANGELOG.md"]
|
|
22
|
+
packages = [{ include = "kuflow_temporal_worker" }]
|
|
23
|
+
requires-poetry = '>=2.0,<3.0'
|
|
24
|
+
|
|
18
25
|
[tool.poetry.dependencies]
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
kuflow-temporal-common = "^3.2.0"
|
|
27
|
+
temporalio = "~1.10.0"
|
|
28
|
+
cryptography = "^38.0.1"
|
|
22
29
|
|
|
23
30
|
[tool.poetry.group.dev.dependencies]
|
|
24
31
|
mypy = "^1.11.1"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
3.0.0
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
# -*- coding: utf-8 -*-
|
|
2
|
-
from setuptools import setup
|
|
3
|
-
|
|
4
|
-
packages = \
|
|
5
|
-
['kuflow_temporal_worker']
|
|
6
|
-
|
|
7
|
-
package_data = \
|
|
8
|
-
{'': ['*']}
|
|
9
|
-
|
|
10
|
-
install_requires = \
|
|
11
|
-
['kuflow-temporal-common>=3.0.0,<4.0.0', 'temporalio>=1.6.0,<1.7.0']
|
|
12
|
-
|
|
13
|
-
setup_kwargs = {
|
|
14
|
-
'name': 'kuflow-temporal-worker',
|
|
15
|
-
'version': '3.0.0',
|
|
16
|
-
'description': 'KuFlow utilities to use Temporal.io',
|
|
17
|
-
'long_description': '[](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)\n[](https://pypi.org/project/kuflow-temporal-worker)\n[](https://pypi.org/project/kuflow-temporal-worker)\n\n# KuFlow Temporal worker\n\nTemporal worker utilities to connect to KuFlow.\n\n## Documentation\n\nMore detailed docs are available in the [documentation pages](https://docs.kuflow.com/developers/).\n\n## Contributing\n\nWe are happy to receive your help and comments, together we will dance a wonderful KuFlow. Please review our [contribution guide](CONTRIBUTING.md).\n\n## License\n\n[MIT License](https://github.com/kuflow/kuflow-sdk-python/blob/master/LICENSE)\n',
|
|
18
|
-
'author': 'KuFlow S.L.',
|
|
19
|
-
'author_email': 'kuflow@kuflow.com',
|
|
20
|
-
'maintainer': 'None',
|
|
21
|
-
'maintainer_email': 'None',
|
|
22
|
-
'url': 'https://kuflow.com/',
|
|
23
|
-
'packages': packages,
|
|
24
|
-
'package_data': package_data,
|
|
25
|
-
'install_requires': install_requires,
|
|
26
|
-
'python_requires': '>=3.8,<4.0',
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
setup(**setup_kwargs)
|
|
File without changes
|
{kuflow_temporal_worker-3.0.0 → kuflow_temporal_worker-3.2.0}/kuflow_temporal_worker/__init__.py
RENAMED
|
File without changes
|