Search in sources :

Example 1 with EncryptionContext

use of org.apache.pulsar.common.api.EncryptionContext in project pulsar by apache.

the class UtilsTest method createRecord.

private Record<byte[]> createRecord(byte[] data, String algo, String[] keyNames, byte[][] keyValues, byte[] param, Map<String, String> metadata1, Map<String, String> metadata2, int batchSize, int compressionMsgSize, Map<String, String> properties, boolean isEncryption) {
    EncryptionContext ctx = null;
    if (isEncryption) {
        ctx = new EncryptionContext();
        ctx.setAlgorithm(algo);
        ctx.setBatchSize(Optional.of(batchSize));
        ctx.setCompressionType(CompressionType.LZ4);
        ctx.setUncompressedMessageSize(compressionMsgSize);
        Map<String, EncryptionKey> keys = Maps.newHashMap();
        EncryptionKey encKeyVal = new EncryptionKey();
        encKeyVal.setKeyValue(keyValues[0]);
        encKeyVal.setMetadata(metadata1);
        EncryptionKey encKeyVal2 = new EncryptionKey();
        encKeyVal2.setKeyValue(keyValues[1]);
        encKeyVal2.setMetadata(metadata2);
        keys.put(keyNames[0], encKeyVal);
        keys.put(keyNames[1], encKeyVal2);
        ctx.setKeys(keys);
        ctx.setParam(param);
    }
    return new RecordImpl(data, properties, Optional.ofNullable(ctx));
}
Also used : EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) RecordWithEncryptionContext(org.apache.pulsar.functions.source.RecordWithEncryptionContext) EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey) ToString(lombok.ToString)

Example 2 with EncryptionContext

use of org.apache.pulsar.common.api.EncryptionContext in project pulsar by apache.

the class Utils method serializeRecordToJson.

/**
 * Serializes sink-record into json format. It encodes encryption-keys, encryption-param and payload in base64
 * format so, it can be sent in json.
 *
 * @param record
 * @return
 */
public static String serializeRecordToJson(Record<byte[]> record) {
    checkNotNull(record, "record can't be null");
    JsonObject result = new JsonObject();
    result.addProperty(PAYLOAD_FIELD, getEncoder().encodeToString(record.getValue()));
    if (record.getProperties() != null) {
        JsonObject properties = new JsonObject();
        record.getProperties().entrySet().forEach(e -> properties.addProperty(e.getKey(), e.getValue()));
        result.add(PROPERTIES_FIELD, properties);
    }
    Optional<EncryptionContext> optEncryptionCtx = (record instanceof RecordWithEncryptionContext) ? ((RecordWithEncryptionContext<byte[]>) record).getEncryptionCtx() : Optional.empty();
    if (optEncryptionCtx.isPresent()) {
        EncryptionContext encryptionCtx = optEncryptionCtx.get();
        JsonObject encryptionCtxJson = new JsonObject();
        JsonObject keyBase64Map = new JsonObject();
        JsonObject keyMetadataMap = new JsonObject();
        encryptionCtx.getKeys().entrySet().forEach(entry -> {
            keyBase64Map.addProperty(entry.getKey(), getEncoder().encodeToString(entry.getValue().getKeyValue()));
            Map<String, String> keyMetadata = entry.getValue().getMetadata();
            if (keyMetadata != null && !keyMetadata.isEmpty()) {
                JsonObject metadata = new JsonObject();
                entry.getValue().getMetadata().entrySet().forEach(m -> metadata.addProperty(m.getKey(), m.getValue()));
                keyMetadataMap.add(entry.getKey(), metadata);
            }
        });
        encryptionCtxJson.add(KEY_MAP_FIELD, keyBase64Map);
        encryptionCtxJson.add(KEY_METADATA_MAP_FIELD, keyMetadataMap);
        encryptionCtxJson.addProperty(ENCRYPTION_PARAM_FIELD, getEncoder().encodeToString(encryptionCtx.getParam()));
        encryptionCtxJson.addProperty(ALGO_FIELD, encryptionCtx.getAlgorithm());
        if (encryptionCtx.getCompressionType() != null) {
            encryptionCtxJson.addProperty(COMPRESSION_TYPE_FIELD, encryptionCtx.getCompressionType().name());
            encryptionCtxJson.addProperty(UNCPRESSED_MSG_SIZE_FIELD, encryptionCtx.getUncompressedMessageSize());
        }
        if (encryptionCtx.getBatchSize().isPresent()) {
            encryptionCtxJson.addProperty(BATCH_SIZE_FIELD, encryptionCtx.getBatchSize().get());
        }
        result.add(ENCRYPTION_CTX_FIELD, encryptionCtxJson);
    }
    return result.toString();
}
Also used : EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) RecordWithEncryptionContext(org.apache.pulsar.functions.source.RecordWithEncryptionContext) JsonObject(com.google.gson.JsonObject) RecordWithEncryptionContext(org.apache.pulsar.functions.source.RecordWithEncryptionContext)

