diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/README.md b/core/src/main/java/io/temporal/samples/nexusserializationcontext/README.md index 32fc41ba..cc668463 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/README.md +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/README.md @@ -1,98 +1,129 @@ # Nexus serialization context -This sample calls a synchronous and an asynchronous Nexus operation through each of -two endpoints. Each endpoint routes to its own handler worker, which registers both -`SyncEchoService` and `AsyncEchoService`. The caller's `NexusCodec` uses -`NexusSerializationContext` to select the `PayloadCodec` registered for each endpoint. -The sample uses these keys: - -- Key A: compresses with zlib, then encrypts synchronous and asynchronous payloads for `nexus-serialization-compressed-encrypted`. -- Key B: encrypts synchronous and asynchronous payloads for `nexus-serialization-encrypted`. -- Key C: encrypts the caller workflow's input and final result. - -The caller configures a codec for each endpoint and a separate codec for its own -workflow input and result. Each handler worker uses the fixed key for its endpoint. - -The caller schedules all four operations before waiting for their results, so each -result must be decoded using the context of its own endpoint. The caller's -`NexusCodec` uses Key C for its own workflow payloads, which have no Nexus endpoint. - -For both Nexus endpoints, the outer encrypted payload stores the endpoint name in -`nexus-endpoint-name` metadata alongside `binary/nexus-aes-gcm` and a sample key ID -(`key-a` or `key-b`). A Codec Server can use the endpoint name to select the matching -key and decompression chain without SDK context. - -For the compressed endpoint, the outer payload's decoded metadata looks like: +This sample uses `NexusSerializationContext` to select an encryption key for each Nexus +endpoint. The caller invokes synchronous and workflow-backed asynchronous operations +through four endpoints. `CompressedEncryptedHandlerWorker` compresses and then +encrypts Nexus payloads. `EncryptedHandlerWorker` encrypts without +compression. Each handler selects between its own key 1 and key 2 using +the endpoint in the Nexus context. +The caller and each handler run in separate namespaces. + +| Handler | Endpoint | Encryption key | Nexus payload encoding | +|---|---|---|---| +| `CompressedEncryptedHandlerWorker` | `nexus-serialization-compressed-encrypted-1` | `COMPRESSED_ENCRYPTED_KEY_1` | zlib, then AES-GCM | +| `CompressedEncryptedHandlerWorker` | `nexus-serialization-compressed-encrypted-2` | `COMPRESSED_ENCRYPTED_KEY_2` | zlib, then AES-GCM | +| `EncryptedHandlerWorker` | `nexus-serialization-encrypted-1` | `ENCRYPTED_KEY_1` | AES-GCM | +| `EncryptedHandlerWorker` | `nexus-serialization-encrypted-2` | `ENCRYPTED_KEY_2` | AES-GCM | + +These four endpoint keys are distinct 128-bit AES keys. Compression runs before encryption; +decoding decrypts before decompressing. AES-GCM authenticates the ciphertext. +The AES-GCM and zlib codecs are implemented in this sample; Nexus supplies the endpoint +context used to select them. + +Each worker configures `NexusCodec` with an endpoint-to-codec map and a default codec +for ordinary workflow payloads. The caller uses a separate `CALLER_WORKFLOW_KEY` for +its own input and final result, keeping those payloads independent of the keys shared +with Nexus handlers. Each handler reuses its key 1 for backing workflow inputs. + +| Ordinary workflow payload | Encryption key | +|---|---| +| Caller workflow input and final result | `CALLER_WORKFLOW_KEY` | +| Compressed/encrypted handler workflow inputs | `COMPRESSED_ENCRYPTED_KEY_1` | +| Encrypted handler workflow inputs | `ENCRYPTED_KEY_1` | + +These workflow payloads use AES-GCM without compression or endpoint metadata. +An async Nexus result uses the key and compression chain selected by its endpoint, +even when that differs from the backing workflow's input encryption. + +For synchronous operations, the SDK supplies Nexus context when decoding inputs and +encoding results. When an asynchronous handler starts `EchoWorkflow`, the SDK includes +the Nexus endpoint, service, and operation in the workflow-start request. The server +stores these fields in the `WorkflowExecutionStarted` history event. The worker SDK +restores the Nexus context from that event when encoding the workflow's result, so +`NexusCodec` can select the endpoint's codec and key from the worker's local configuration. +The workflow's input still uses ordinary workflow context; this sample's default codec +encrypts it with that handler's key 1. + +The caller starts all eight operations before waiting for their results. Each operation +keeps its own endpoint context, even when operations for different keys are in flight. +No custom interceptor or workflow-header propagation is required. + +The outer encrypted payload includes `encoding`, `encryption-key-id`, and, for Nexus +payloads, `nexus-endpoint-name` metadata. For example: ```text encoding: binary/nexus-aes-gcm -encryption-key-id: key-a -nexus-endpoint-name: nexus-serialization-compressed-encrypted +encryption-key-id: compressed-encrypted-1 +nexus-endpoint-name: nexus-serialization-compressed-encrypted-1 ``` -The asynchronous results have `encryption-key-id: key-a` or `key-b` and their respective -endpoint names in the outer payload metadata. -The caller workflow's input and final result use `encryption-key-id: key-c`; they do not -have endpoint metadata. The starter uses the same converter as the caller worker, so it -can decode the final result before printing it. - -`NexusSerializationContext` works end to end for synchronous Nexus operations. -For an asynchronous operation, the handler's final result is serialized as a workflow -result and does not receive `NexusSerializationContext`. We plan to add -`NexusSerializationContext` support for asynchronous operation results in the Java SDK. -Until then, the sample's `NexusEndpointInterceptor` captures the endpoint when the -handler starts the backing `EchoWorkflow`. `NexusEndpointContextPropagator` saves it in -the workflow headers and restores it on the workflow thread. Each handler's codec uses -its fixed key to encrypt the workflow result and includes the propagated endpoint name -in the outer payload metadata. This propagation is needed for the endpoint metadata; -the handler already knows which key to use. When the result reaches the caller, the SDK -supplies `NexusSerializationContext` to decode it. - -This endpoint propagation covers asynchronous operations backed by workflows. If the -endpoint is not propagated, the result remains encrypted with the handler's fixed key -but lacks the endpoint name in its metadata. +A Codec Server can use that metadata to select the key and decompression chain without +SDK context. Ordinary workflow payloads have a key ID but no endpoint metadata or compression. The hard-coded keys are only for this local example. For production encryption, use a secure key store, as in the [AWS Encryption SDK sample](../keymanagementencryption/awsencryptionsdk/README.md). -Requires Java SDK 1.40.0 or later and Temporal Server 1.30.0 or later with Nexus enabled -so the handler can read the endpoint name. +## Prerequisites + +Use a Temporal Server that supports Nexus serialization-context propagation for +workflow-backed asynchronous operations. For local development, download +[Temporal CLI `v1.9.3-nexus-serialization-context`](https://github.com/temporalio/cli/releases/tag/v1.9.3-nexus-serialization-context). +Keep this prerelease binary separate from your stable CLI. The commands below use +`./temporal` to run the downloaded binary from the repository root. ## Run locally -Start a Temporal dev server: +The caller and each handler use separate namespaces. Each worker polls a task queue +with the same name as its namespace. Both endpoints for a handler target that handler's +namespace and task queue. + +| Worker | Namespace and task queue | +|---|---| +| Caller | `nexus-serialization-caller` | +| Compressed/encrypted handler | `nexus-serialization-compressed-encrypted-handler` | +| Encrypted handler | `nexus-serialization-encrypted-handler` | + +Start the dev server: ```bash -temporal server start-dev +./temporal server start-dev \ + --namespace nexus-serialization-caller \ + --namespace nexus-serialization-compressed-encrypted-handler \ + --namespace nexus-serialization-encrypted-handler ``` -In another terminal, create the namespaces and endpoints: +Create two endpoints for each handler worker: ```bash -temporal operator namespace create --namespace nexus-serialization-caller -temporal operator namespace create --namespace nexus-serialization-key-a-handler -temporal operator namespace create --namespace nexus-serialization-key-b-handler -temporal operator nexus endpoint create \ - --name nexus-serialization-compressed-encrypted \ - --target-namespace nexus-serialization-key-a-handler \ - --target-task-queue nexus-serialization-key-a-handler -temporal operator nexus endpoint create \ - --name nexus-serialization-encrypted \ - --target-namespace nexus-serialization-key-b-handler \ - --target-task-queue nexus-serialization-key-b-handler +./temporal operator nexus endpoint create \ + --name nexus-serialization-compressed-encrypted-1 \ + --target-namespace nexus-serialization-compressed-encrypted-handler \ + --target-task-queue nexus-serialization-compressed-encrypted-handler +./temporal operator nexus endpoint create \ + --name nexus-serialization-compressed-encrypted-2 \ + --target-namespace nexus-serialization-compressed-encrypted-handler \ + --target-task-queue nexus-serialization-compressed-encrypted-handler +./temporal operator nexus endpoint create \ + --name nexus-serialization-encrypted-1 \ + --target-namespace nexus-serialization-encrypted-handler \ + --target-task-queue nexus-serialization-encrypted-handler +./temporal operator nexus endpoint create \ + --name nexus-serialization-encrypted-2 \ + --target-namespace nexus-serialization-encrypted-handler \ + --target-task-queue nexus-serialization-encrypted-handler ``` Run each of the following in its own terminal from the repository root: ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusserializationcontext.handler.CompressedEncryptedHandlerWorker \ - --args="-namespace nexus-serialization-key-a-handler" + --args="-namespace nexus-serialization-compressed-encrypted-handler" ``` ```bash ./gradlew -q :core:execute -PmainClass=io.temporal.samples.nexusserializationcontext.handler.EncryptedHandlerWorker \ - --args="-namespace nexus-serialization-key-b-handler" + --args="-namespace nexus-serialization-encrypted-handler" ``` ```bash @@ -105,11 +136,13 @@ Run each of the following in its own terminal from the repository root: --args="-namespace nexus-serialization-caller" ``` -The starter will print: +The starter prints a sync result and an async result for each endpoint. All eight +results should be `Hello from Nexus`. -```text -Compressed and encrypted endpoint sync result: Hello from Nexus -Encrypted endpoint sync result: Hello from Nexus -Compressed and encrypted endpoint async result: Hello from Nexus -Encrypted endpoint async result: Hello from Nexus +## Test + +Run the codec tests: + +```bash +./gradlew :core:test --tests 'io.temporal.samples.nexusserializationcontext.codec.NexusCodecTest' ``` diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/SampleConfig.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/SampleConfig.java index 1ba965c4..1abdf080 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/SampleConfig.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/SampleConfig.java @@ -1,18 +1,25 @@ package io.temporal.samples.nexusserializationcontext; public final class SampleConfig { - public static final String COMPRESSED_ENCRYPTED_ENDPOINT = - "nexus-serialization-compressed-encrypted"; - public static final String ENCRYPTED_ENDPOINT = "nexus-serialization-encrypted"; + public static final String COMPRESSED_ENCRYPTED_1_ENDPOINT = + "nexus-serialization-compressed-encrypted-1"; + public static final String ENCRYPTED_1_ENDPOINT = "nexus-serialization-encrypted-1"; + public static final String COMPRESSED_ENCRYPTED_2_ENDPOINT = + "nexus-serialization-compressed-encrypted-2"; + public static final String ENCRYPTED_2_ENDPOINT = "nexus-serialization-encrypted-2"; public static final String ENDPOINT_METADATA_KEY = "nexus-endpoint-name"; - public static final String KEY_A_ID = "key-a"; - public static final String KEY_B_ID = "key-b"; - public static final String KEY_C_ID = "key-c"; + public static final String COMPRESSED_ENCRYPTED_KEY_1_ID = "compressed-encrypted-1"; + public static final String ENCRYPTED_KEY_1_ID = "encrypted-1"; + public static final String COMPRESSED_ENCRYPTED_KEY_2_ID = "compressed-encrypted-2"; + public static final String ENCRYPTED_KEY_2_ID = "encrypted-2"; + public static final String CALLER_WORKFLOW_KEY_ID = "caller-workflow"; // Hard-coded keys are only for this local sample. - public static final String KEY_A_VALUE = "sample-key-A-123"; - public static final String KEY_B_VALUE = "sample-key-B-123"; - public static final String KEY_C_VALUE = "sample-key-C-123"; + public static final String COMPRESSED_ENCRYPTED_KEY_1 = "handler-a-key-01"; + public static final String ENCRYPTED_KEY_1 = "handler-b-key-01"; + public static final String COMPRESSED_ENCRYPTED_KEY_2 = "handler-a-key-02"; + public static final String ENCRYPTED_KEY_2 = "handler-b-key-02"; + public static final String CALLER_WORKFLOW_KEY = "sample-key-C-123"; private SampleConfig() {} } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerStarter.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerStarter.java index 7defd522..2da33df4 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerStarter.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerStarter.java @@ -4,6 +4,7 @@ import io.temporal.client.WorkflowClientOptions; import io.temporal.client.WorkflowOptions; import io.temporal.samples.nexus.options.ClientOptions; +import io.temporal.samples.nexusserializationcontext.SampleConfig; public class CallerStarter { public static void main(String[] args) { @@ -18,12 +19,28 @@ public static void main(String[] args) { EndpointResults results = workflow.echoThroughEndpoints("Hello from Nexus"); System.out.println( - "Compressed and encrypted endpoint sync result: " - + results.compressedEncryptedSyncResult()); - System.out.println("Encrypted endpoint sync result: " + results.encryptedSyncResult()); + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT + + " sync result: " + + results.compressedEncrypted1SyncResult()); System.out.println( - "Compressed and encrypted endpoint async result: " - + results.compressedEncryptedAsyncResult()); - System.out.println("Encrypted endpoint async result: " + results.encryptedAsyncResult()); + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT + + " async result: " + + results.compressedEncrypted1AsyncResult()); + System.out.println( + SampleConfig.ENCRYPTED_1_ENDPOINT + " sync result: " + results.encrypted1SyncResult()); + System.out.println( + SampleConfig.ENCRYPTED_1_ENDPOINT + " async result: " + results.encrypted1AsyncResult()); + System.out.println( + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT + + " sync result: " + + results.compressedEncrypted2SyncResult()); + System.out.println( + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT + + " async result: " + + results.compressedEncrypted2AsyncResult()); + System.out.println( + SampleConfig.ENCRYPTED_2_ENDPOINT + " sync result: " + results.encrypted2SyncResult()); + System.out.println( + SampleConfig.ENCRYPTED_2_ENDPOINT + " async result: " + results.encrypted2AsyncResult()); } } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorker.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorker.java index 3c993809..474be9b9 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorker.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorker.java @@ -34,25 +34,42 @@ public static void main(String[] args) { } public static DataConverter dataConverter() { - SecretKey keyA = - new SecretKeySpec(SampleConfig.KEY_A_VALUE.getBytes(StandardCharsets.UTF_8), "AES"); - SecretKey keyB = - new SecretKeySpec(SampleConfig.KEY_B_VALUE.getBytes(StandardCharsets.UTF_8), "AES"); - SecretKey keyC = - new SecretKeySpec(SampleConfig.KEY_C_VALUE.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey compressedEncryptedKey1 = + new SecretKeySpec( + SampleConfig.COMPRESSED_ENCRYPTED_KEY_1.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey encryptedKey1 = + new SecretKeySpec(SampleConfig.ENCRYPTED_KEY_1.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey compressedEncryptedKey2 = + new SecretKeySpec( + SampleConfig.COMPRESSED_ENCRYPTED_KEY_2.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey encryptedKey2 = + new SecretKeySpec(SampleConfig.ENCRYPTED_KEY_2.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey callerWorkflowKey = + new SecretKeySpec(SampleConfig.CALLER_WORKFLOW_KEY.getBytes(StandardCharsets.UTF_8), "AES"); + PayloadCodec compressedEncryptedKey1Encryption = + new AesGcmCodec(SampleConfig.COMPRESSED_ENCRYPTED_KEY_1_ID, compressedEncryptedKey1); + PayloadCodec encryptedKey1Encryption = + new AesGcmCodec(SampleConfig.ENCRYPTED_KEY_1_ID, encryptedKey1); + PayloadCodec compressedEncryptedKey2Encryption = + new AesGcmCodec(SampleConfig.COMPRESSED_ENCRYPTED_KEY_2_ID, compressedEncryptedKey2); + PayloadCodec encryptedKey2Encryption = + new AesGcmCodec(SampleConfig.ENCRYPTED_KEY_2_ID, encryptedKey2); // ChainCodec encodes last to first: compress, then encrypt. - PayloadCodec compressedEncrypted = - new ChainCodec(List.of(new AesGcmCodec(SampleConfig.KEY_A_ID, keyA), new ZlibCodec())); - PayloadCodec encrypted = new AesGcmCodec(SampleConfig.KEY_B_ID, keyB); + Map nexusEndpointCodecs = + Map.of( + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT, + new ChainCodec(List.of(compressedEncryptedKey1Encryption, new ZlibCodec())), + SampleConfig.ENCRYPTED_1_ENDPOINT, + encryptedKey1Encryption, + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT, + new ChainCodec(List.of(compressedEncryptedKey2Encryption, new ZlibCodec())), + SampleConfig.ENCRYPTED_2_ENDPOINT, + encryptedKey2Encryption); + // Ordinary caller workflow payloads use a separate key from Nexus payloads. + PayloadCodec callerWorkflowEncryption = + new AesGcmCodec(SampleConfig.CALLER_WORKFLOW_KEY_ID, callerWorkflowKey); return new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), - List.of( - new NexusCodec( - Map.of( - SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, - compressedEncrypted, - SampleConfig.ENCRYPTED_ENDPOINT, - encrypted), - new AesGcmCodec(SampleConfig.KEY_C_ID, keyC)))); + List.of(new NexusCodec(nexusEndpointCodecs, callerWorkflowEncryption))); } } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorkflowImpl.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorkflowImpl.java index 9e0505b0..53cb0965 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorkflowImpl.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/CallerWorkflowImpl.java @@ -12,29 +12,50 @@ public class CallerWorkflowImpl implements CallerWorkflow { @Override public EndpointResults echoThroughEndpoints(String message) { - SyncEchoService compressedEncryptedService = - serviceFor(SyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT); - SyncEchoService encryptedService = - serviceFor(SyncEchoService.class, SampleConfig.ENCRYPTED_ENDPOINT); - AsyncEchoService compressedEncryptedAsyncService = - serviceFor(AsyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT); - AsyncEchoService encryptedAsyncService = - serviceFor(AsyncEchoService.class, SampleConfig.ENCRYPTED_ENDPOINT); + SyncEchoService compressedEncrypted1SyncService = + serviceFor(SyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT); + SyncEchoService encrypted1SyncService = + serviceFor(SyncEchoService.class, SampleConfig.ENCRYPTED_1_ENDPOINT); + SyncEchoService compressedEncrypted2SyncService = + serviceFor(SyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT); + SyncEchoService encrypted2SyncService = + serviceFor(SyncEchoService.class, SampleConfig.ENCRYPTED_2_ENDPOINT); + AsyncEchoService compressedEncrypted1AsyncService = + serviceFor(AsyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT); + AsyncEchoService encrypted1AsyncService = + serviceFor(AsyncEchoService.class, SampleConfig.ENCRYPTED_1_ENDPOINT); + AsyncEchoService compressedEncrypted2AsyncService = + serviceFor(AsyncEchoService.class, SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT); + AsyncEchoService encrypted2AsyncService = + serviceFor(AsyncEchoService.class, SampleConfig.ENCRYPTED_2_ENDPOINT); + + // Start all eight operations before awaiting results. Each keeps its endpoint context. + NexusOperationHandle compressedEncrypted1Sync = + Workflow.startNexusOperation(compressedEncrypted1SyncService::echo, message); + NexusOperationHandle compressedEncrypted1Async = + Workflow.startNexusOperation(compressedEncrypted1AsyncService::echoAsync, message); + NexusOperationHandle encrypted1Sync = + Workflow.startNexusOperation(encrypted1SyncService::echo, message); + NexusOperationHandle encrypted1Async = + Workflow.startNexusOperation(encrypted1AsyncService::echoAsync, message); + NexusOperationHandle compressedEncrypted2Sync = + Workflow.startNexusOperation(compressedEncrypted2SyncService::echo, message); + NexusOperationHandle compressedEncrypted2Async = + Workflow.startNexusOperation(compressedEncrypted2AsyncService::echoAsync, message); + NexusOperationHandle encrypted2Sync = + Workflow.startNexusOperation(encrypted2SyncService::echo, message); + NexusOperationHandle encrypted2Async = + Workflow.startNexusOperation(encrypted2AsyncService::echoAsync, message); - // Start all operations before awaiting results. Each result keeps its endpoint context. - NexusOperationHandle compressedEncryptedSync = - Workflow.startNexusOperation(compressedEncryptedService::echo, message); - NexusOperationHandle encryptedSync = - Workflow.startNexusOperation(encryptedService::echo, message); - NexusOperationHandle compressedEncryptedAsync = - Workflow.startNexusOperation(compressedEncryptedAsyncService::echoAsync, message); - NexusOperationHandle encryptedAsync = - Workflow.startNexusOperation(encryptedAsyncService::echoAsync, message); return new EndpointResults( - compressedEncryptedSync.getResult().get(), - encryptedSync.getResult().get(), - compressedEncryptedAsync.getResult().get(), - encryptedAsync.getResult().get()); + compressedEncrypted1Sync.getResult().get(), + encrypted1Sync.getResult().get(), + compressedEncrypted2Sync.getResult().get(), + encrypted2Sync.getResult().get(), + compressedEncrypted1Async.getResult().get(), + encrypted1Async.getResult().get(), + compressedEncrypted2Async.getResult().get(), + encrypted2Async.getResult().get()); } private static T serviceFor(Class serviceClass, String endpoint) { diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/EndpointResults.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/EndpointResults.java index 741f9286..ff729460 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/EndpointResults.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/caller/EndpointResults.java @@ -1,7 +1,11 @@ package io.temporal.samples.nexusserializationcontext.caller; public record EndpointResults( - String compressedEncryptedSyncResult, - String encryptedSyncResult, - String compressedEncryptedAsyncResult, - String encryptedAsyncResult) {} + String compressedEncrypted1SyncResult, + String encrypted1SyncResult, + String compressedEncrypted2SyncResult, + String encrypted2SyncResult, + String compressedEncrypted1AsyncResult, + String encrypted1AsyncResult, + String compressedEncrypted2AsyncResult, + String encrypted2AsyncResult) {} diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/AesGcmCodec.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/AesGcmCodec.java index 0208849a..f13899b5 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/AesGcmCodec.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/AesGcmCodec.java @@ -9,7 +9,6 @@ import io.temporal.payload.context.NexusSerializationContext; import io.temporal.payload.context.SerializationContext; import io.temporal.samples.nexusserializationcontext.SampleConfig; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointContextPropagator; import java.nio.ByteBuffer; import java.security.GeneralSecurityException; import java.security.SecureRandom; @@ -19,7 +18,6 @@ import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.GCMParameterSpec; -import org.apache.commons.lang.StringUtils; /** Encrypts payloads with a configured key and includes endpoint metadata when available. */ public final class AesGcmCodec implements PayloadCodec { @@ -58,8 +56,6 @@ public PayloadCodec withContext(@Nonnull SerializationContext context) { @Override @Nonnull public List encode(@Nonnull List payloads) { - String endpointName = - StringUtils.defaultIfBlank(endpoint, NexusEndpointContextPropagator.currentEndpoint()); List encoded = new ArrayList<>(payloads.size()); for (Payload payload : payloads) { Payload.Builder encrypted = @@ -69,9 +65,9 @@ public List encode(@Nonnull List payloads) { ByteString.copyFromUtf8(NexusEncoding.AES_GCM.encodingName())) .putMetadata(KEY_ID_METADATA_KEY, ByteString.copyFromUtf8(keyId)) .setData(ByteString.copyFrom(encrypt(payload.toByteArray()))); - if (StringUtils.isNotBlank(endpointName)) { + if (endpoint != null && !endpoint.isEmpty()) { encrypted.putMetadata( - SampleConfig.ENDPOINT_METADATA_KEY, ByteString.copyFromUtf8(endpointName)); + SampleConfig.ENDPOINT_METADATA_KEY, ByteString.copyFromUtf8(endpoint)); } encoded.add(encrypted.build()); } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodec.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodec.java index 3c6284ea..55ea820f 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodec.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodec.java @@ -10,12 +10,12 @@ import javax.annotation.Nonnull; /** - * Selects an endpoint codec for synchronous and asynchronous Nexus payloads. The caller's own - * workflow payloads use a separate codec. + * Selects an endpoint codec for synchronous and asynchronous Nexus payloads. Ordinary workflow + * payloads use a separate codec. */ public final class NexusCodec implements PayloadCodec { private final Map codecsByEndpoint; - // The caller workflow has no Nexus endpoint, so Key C encrypts its input and final result. + // Payloads without Nexus context use the local workflow codec. private final PayloadCodec workflowCodec; public NexusCodec(Map codecsByEndpoint, PayloadCodec workflowCodec) { @@ -29,7 +29,7 @@ public PayloadCodec withContext(@Nonnull SerializationContext context) { if (context instanceof NexusSerializationContext nexusContext) { return codecFor(nexusContext.getEndpoint()).withContext(context); } - // Caller workflow input and result have no Nexus endpoint; use the caller's Key C codec. + // Ordinary workflow payloads use the worker's configured default codec. return workflowCodec.withContext(context); } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/CompressedEncryptedHandlerWorker.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/CompressedEncryptedHandlerWorker.java index 9640b0f2..27819b84 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/CompressedEncryptedHandlerWorker.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/CompressedEncryptedHandlerWorker.java @@ -6,36 +6,28 @@ import io.temporal.common.converter.DataConverter; import io.temporal.common.converter.DefaultDataConverter; import io.temporal.payload.codec.ChainCodec; +import io.temporal.payload.codec.PayloadCodec; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexusserializationcontext.SampleConfig; import io.temporal.samples.nexusserializationcontext.codec.AesGcmCodec; +import io.temporal.samples.nexusserializationcontext.codec.NexusCodec; import io.temporal.samples.nexusserializationcontext.codec.ZlibCodec; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointContextPropagator; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointInterceptor; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; -import io.temporal.worker.WorkerFactoryOptions; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class CompressedEncryptedHandlerWorker { - private static final String TASK_QUEUE = "nexus-serialization-key-a-handler"; + private static final String TASK_QUEUE = "nexus-serialization-compressed-encrypted-handler"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient( - args, - WorkflowClientOptions.newBuilder() - .setDataConverter(dataConverter()) - .setContextPropagators(List.of(new NexusEndpointContextPropagator()))); - WorkerFactory factory = - WorkerFactory.newInstance( - client, - WorkerFactoryOptions.newBuilder() - .setWorkerInterceptors(new NexusEndpointInterceptor()) - .build()); + args, WorkflowClientOptions.newBuilder().setDataConverter(dataConverter())); + WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(EchoWorkflowImpl.class); worker.registerNexusServiceImplementation(new SyncEchoServiceImpl()); @@ -44,13 +36,27 @@ public static void main(String[] args) { } public static DataConverter dataConverter() { - SecretKey keyA = - new SecretKeySpec(SampleConfig.KEY_A_VALUE.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey key1 = + new SecretKeySpec( + SampleConfig.COMPRESSED_ENCRYPTED_KEY_1.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey key2 = + new SecretKeySpec( + SampleConfig.COMPRESSED_ENCRYPTED_KEY_2.getBytes(StandardCharsets.UTF_8), "AES"); + PayloadCodec key1Encryption = new AesGcmCodec(SampleConfig.COMPRESSED_ENCRYPTED_KEY_1_ID, key1); + PayloadCodec key2Encryption = new AesGcmCodec(SampleConfig.COMPRESSED_ENCRYPTED_KEY_2_ID, key2); // ChainCodec encodes last to first: compress, then encrypt. + PayloadCodec compressedKey1Encryption = + new ChainCodec(List.of(key1Encryption, new ZlibCodec())); + PayloadCodec compressedKey2Encryption = + new ChainCodec(List.of(key2Encryption, new ZlibCodec())); + Map nexusEndpointCodecs = + Map.of( + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT, compressedKey1Encryption, + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT, compressedKey2Encryption); + // Ordinary workflow inputs use this handler's key 1, regardless of the Nexus endpoint. + PayloadCodec handlerWorkflowEncryption = key1Encryption; return new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), - List.of( - new ChainCodec( - List.of(new AesGcmCodec(SampleConfig.KEY_A_ID, keyA), new ZlibCodec())))); + List.of(new NexusCodec(nexusEndpointCodecs, handlerWorkflowEncryption))); } } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/EncryptedHandlerWorker.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/EncryptedHandlerWorker.java index 85525aac..e31bd842 100644 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/EncryptedHandlerWorker.java +++ b/core/src/main/java/io/temporal/samples/nexusserializationcontext/handler/EncryptedHandlerWorker.java @@ -5,35 +5,27 @@ import io.temporal.common.converter.CodecDataConverter; import io.temporal.common.converter.DataConverter; import io.temporal.common.converter.DefaultDataConverter; +import io.temporal.payload.codec.PayloadCodec; import io.temporal.samples.nexus.options.ClientOptions; import io.temporal.samples.nexusserializationcontext.SampleConfig; import io.temporal.samples.nexusserializationcontext.codec.AesGcmCodec; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointContextPropagator; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointInterceptor; +import io.temporal.samples.nexusserializationcontext.codec.NexusCodec; import io.temporal.worker.Worker; import io.temporal.worker.WorkerFactory; -import io.temporal.worker.WorkerFactoryOptions; import java.nio.charset.StandardCharsets; import java.util.List; +import java.util.Map; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class EncryptedHandlerWorker { - private static final String TASK_QUEUE = "nexus-serialization-key-b-handler"; + private static final String TASK_QUEUE = "nexus-serialization-encrypted-handler"; public static void main(String[] args) { WorkflowClient client = ClientOptions.getWorkflowClient( - args, - WorkflowClientOptions.newBuilder() - .setDataConverter(dataConverter()) - .setContextPropagators(List.of(new NexusEndpointContextPropagator()))); - WorkerFactory factory = - WorkerFactory.newInstance( - client, - WorkerFactoryOptions.newBuilder() - .setWorkerInterceptors(new NexusEndpointInterceptor()) - .build()); + args, WorkflowClientOptions.newBuilder().setDataConverter(dataConverter())); + WorkerFactory factory = WorkerFactory.newInstance(client); Worker worker = factory.newWorker(TASK_QUEUE); worker.registerWorkflowImplementationTypes(EchoWorkflowImpl.class); worker.registerNexusServiceImplementation(new SyncEchoServiceImpl()); @@ -42,10 +34,20 @@ public static void main(String[] args) { } public static DataConverter dataConverter() { - SecretKey keyB = - new SecretKeySpec(SampleConfig.KEY_B_VALUE.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey key1 = + new SecretKeySpec(SampleConfig.ENCRYPTED_KEY_1.getBytes(StandardCharsets.UTF_8), "AES"); + SecretKey key2 = + new SecretKeySpec(SampleConfig.ENCRYPTED_KEY_2.getBytes(StandardCharsets.UTF_8), "AES"); + PayloadCodec key1Encryption = new AesGcmCodec(SampleConfig.ENCRYPTED_KEY_1_ID, key1); + PayloadCodec key2Encryption = new AesGcmCodec(SampleConfig.ENCRYPTED_KEY_2_ID, key2); + Map nexusEndpointCodecs = + Map.of( + SampleConfig.ENCRYPTED_1_ENDPOINT, key1Encryption, + SampleConfig.ENCRYPTED_2_ENDPOINT, key2Encryption); + // Ordinary workflow inputs use this handler's key 1, regardless of the Nexus endpoint. + PayloadCodec handlerWorkflowEncryption = key1Encryption; return new CodecDataConverter( DefaultDataConverter.newDefaultInstance(), - List.of(new AesGcmCodec(SampleConfig.KEY_B_ID, keyB))); + List.of(new NexusCodec(nexusEndpointCodecs, handlerWorkflowEncryption))); } } diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointContextPropagator.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointContextPropagator.java deleted file mode 100644 index 394275f1..00000000 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointContextPropagator.java +++ /dev/null @@ -1,51 +0,0 @@ -package io.temporal.samples.nexusserializationcontext.propagation; - -import io.temporal.api.common.v1.Payload; -import io.temporal.common.context.ContextPropagator; -import io.temporal.common.converter.DataConverter; -import io.temporal.samples.nexusserializationcontext.SampleConfig; -import java.util.Map; -import org.slf4j.MDC; - -/** Carries the Nexus endpoint from a handler into the workflow it starts. */ -public final class NexusEndpointContextPropagator implements ContextPropagator { - private static final DataConverter CONVERTER = DataConverter.getDefaultInstance(); - - public static String currentEndpoint() { - return MDC.get(SampleConfig.ENDPOINT_METADATA_KEY); - } - - @Override - public String getName() { - return NexusEndpointContextPropagator.class.getName(); - } - - @Override - public Object getCurrentContext() { - return currentEndpoint(); - } - - @Override - public void setCurrentContext(Object context) { - if (context == null) { - MDC.remove(SampleConfig.ENDPOINT_METADATA_KEY); - } else { - MDC.put(SampleConfig.ENDPOINT_METADATA_KEY, (String) context); - } - } - - @Override - public Map serializeContext(Object context) { - if (context == null) { - return Map.of(); - } - return Map.of( - SampleConfig.ENDPOINT_METADATA_KEY, CONVERTER.toPayload((String) context).orElseThrow()); - } - - @Override - public Object deserializeContext(Map header) { - Payload payload = header.get(SampleConfig.ENDPOINT_METADATA_KEY); - return payload == null ? null : CONVERTER.fromPayload(payload, String.class, String.class); - } -} diff --git a/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointInterceptor.java b/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointInterceptor.java deleted file mode 100644 index acf05000..00000000 --- a/core/src/main/java/io/temporal/samples/nexusserializationcontext/propagation/NexusEndpointInterceptor.java +++ /dev/null @@ -1,36 +0,0 @@ -package io.temporal.samples.nexusserializationcontext.propagation; - -import io.nexusrpc.OperationException; -import io.nexusrpc.handler.OperationContext; -import io.temporal.common.interceptors.NexusOperationInboundCallsInterceptor; -import io.temporal.common.interceptors.NexusOperationInboundCallsInterceptorBase; -import io.temporal.common.interceptors.WorkerInterceptorBase; -import io.temporal.nexus.Nexus; -import io.temporal.samples.nexusserializationcontext.SampleConfig; -import org.slf4j.MDC; - -/** Makes the endpoint available while a Nexus handler starts its backing workflow. */ -public final class NexusEndpointInterceptor extends WorkerInterceptorBase { - @Override - public NexusOperationInboundCallsInterceptor interceptNexusOperation( - OperationContext context, NexusOperationInboundCallsInterceptor next) { - return new NexusOperationInboundCallsInterceptorBase(next) { - @Override - public StartOperationOutput startOperation(StartOperationInput input) - throws OperationException { - String previousEndpoint = NexusEndpointContextPropagator.currentEndpoint(); - String endpoint = Nexus.getOperationContext().getInfo().getEndpoint(); - try { - MDC.put(SampleConfig.ENDPOINT_METADATA_KEY, endpoint); - return super.startOperation(input); - } finally { - if (previousEndpoint == null) { - MDC.remove(SampleConfig.ENDPOINT_METADATA_KEY); - } else { - MDC.put(SampleConfig.ENDPOINT_METADATA_KEY, previousEndpoint); - } - } - } - }; - } -} diff --git a/core/src/test/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodecTest.java b/core/src/test/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodecTest.java index b5329952..27583bb3 100644 --- a/core/src/test/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodecTest.java +++ b/core/src/test/java/io/temporal/samples/nexusserializationcontext/codec/NexusCodecTest.java @@ -5,7 +5,6 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import com.google.protobuf.ByteString; import io.temporal.api.common.v1.Payload; import io.temporal.common.converter.DataConverter; import io.temporal.common.converter.EncodingKeys; @@ -17,76 +16,53 @@ import io.temporal.samples.nexusserializationcontext.caller.EndpointResults; import io.temporal.samples.nexusserializationcontext.handler.CompressedEncryptedHandlerWorker; import io.temporal.samples.nexusserializationcontext.handler.EncryptedHandlerWorker; -import io.temporal.samples.nexusserializationcontext.propagation.NexusEndpointContextPropagator; -import io.temporal.samples.nexusserializationcontext.service.AsyncEchoService; import io.temporal.samples.nexusserializationcontext.service.SyncEchoService; import org.junit.jupiter.api.Test; class NexusCodecTest { @Test - void encryptsSyncAndAsyncOperationsWithTheKeyForTheirEndpoint() { - DataConverter syncA = converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT); - DataConverter asyncA = converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, true); - DataConverter syncB = converterFor(SampleConfig.ENCRYPTED_ENDPOINT); - DataConverter asyncB = converterFor(SampleConfig.ENCRYPTED_ENDPOINT, true); - - Payload syncAPayload = syncA.toPayload("hello").orElseThrow(); - Payload asyncAPayload = asyncA.toPayload("hello").orElseThrow(); - Payload syncBPayload = syncB.toPayload("hello").orElseThrow(); - Payload asyncBPayload = asyncB.toPayload("hello").orElseThrow(); - - assertEncryptedFor( - syncAPayload, SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, SampleConfig.KEY_A_ID); - assertEncryptedFor( - asyncAPayload, SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, SampleConfig.KEY_A_ID); - assertEncryptedFor(syncBPayload, SampleConfig.ENCRYPTED_ENDPOINT, SampleConfig.KEY_B_ID); - assertEncryptedFor(asyncBPayload, SampleConfig.ENCRYPTED_ENDPOINT, SampleConfig.KEY_B_ID); - assertEquals("hello", syncA.fromPayload(syncAPayload, String.class, String.class)); - assertEquals("hello", asyncA.fromPayload(asyncAPayload, String.class, String.class)); - assertEquals("hello", syncB.fromPayload(syncBPayload, String.class, String.class)); - assertEquals("hello", asyncB.fromPayload(asyncBPayload, String.class, String.class)); - assertThrows( - PayloadCodecException.class, - () -> syncA.fromPayload(syncBPayload, String.class, String.class)); - assertThrows( - PayloadCodecException.class, - () -> asyncB.fromPayload(asyncAPayload, String.class, String.class)); - Payload keyAPayloadMarkedAsB = - syncAPayload.toBuilder() - .putMetadata( - AesGcmCodec.KEY_ID_METADATA_KEY, ByteString.copyFromUtf8(SampleConfig.KEY_B_ID)) - .build(); - assertThrows( - PayloadCodecException.class, - () -> syncB.fromPayload(keyAPayloadMarkedAsB, String.class, String.class)); + void callerAndHandlersUseTheKeyForEachEndpoint() { + DataConverter compressedEncryptedHandler = CompressedEncryptedHandlerWorker.dataConverter(); + DataConverter encryptedHandler = EncryptedHandlerWorker.dataConverter(); + + assertEndpointRoundTrip( + compressedEncryptedHandler, + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT, + SampleConfig.COMPRESSED_ENCRYPTED_KEY_1_ID); + assertEndpointRoundTrip( + compressedEncryptedHandler, + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT, + SampleConfig.COMPRESSED_ENCRYPTED_KEY_2_ID); + assertEndpointRoundTrip( + encryptedHandler, SampleConfig.ENCRYPTED_1_ENDPOINT, SampleConfig.ENCRYPTED_KEY_1_ID); + assertEndpointRoundTrip( + encryptedHandler, SampleConfig.ENCRYPTED_2_ENDPOINT, SampleConfig.ENCRYPTED_KEY_2_ID); } @Test - void compressesBeforeEncryptingForBothOperationsOnTheCompressedEndpoint() { - String message = "repeat me ".repeat(100); - Payload syncCompressed = - converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT).toPayload(message).orElseThrow(); - Payload syncEncryptedOnly = - converterFor(SampleConfig.ENCRYPTED_ENDPOINT).toPayload(message).orElseThrow(); - Payload asyncCompressed = - converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, true) - .toPayload(message) - .orElseThrow(); - Payload asyncEncrypted = - converterFor(SampleConfig.ENCRYPTED_ENDPOINT, true).toPayload(message).orElseThrow(); - - assertTrue(syncCompressed.getData().size() < syncEncryptedOnly.getData().size()); - assertTrue(asyncCompressed.getData().size() < asyncEncrypted.getData().size()); + void compressesBeforeEncryptingWithEitherKey() { + assertCompressionReducesPayload( + SampleConfig.COMPRESSED_ENCRYPTED_1_ENDPOINT, SampleConfig.ENCRYPTED_1_ENDPOINT); + assertCompressionReducesPayload( + SampleConfig.COMPRESSED_ENCRYPTED_2_ENDPOINT, SampleConfig.ENCRYPTED_2_ENDPOINT); } @Test - void encryptsCallerWorkflowInputAndResultWithKeyC() { + void callerWorkflowPayloadsUseTheirOwnKey() { DataConverter converter = CallerWorker.dataConverter() .withContext( new WorkflowSerializationContext("nexus-serialization-caller", "caller-id")); - EndpointResults results = new EndpointResults("reply A", "reply B", "reply C", "reply D"); - + EndpointResults results = + new EndpointResults( + "reply compressed-encrypted-1", + "reply encrypted-1", + "reply compressed-encrypted-2", + "reply encrypted-2", + "async reply compressed-encrypted-1", + "async reply encrypted-1", + "async reply compressed-encrypted-2", + "async reply encrypted-2"); Payload input = converter.toPayload("Hello from Nexus").orElseThrow(); Payload result = converter.toPayload(results).orElseThrow(); @@ -94,14 +70,14 @@ void encryptsCallerWorkflowInputAndResultWithKeyC() { NexusEncoding.AES_GCM.encodingName(), input.getMetadataOrThrow(EncodingKeys.METADATA_ENCODING_KEY).toStringUtf8()); assertEquals( - SampleConfig.KEY_C_ID, + SampleConfig.CALLER_WORKFLOW_KEY_ID, input.getMetadataOrThrow(AesGcmCodec.KEY_ID_METADATA_KEY).toStringUtf8()); assertEquals( - SampleConfig.KEY_C_ID, + SampleConfig.CALLER_WORKFLOW_KEY_ID, result.getMetadataOrThrow(AesGcmCodec.KEY_ID_METADATA_KEY).toStringUtf8()); - assertFalse(input.getMetadataMap().containsKey(SampleConfig.ENDPOINT_METADATA_KEY)); + assertFalse(input.containsMetadata(SampleConfig.ENDPOINT_METADATA_KEY)); + assertFalse(result.containsMetadata(SampleConfig.ENDPOINT_METADATA_KEY)); assertFalse(input.getData().toStringUtf8().contains("Hello from Nexus")); - assertFalse(result.getData().toStringUtf8().contains("reply A")); assertEquals("Hello from Nexus", converter.fromPayload(input, String.class, String.class)); assertEquals( results, converter.fromPayload(result, EndpointResults.class, EndpointResults.class)); @@ -109,150 +85,42 @@ void encryptsCallerWorkflowInputAndResultWithKeyC() { @Test void rejectsUnknownEndpoints() { - DataConverter converter = - CallerWorker.dataConverter() - .withContext( - new NexusSerializationContext( - "unknown", SyncEchoService.SERVICE_NAME, SyncEchoService.ECHO_OPERATION_NAME)); - + DataConverter converter = converterFor("unknown"); assertThrows(PayloadCodecException.class, () -> converter.toPayload("hello")); } - @Test - void synchronousHandlersUseTheirOwnCodecWithoutEndpointContext() { - DataConverter callerA = converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT); - DataConverter callerB = converterFor(SampleConfig.ENCRYPTED_ENDPOINT); - DataConverter handlerA = CompressedEncryptedHandlerWorker.dataConverter(); - DataConverter handlerB = EncryptedHandlerWorker.dataConverter(); - - Payload requestA = callerA.toPayload("hello").orElseThrow(); - Payload requestB = callerB.toPayload("hello").orElseThrow(); - assertEquals("hello", handlerA.fromPayload(requestA, String.class, String.class)); - assertEquals("hello", handlerB.fromPayload(requestB, String.class, String.class)); - - Payload resultA = handlerA.toPayload("reply").orElseThrow(); - Payload resultB = handlerB.toPayload("reply").orElseThrow(); - assertEquals("reply", callerA.fromPayload(resultA, String.class, String.class)); - assertEquals("reply", callerB.fromPayload(resultB, String.class, String.class)); - - Payload contextualResultA = - handlerA - .withContext(contextFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT)) - .toPayload("reply") - .orElseThrow(); - Payload contextualResultB = - handlerB - .withContext(contextFor(SampleConfig.ENCRYPTED_ENDPOINT)) - .toPayload("reply") - .orElseThrow(); - assertEquals( - SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, - contextualResultA.getMetadataOrThrow(SampleConfig.ENDPOINT_METADATA_KEY).toStringUtf8()); - assertEquals( - SampleConfig.ENCRYPTED_ENDPOINT, - contextualResultB.getMetadataOrThrow(SampleConfig.ENDPOINT_METADATA_KEY).toStringUtf8()); - - assertThrows( - PayloadCodecException.class, - () -> handlerA.fromPayload(requestB, String.class, String.class)); - assertThrows( - PayloadCodecException.class, - () -> handlerB.fromPayload(requestA, String.class, String.class)); - } - - @Test - void handlersDecodeAsyncRequestsWithTheirEndpointKey() { - DataConverter handlerA = - CompressedEncryptedHandlerWorker.dataConverter() - .withContext(contextFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, true)); - DataConverter handlerB = - EncryptedHandlerWorker.dataConverter() - .withContext(contextFor(SampleConfig.ENCRYPTED_ENDPOINT, true)); - Payload requestA = - converterFor(SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, true) - .toPayload("hello") - .orElseThrow(); - Payload requestB = - converterFor(SampleConfig.ENCRYPTED_ENDPOINT, true).toPayload("hello").orElseThrow(); - - assertEquals("hello", handlerA.fromPayload(requestA, String.class, String.class)); - assertEquals("hello", handlerB.fromPayload(requestB, String.class, String.class)); - assertThrows( - PayloadCodecException.class, - () -> handlerA.fromPayload(requestB, String.class, String.class)); - } - - @Test - void propagatedEndpointAppearsOnEncryptedAsyncWorkflowResult() { - NexusEndpointContextPropagator propagator = new NexusEndpointContextPropagator(); - try { - propagator.setCurrentContext(null); - DataConverter handlerA = - CompressedEncryptedHandlerWorker.dataConverter() - .withContext(new WorkflowSerializationContext("handler-a", "echo-workflow")); - DataConverter handlerB = - EncryptedHandlerWorker.dataConverter() - .withContext(new WorkflowSerializationContext("handler-b", "echo-workflow")); - - Payload resultA = - asyncResultFor( - propagator, - handlerA, - SampleConfig.COMPRESSED_ENCRYPTED_ENDPOINT, - SampleConfig.KEY_A_ID); - Payload resultB = - asyncResultFor( - propagator, handlerB, SampleConfig.ENCRYPTED_ENDPOINT, SampleConfig.KEY_B_ID); - assertTrue(resultA.getData().size() < resultB.getData().size()); - } finally { - propagator.setCurrentContext(null); - } + private static void assertEndpointRoundTrip( + DataConverter handler, String endpoint, String keyId) { + DataConverter caller = converterFor(endpoint); + DataConverter contextualHandler = handler.withContext(contextFor(endpoint)); + Payload request = caller.toPayload("hello").orElseThrow(); + assertEncryptionMetadata(request, endpoint, keyId); + assertEquals("hello", contextualHandler.fromPayload(request, String.class, String.class)); + + Payload result = contextualHandler.toPayload("reply").orElseThrow(); + assertEncryptionMetadata(result, endpoint, keyId); + assertEquals("reply", caller.fromPayload(result, String.class, String.class)); } - private static Payload asyncResultFor( - NexusEndpointContextPropagator propagator, - DataConverter handler, - String endpoint, - String keyId) { - propagator.setCurrentContext(endpoint); - var header = propagator.serializeContext(propagator.getCurrentContext()); - propagator.setCurrentContext(null); - propagator.setCurrentContext(propagator.deserializeContext(header)); - - String message = "reply ".repeat(100); - Payload result = handler.toPayload(message).orElseThrow(); - assertEquals( - endpoint, result.getMetadataOrThrow(SampleConfig.ENDPOINT_METADATA_KEY).toStringUtf8()); - assertEquals(keyId, result.getMetadataOrThrow(AesGcmCodec.KEY_ID_METADATA_KEY).toStringUtf8()); - assertEquals( - message, converterFor(endpoint, true).fromPayload(result, String.class, String.class)); - assertEquals(message, handler.fromPayload(result, String.class, String.class)); - propagator.setCurrentContext(null); - return result; + private static void assertCompressionReducesPayload( + String compressedEndpoint, String encryptedOnlyEndpoint) { + String message = "repeat me ".repeat(100); + Payload compressed = converterFor(compressedEndpoint).toPayload(message).orElseThrow(); + Payload encrypted = converterFor(encryptedOnlyEndpoint).toPayload(message).orElseThrow(); + assertTrue(compressed.getData().size() < encrypted.getData().size()); } private static DataConverter converterFor(String endpoint) { return CallerWorker.dataConverter().withContext(contextFor(endpoint)); } - private static DataConverter converterFor(String endpoint, boolean async) { - return CallerWorker.dataConverter().withContext(contextFor(endpoint, async)); - } - private static NexusSerializationContext contextFor(String endpoint) { - return contextFor(endpoint, false); - } - - private static NexusSerializationContext contextFor(String endpoint, boolean async) { - if (async) { - return new NexusSerializationContext( - endpoint, AsyncEchoService.SERVICE_NAME, AsyncEchoService.ECHO_ASYNC_OPERATION_NAME); - } + // Supply context directly to check sample configuration, not SDK context propagation. return new NexusSerializationContext( endpoint, SyncEchoService.SERVICE_NAME, SyncEchoService.ECHO_OPERATION_NAME); } - private static void assertEncryptedFor(Payload payload, String endpoint, String keyId) { + private static void assertEncryptionMetadata(Payload payload, String endpoint, String keyId) { assertEquals( NexusEncoding.AES_GCM.encodingName(), payload.getMetadataOrThrow(EncodingKeys.METADATA_ENCODING_KEY).toStringUtf8());