Example 3 with EncryptionContext

use of org.apache.pulsar.common.api.EncryptionContext in project pulsar by apache.

the class SimpleProducerConsumerTest method decryptMessage.

private String decryptMessage(TopicMessageImpl<byte[]> msg, String encryptionKeyName, CryptoKeyReader reader) throws Exception {
    Optional<EncryptionContext> ctx = msg.getEncryptionCtx();
    assertTrue(ctx.isPresent());
    EncryptionContext encryptionCtx = ctx.orElseThrow(() -> new IllegalStateException("encryption-ctx not present for encrypted message"));
    Map<String, EncryptionContext.EncryptionKey> keys = encryptionCtx.getKeys();
    assertEquals(keys.size(), 1);
    EncryptionContext.EncryptionKey encryptionKey = keys.get(encryptionKeyName);
    byte[] dataKey = encryptionKey.getKeyValue();
    Map<String, String> metadata = encryptionKey.getMetadata();
    String version = metadata.get("version");
    assertEquals(version, "1.0");
    CompressionType compressionType = encryptionCtx.getCompressionType();
    int uncompressedSize = encryptionCtx.getUncompressedMessageSize();
    byte[] encrParam = encryptionCtx.getParam();
    String encAlgo = encryptionCtx.getAlgorithm();
    int batchSize = encryptionCtx.getBatchSize().orElse(0);
    ByteBuffer payloadBuf = ByteBuffer.wrap(msg.getData());
    // try to decrypt use default MessageCryptoBc
    MessageCrypto crypto = new MessageCryptoBc("test", false);
    MessageMetadata msgMetadata = new MessageMetadata().setEncryptionParam(encrParam).setProducerName("test").setSequenceId(123).setPublishTime(12333453454L).setCompression(CompressionCodecProvider.convertToWireProtocol(compressionType)).setUncompressedSize(uncompressedSize);
    if (encAlgo != null) {
        msgMetadata.setEncryptionAlgo(encAlgo);
    }
    msgMetadata.addEncryptionKey().setKey(encryptionKeyName).setValue(dataKey);
    ByteBuffer decryptedPayload = ByteBuffer.allocate(crypto.getMaxOutputSize(payloadBuf.remaining()));
    crypto.decrypt(() -> msgMetadata, payloadBuf, decryptedPayload, reader);
    // try to uncompress
    CompressionCodec codec = CompressionCodecProvider.getCompressionCodec(compressionType);
    ByteBuf uncompressedPayload = codec.decode(Unpooled.wrappedBuffer(decryptedPayload), uncompressedSize);
    if (batchSize > 0) {
        SingleMessageMetadata singleMessageMetadata = new SingleMessageMetadata();
        uncompressedPayload = Commands.deSerializeSingleMessageInBatch(uncompressedPayload, singleMessageMetadata, 0, batchSize);
    }
    byte[] data = new byte[uncompressedPayload.readableBytes()];
    uncompressedPayload.readBytes(data);
    uncompressedPayload.release();
    return new String(data);
}
Also used : MessageCrypto(org.apache.pulsar.client.api.MessageCrypto) MessageCryptoBc(org.apache.pulsar.client.impl.crypto.MessageCryptoBc) ByteBuf(org.apache.pulsar.shade.io.netty.buffer.ByteBuf) ByteBuffer(java.nio.ByteBuffer) MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) CompressionType(org.apache.pulsar.client.api.CompressionType)

Example 4 with EncryptionContext

use of org.apache.pulsar.common.api.EncryptionContext in project pulsar by yahoo.

the class ConsumerImpl method createEncryptionContext.

/**
 * Create EncryptionContext if message payload is encrypted.
 *
 * @param msgMetadata
 * @return {@link Optional}<{@link EncryptionContext}>
 */
private Optional<EncryptionContext> createEncryptionContext(MessageMetadata msgMetadata) {
    EncryptionContext encryptionCtx = null;
    if (msgMetadata.getEncryptionKeysCount() > 0) {
        encryptionCtx = new EncryptionContext();
        Map<String, EncryptionKey> keys = msgMetadata.getEncryptionKeysList().stream().collect(Collectors.toMap(EncryptionKeys::getKey, e -> new EncryptionKey(e.getValue(), e.getMetadatasList().stream().collect(Collectors.toMap(KeyValue::getKey, KeyValue::getValue)))));
        byte[] encParam = msgMetadata.getEncryptionParam();
        Optional<Integer> batchSize = Optional.ofNullable(msgMetadata.hasNumMessagesInBatch() ? msgMetadata.getNumMessagesInBatch() : null);
        encryptionCtx.setKeys(keys);
        encryptionCtx.setParam(encParam);
        if (msgMetadata.hasEncryptionAlgo()) {
            encryptionCtx.setAlgorithm(msgMetadata.getEncryptionAlgo());
        }
        encryptionCtx.setCompressionType(CompressionCodecProvider.convertFromWireProtocol(msgMetadata.getCompression()));
        encryptionCtx.setUncompressedMessageSize(msgMetadata.getUncompressedSize());
        encryptionCtx.setBatchSize(batchSize);
    }
    return Optional.ofNullable(encryptionCtx);
}
Also used : EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey) SubscriptionMode(org.apache.pulsar.client.api.SubscriptionMode) MessageIdData(org.apache.pulsar.common.api.proto.MessageIdData) Producer(org.apache.pulsar.client.api.Producer) LoggerFactory(org.slf4j.LoggerFactory) MessageCryptoBc(org.apache.pulsar.client.impl.crypto.MessageCryptoBc) MessageCrypto(org.apache.pulsar.client.api.MessageCrypto) StringUtils(org.apache.commons.lang3.StringUtils) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) ByteBuffer(java.nio.ByteBuffer) GrowableArrayBlockingQueue(org.apache.pulsar.common.util.collections.GrowableArrayBlockingQueue) ProtocolVersion(org.apache.pulsar.common.api.proto.ProtocolVersion) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) TxnID(org.apache.pulsar.client.api.transaction.TxnID) Handle(io.netty.util.Recycler.Handle) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorProvider(org.apache.pulsar.client.util.ExecutorProvider) Runnables.catchingAndLoggingThrowables(org.apache.pulsar.common.util.Runnables.catchingAndLoggingThrowables) Map(java.util.Map) Messages(org.apache.pulsar.client.api.Messages) RetryMessageUtil(org.apache.pulsar.client.util.RetryMessageUtil) CompletableFutureCancellationHandler(org.apache.pulsar.common.util.CompletableFutureCancellationHandler) PulsarClientException(org.apache.pulsar.client.api.PulsarClientException) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) BrokerEntryMetadata(org.apache.pulsar.common.api.proto.BrokerEntryMetadata) Crc32cIntChecksum(com.scurrilous.circe.checksum.Crc32cIntChecksum) ValidationError(org.apache.pulsar.common.api.proto.CommandAck.ValidationError) BitSetRecyclable(org.apache.pulsar.common.util.collections.BitSetRecyclable) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) ComparisonChain(com.google.common.collect.ComparisonChain) Collectors(java.util.stream.Collectors) PulsarByteBufAllocator(org.apache.pulsar.common.allocator.PulsarByteBufAllocator) Recycler(io.netty.util.Recycler) Objects(java.util.Objects) Consumer(org.apache.pulsar.client.api.Consumer) List(java.util.List) FutureUtil(org.apache.pulsar.common.util.FutureUtil) MessageMetadata(org.apache.pulsar.common.api.proto.MessageMetadata) ConcurrentOpenHashMap(org.apache.pulsar.common.util.collections.ConcurrentOpenHashMap) EncryptionKeys(org.apache.pulsar.common.api.proto.EncryptionKeys) CommandMessage(org.apache.pulsar.common.api.proto.CommandMessage) ReferenceCountUtil(io.netty.util.ReferenceCountUtil) Optional(java.util.Optional) SchemaInfo(org.apache.pulsar.common.schema.SchemaInfo) SortedMap(java.util.SortedMap) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CompressionCodec(org.apache.pulsar.common.compression.CompressionCodec) Iterables(com.google.common.collect.Iterables) AtomicIntegerFieldUpdater(java.util.concurrent.atomic.AtomicIntegerFieldUpdater) ConsumerCryptoFailureAction(org.apache.pulsar.client.api.ConsumerCryptoFailureAction) TopicName(org.apache.pulsar.common.naming.TopicName) ConsumerConfigurationData(org.apache.pulsar.client.impl.conf.ConsumerConfigurationData) AckType(org.apache.pulsar.common.api.proto.CommandAck.AckType) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) Message(org.apache.pulsar.client.api.Message) SubscriptionInitialPosition(org.apache.pulsar.client.api.SubscriptionInitialPosition) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) SchemaType(org.apache.pulsar.common.schema.SchemaType) ArrayList(java.util.ArrayList) Commands(org.apache.pulsar.common.protocol.Commands) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Commands.hasChecksum(org.apache.pulsar.common.protocol.Commands.hasChecksum) TopicDoesNotExistException(org.apache.pulsar.client.api.PulsarClientException.TopicDoesNotExistException) CompressionCodecProvider(org.apache.pulsar.common.compression.CompressionCodecProvider) CompressionType(org.apache.pulsar.common.api.proto.CompressionType) TypedMessageBuilder(org.apache.pulsar.client.api.TypedMessageBuilder) SafeCollectionUtils(org.apache.pulsar.common.util.SafeCollectionUtils) DEFAULT_CONSUMER_EPOCH(org.apache.pulsar.common.protocol.Commands.DEFAULT_CONSUMER_EPOCH) Timeout(io.netty.util.Timeout) Logger(org.slf4j.Logger) TransactionImpl(org.apache.pulsar.client.impl.transaction.TransactionImpl) InitialPosition(org.apache.pulsar.common.api.proto.CommandSubscribe.InitialPosition) DeadLetterPolicy(org.apache.pulsar.client.api.DeadLetterPolicy) IOException(java.io.IOException) AtomicLongFieldUpdater(java.util.concurrent.atomic.AtomicLongFieldUpdater) SubscriptionType(org.apache.pulsar.client.api.SubscriptionType) Schema(org.apache.pulsar.client.api.Schema) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageId(org.apache.pulsar.client.api.MessageId) TreeMap(java.util.TreeMap) SingleMessageMetadata(org.apache.pulsar.common.api.proto.SingleMessageMetadata) Collections(java.util.Collections) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) KeyValue(org.apache.pulsar.common.api.proto.KeyValue) EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey)

Example 5 with EncryptionContext

use of org.apache.pulsar.common.api.EncryptionContext in project pulsar by yahoo.

the class UtilsTest method createRecord.

private Record<GenericObject> createRecord(byte[] data, String algo, String[] keyNames, byte[][] keyValues, byte[] param, Map<String, String> metadata1, Map<String, String> metadata2, int batchSize, int compressionMsgSize, Map<String, String> properties, boolean isEncryption) {
    EncryptionContext ctx = null;
    if (isEncryption) {
        ctx = new EncryptionContext();
        ctx.setAlgorithm(algo);
        ctx.setBatchSize(Optional.of(batchSize));
        ctx.setCompressionType(CompressionType.LZ4);
        ctx.setUncompressedMessageSize(compressionMsgSize);
        Map<String, EncryptionKey> keys = Maps.newHashMap();
        EncryptionKey encKeyVal = new EncryptionKey();
        encKeyVal.setKeyValue(keyValues[0]);
        encKeyVal.setMetadata(metadata1);
        EncryptionKey encKeyVal2 = new EncryptionKey();
        encKeyVal2.setKeyValue(keyValues[1]);
        encKeyVal2.setMetadata(metadata2);
        keys.put(keyNames[0], encKeyVal);
        keys.put(keyNames[1], encKeyVal2);
        ctx.setKeys(keys);
        ctx.setParam(param);
    }
    org.apache.pulsar.client.api.Message<GenericObject> message = mock(org.apache.pulsar.client.api.Message.class);
    when(message.getData()).thenReturn(data);
    when(message.getProperties()).thenReturn(properties);
    when(message.getEncryptionCtx()).thenReturn(Optional.ofNullable(ctx));
    return PulsarRecord.<GenericObject>builder().message(message).build();
}
Also used : EncryptionContext(org.apache.pulsar.common.api.EncryptionContext) GenericObject(org.apache.pulsar.client.api.schema.GenericObject) EncryptionKey(org.apache.pulsar.common.api.EncryptionContext.EncryptionKey) ToString(lombok.ToString)

Aggregations

EncryptionContext (org.apache.pulsar.common.api.EncryptionContext)19 ByteBuffer (java.nio.ByteBuffer)12 MessageCryptoBc (org.apache.pulsar.client.impl.crypto.MessageCryptoBc)9 EncryptionKey (org.apache.pulsar.common.api.EncryptionContext.EncryptionKey)9 MessageMetadata (org.apache.pulsar.common.api.proto.MessageMetadata)9 SingleMessageMetadata (org.apache.pulsar.common.api.proto.SingleMessageMetadata)9 CompressionCodec (org.apache.pulsar.common.compression.CompressionCodec)9 ByteBuf (io.netty.buffer.ByteBuf)6 MessageCrypto (org.apache.pulsar.client.api.MessageCrypto)6 GenericObject (org.apache.pulsar.client.api.schema.GenericObject)6 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)3 ComparisonChain (com.google.common.collect.ComparisonChain)3 Iterables (com.google.common.collect.Iterables)3 JsonObject (com.google.gson.JsonObject)3 Crc32cIntChecksum (com.scurrilous.circe.checksum.Crc32cIntChecksum)3 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)3 Recycler (io.netty.util.Recycler)3 Handle (io.netty.util.Recycler.Handle)3 ReferenceCountUtil (io.netty.util.ReferenceCountUtil)3 Timeout (io.netty.util.Timeout)3