index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r/data/ParquetSchema.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import lombok.Builder;
import lombok.Getter;
import lombok.NonNull;
import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.parquet.schema.MessageType;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.apache.parquet.schema.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Schema for a source Parquet file.
*/
public class ParquetSchema {
/**
* Parquet schema.
*/
@Getter
private final org.apache.parquet.schema.MessageType reconstructedMessageType;
/**
* Column names.
*/
@Getter
private final List<ColumnHeader> headers;
/**
* Map of column names to column index.
*/
private final Map<ColumnHeader, Integer> columnIndices;
/**
* Map of column names to Parquet data type.
*/
@Getter
private final Map<ColumnHeader, ParquetDataType> columnParquetDataTypeMap;
/**
* Client data types associated with the parquet file's columns.
*/
@Getter
private final List<ClientDataType> columnClientDataTypes;
/**
* Generate a C3R schema based off of a Parquet schema.
*
* @param messageType Apache's Parquet schema
* @deprecated Use the {@link ParquetSchema#builder()} method for this class.
*/
@Deprecated
public ParquetSchema(final org.apache.parquet.schema.MessageType messageType) {
this(messageType, false, false);
}
/**
* Generate a C3R schema based off of a Parquet schema.
*
* @param messageType Apache's Parquet schema
* @param skipHeaderNormalization Whether headers should be normalized
* @param binaryAsString If {@code true}, treat unannounced binary values as strings
*/
@Builder
private ParquetSchema(final org.apache.parquet.schema.MessageType messageType,
final boolean skipHeaderNormalization,
final Boolean binaryAsString) {
reconstructedMessageType = reconstructMessageType(messageType, binaryAsString);
headers = new ArrayList<>();
columnIndices = new HashMap<>();
final var parquetTypes = new HashMap<ColumnHeader, ParquetDataType>();
final var clientTypes = new ArrayList<ClientDataType>(reconstructedMessageType.getFieldCount());
for (int i = 0; i < reconstructedMessageType.getFieldCount(); i++) {
final ColumnHeader column = skipHeaderNormalization
? ColumnHeader.ofRaw(reconstructedMessageType.getFieldName(i))
: new ColumnHeader(reconstructedMessageType.getFieldName(i));
headers.add(column);
columnIndices.put(column, i);
final org.apache.parquet.schema.Type originalType = reconstructedMessageType.getType(i);
final ParquetDataType parquetType = ParquetDataType.fromType(originalType);
parquetTypes.put(column, parquetType);
clientTypes.add(parquetType.getClientDataType());
}
columnParquetDataTypeMap = Collections.unmodifiableMap(parquetTypes);
columnClientDataTypes = Collections.unmodifiableList(clientTypes);
}
/**
* If needed, examine all input Parquet types and reconstruct them according to the specifications.
*
* @param messageType All types in the table and table name
* @param binaryAsString If {@code true}, treat unannounced binary values as strings
* @return Parquet types to use for marshalling
*/
private MessageType reconstructMessageType(final MessageType messageType, final Boolean binaryAsString) {
if (binaryAsString == null || !binaryAsString) {
return new MessageType(messageType.getName(), messageType.getFields());
}
final List<Type> reconstructedFields = messageType.getFields().stream().map(this::reconstructType).collect(Collectors.toList());
return new MessageType(messageType.getName(), reconstructedFields);
}
/**
* Reconstruct Parquet types as needed. Currently only examines binary values,
* adding the string annotation if needed as this is commonly left off.
*
* @param type Parquet type information to modify if needed
* @return Finalized Parquet type information
*/
private Type reconstructType(final Type type) {
if (type.isPrimitive() && type.asPrimitiveType().getPrimitiveTypeName() == PrimitiveType.PrimitiveTypeName.BINARY) {
if (type.getLogicalTypeAnnotation() == null) {
final Types.PrimitiveBuilder<PrimitiveType> construct;
if (type.getRepetition() == Type.Repetition.OPTIONAL) {
construct = Types.optional(PrimitiveType.PrimitiveTypeName.BINARY);
} else if (type.getRepetition() == Type.Repetition.REQUIRED) {
construct = Types.required(PrimitiveType.PrimitiveTypeName.BINARY);
} else {
construct = Types.repeated(PrimitiveType.PrimitiveTypeName.BINARY);
}
return construct.as(LogicalTypeAnnotation.stringType()).named(type.getName());
}
}
return type;
}
/**
* How many columns are in the file.
*
* @return Column count
*/
public int size() {
return headers.size();
}
/**
* Get the column index for the named column.
*
* @param column Name of the column
* @return Indexed location of column
*/
public int getColumnIndex(final ColumnHeader column) {
return columnIndices.get(column);
}
/**
* Get the Parquet type for a column.
*
* @param column Name of the column
* @return Type of the column
*/
public ParquetDataType getColumnType(final ColumnHeader column) {
return columnParquetDataTypeMap.get(column);
}
/**
* Constructs the target {@link ParquetSchema} using this as the source
* {@link ParquetSchema} and the given {@link TableSchema}.
*
* @param tableSchema The table schema mapping this source {@link ParquetSchema} to
* the corresponding target {@link ParquetSchema}. NOTE: each
* `sourceHeader` in the schema must be present as a field in the
* source {@link ParquetSchema} or an error is raised
* @return The corresponding target schema described by this {@link ParquetSchema} and the given {@link TableSchema}
* @throws C3rIllegalArgumentException If the source header is not found in schema
*/
public ParquetSchema deriveTargetSchema(final TableSchema tableSchema) {
for (ColumnSchema c : tableSchema.getColumns()) {
if (!columnParquetDataTypeMap.containsKey(c.getSourceHeader())) {
throw new C3rIllegalArgumentException("sourceHeader in schema not found in Parquet schema: "
+ c.getSourceHeader());
}
}
final List<org.apache.parquet.schema.Type> fields = tableSchema.getColumns().stream()
.map(c -> targetColumnParquetDataType(columnParquetDataTypeMap.get(c.getSourceHeader()), c.getType())
.toTypeWithName(c.getTargetHeader().toString()))
.collect(Collectors.toList());
return new ParquetSchema(new org.apache.parquet.schema.MessageType("EncryptedTable", fields));
}
/**
* Check if target column type does not match input column type and set the target type.
*
* @param type Input Parquet data type
* @param columnType Targeted column type
* @return Required type for output column
*/
private ParquetDataType targetColumnParquetDataType(@NonNull final ParquetDataType type, @NonNull final ColumnType columnType) {
if (type.getClientDataType() == ClientDataType.STRING) {
return type;
}
if (columnType == ColumnType.FINGERPRINT || columnType == ColumnType.SEALED) {
return ParquetDataType.fromType(Types.optional(PrimitiveType.PrimitiveTypeName.BINARY).as(LogicalTypeAnnotation.stringType())
.named(type.getParquetType().getName()));
}
return type;
}
} | 2,500 |
0 | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r/data/ParquetDataType.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.Validatable;
import lombok.Value;
import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.parquet.schema.PrimitiveType;
import org.apache.parquet.schema.Type;
import org.apache.parquet.schema.Types;
import static org.apache.parquet.schema.PrimitiveType.PrimitiveTypeName;
/**
* Supported Parquet types.
*/
@Value
public final class ParquetDataType implements Validatable {
/**
* This is the Parquet type used for nonces.
*/
private static final org.apache.parquet.schema.Type NONCE_PARQUET_TYPE = org.apache.parquet.schema.Types
.required(PrimitiveTypeName.BINARY).named("nonce");
/**
* The type used for nonces in ParquetDataTypes.
*/
public static final ParquetDataType NONCE_TYPE = new ParquetDataType(NONCE_PARQUET_TYPE, ClientDataType.UNKNOWN);
/**
* Client type.
*/
private ClientDataType clientDataType;
/**
* Parquet type.
*/
private org.apache.parquet.schema.Type parquetType;
/**
* Private constructor to set up the nonce data type correctly.
*
* @param pType Parquet type
* @param cType C3r type
*/
private ParquetDataType(final org.apache.parquet.schema.Type pType, final ClientDataType cType) {
parquetType = pType;
clientDataType = cType;
validate();
}
/**
* Checks if the Parquet type is supported by C3R.
* Must be a primitive type that is not an {@code INT96} or {@code FIXED_LEN_BYTE_ARRAY}.
*
* @param type Parquet type
* @return {@code true} if supported
*/
public static boolean isSupportedType(final org.apache.parquet.schema.Type type) {
return type.isPrimitive()
&& type.getRepetition() != Type.Repetition.REPEATED
&& type.asPrimitiveType().getPrimitiveTypeName() != PrimitiveTypeName.INT96;
}
/**
* Convert a Parquet schema type to a C3R Parquet data type after verifying compatability.
*
* @param type Parquet type associated with a column
* @return Instance of the associated {@code ParquetDataTy[e}
* @throws C3rIllegalArgumentException If the data type is an unsupported Parquet data type
*/
public static ParquetDataType fromType(final org.apache.parquet.schema.Type type) {
if (!ParquetDataType.isSupportedType(type)) {
throw new C3rIllegalArgumentException("Unsupported parquet type: " + type);
}
return new ParquetDataType(type, getClientDataType(type));
}
/**
* Checks if this is a string.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a string
*/
static boolean isStringType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.BINARY) &&
annotation != null && annotation.equals(LogicalTypeAnnotation.stringType());
}
/**
* Checks if this is a plain int64 value. The int64 type can either have no logical annotations or the {@code INT}
* annotation with the {@code bitWidth} parameter set to 64 and {@code isSigned} set to {@code true}.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a signed {@code int64} value
*/
static boolean isBigIntType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT64)
&& (annotation == null
|| type.getLogicalTypeAnnotation().equals(LogicalTypeAnnotation.intType(ClientDataType.BIGINT_BIT_SIZE, true)));
}
/**
* Checks if this is a plain boolean value. There should be no annotations on the type.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a {@code boolean} value
*/
static boolean isBooleanType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.BOOLEAN)
&& annotation == null;
}
/**
* Checks if this is a date value. The primitive data type must be an {@code int32} and the logical annotation must
* be {@code Date}.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a {@code Date} value
*/
static boolean isDateType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT32)
&& annotation != null
&& annotation.equals(LogicalTypeAnnotation.dateType());
}
/**
* Checks if this is a decimal value. Decimal is a parameterized type ({@code Decimal(scale, precision)}). This function does not check
* whether or not a particular scale or precisions is being used, just that the logical annotation is an instance of Decimal. Decimal
* is also backed by one of four different data structures in Parquet. We ensure that the primitive data type is one of the four
* valid options but do not check for a specific primitive type.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a {@code Decimal} value
*/
static boolean isDecimalType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
// Multiple primitive types can be used to store DECIMAL values depending on the precision
if ((pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT32)
|| pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT64)
|| pt.getPrimitiveTypeName().equals(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)
|| pt.getPrimitiveTypeName().equals(PrimitiveTypeName.BINARY)) && type.getLogicalTypeAnnotation() != null) {
/*
* Because the decimal annotation is a parameterized type (LogicalTypeAnnotation.decimalType(scale, precision)),
* we can't do a direct equality check of the type name since the scale and precision information isn't known here:
* type.getLogicalAnnotation().equals(LogicalTypeAnnotation.decimalType(scale, precision)
* Regardless of scale and precision, all are an instance of the DecimalLogicalTypeAnnotation class so we use:
* type.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation
*/
return annotation instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation;
}
return false;
}
/**
* Checks if this is a plain double value. The double type should not have any logical annotations on it.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a {@code double} value
*/
static boolean isDoubleType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.DOUBLE)
&& annotation == null;
}
/**
* Checks if this is a plain float value. The float type should not have any logical annotations on it.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a {@code float} value
*/
static boolean isFloatType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.FLOAT)
&& annotation == null;
}
/**
* Checks if this is a plain int32 value. The int32 type can either have no logical annotations or the {@code INT}
* annotation with the {@code bitWidth} parameter set to 32 and {@code isSigned} set to {@code true}.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a signed {@code int32} value
*/
static boolean isInt32Type(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT32)
&& (annotation == null || annotation.equals(LogicalTypeAnnotation.intType(ClientDataType.INT_BIT_SIZE, true)));
}
/**
* Checks if this is a plain smallint value. The smallint is contained inside the primitive type int32 with the {@code INT} logical
* annotation where {@code bitWidth} is 16 and {@code isSigned} is true.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a signed {@code smallint} value
*/
static boolean isSmallIntType(final org.apache.parquet.schema.Type type) {
// A short value (16 bits) is stored in the primitive type INT32 and annotated with a specific bit width and
// flag indicating if it is a signed or unsigned integer
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT32)
&& annotation != null
&& annotation.equals(LogicalTypeAnnotation.intType(ClientDataType.SMALLINT_BIT_SIZE, true));
}
/**
* Checks if this is a timestamp value. The timestamp type is backed by the int64 primitive and has the logical type
* {@code Timestamp(isAdjustedToUTC, timeUnit)}. This function checks to make sure the timestamp annotation is there
* and does not check for a specific time unit being used or if the time is in UTC or not.
*
* @param type Parquet type
* @return {@code true} if Parquet type is storing a signed {@code timestamp} value
*/
static boolean isTimestampType(final org.apache.parquet.schema.Type type) {
/*
* Because the timestamp annotation is a parameterized type (LogicalTypeAnnotation.timestampType(isAdjustedToUTC, timeUnit)),
* we can't do a direct equality check of the type name since the UTC adjustment and unit information isn't known here:
* type.getLogicalAnnotation().equals(LogicalTypeAnnotation.timestampType(isAdjustedToUTC, timeUnit))
* Regardless of the UTC adjustment and unit, all are an instance of the TimestampLogicalTypeAnnotation class so we use:
* type.getLogicalTypeAnnotation() instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation
*/
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.INT64)
&& annotation != null
&& annotation instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation;
}
/**
* Checks if this is a fixed-width byte array.
*
* @param type Parquet Type
* @return If the type represents a fixed width byte array
*/
static boolean isCharType(final org.apache.parquet.schema.Type type) {
if (!type.isPrimitive()) {
return false;
}
final PrimitiveType pt = type.asPrimitiveType();
final LogicalTypeAnnotation annotation = pt.getLogicalTypeAnnotation();
return pt.getPrimitiveTypeName().equals(PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY)
&& pt.getTypeLength() > 0
&& (annotation == null || annotation instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation);
}
/**
* Convert the Parquet data type to the equivalent C3R data type.
*
* @param type Parquet type
* @return C3R data type
*/
private static ClientDataType getClientDataType(final org.apache.parquet.schema.Type type) {
if (type.isPrimitive()) {
if (isStringType(type)) {
return ClientDataType.STRING;
} else if (isInt32Type(type)) {
return ClientDataType.INT;
} else if (isBigIntType(type)) {
return ClientDataType.BIGINT;
} else if (isSmallIntType(type)) {
return ClientDataType.SMALLINT;
} else if (isDecimalType(type)) {
return ClientDataType.DECIMAL;
} else if (isDateType(type)) {
return ClientDataType.DATE;
} else if (isDoubleType(type)) {
return ClientDataType.DOUBLE;
} else if (isFloatType(type)) {
return ClientDataType.FLOAT;
} else if (isBooleanType(type)) {
return ClientDataType.BOOLEAN;
} else if (isTimestampType(type)) {
return ClientDataType.TIMESTAMP;
} else if (isCharType(type)) {
return ClientDataType.CHAR;
} else {
return ClientDataType.UNKNOWN;
}
}
return ClientDataType.UNKNOWN;
}
/**
* Creates a Parquet type with correct metadata including specified name.
*
* @param name Label to use for this particular type
* @return A copy of the Parquet type with the specified name
* @throws C3rIllegalArgumentException If the data type is an unsupported Parquet data type
*/
public org.apache.parquet.schema.Type toTypeWithName(final String name) {
final var primType = parquetType.asPrimitiveType().getPrimitiveTypeName();
final var logicalAnn = parquetType.getLogicalTypeAnnotation();
switch (parquetType.getRepetition()) {
case OPTIONAL:
return Types.optional(primType).as(logicalAnn).named(name);
case REQUIRED:
return Types.required(primType).as(logicalAnn).named(name);
default:
throw new C3rIllegalArgumentException("Unsupported parquet type: " + parquetType + ".");
}
}
@Override
public void validate() {
if (parquetType == null) {
return;
}
if (parquetType == NONCE_PARQUET_TYPE) {
return;
}
if (!isSupportedType(parquetType)) {
throw new C3rRuntimeException("Parquet type " + parquetType + " is not supported.");
} else if (parquetType.isPrimitive()) {
final PrimitiveTypeName name = parquetType.asPrimitiveType().getPrimitiveTypeName();
if (name == PrimitiveTypeName.INT32 || name == PrimitiveTypeName.INT64) {
final LogicalTypeAnnotation logicalTypeAnnotation = parquetType.getLogicalTypeAnnotation();
if (logicalTypeAnnotation == null) {
return;
}
if (logicalTypeAnnotation.equals(LogicalTypeAnnotation.intType(ClientDataType.SMALLINT_BIT_SIZE, false)) ||
logicalTypeAnnotation.equals(LogicalTypeAnnotation.intType(ClientDataType.INT_BIT_SIZE, false)) ||
logicalTypeAnnotation.equals(LogicalTypeAnnotation.intType(ClientDataType.BIGINT_BIT_SIZE, false))) {
throw new C3rRuntimeException("Unsigned integer values are not supported.");
}
} else if (name == PrimitiveTypeName.BINARY && parquetType.getLogicalTypeAnnotation() != LogicalTypeAnnotation.stringType()) {
throw new C3rRuntimeException("Binary values must be annotated with the string logical type.");
}
}
}
}
| 2,501 |
0 | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r/data/ParquetValue.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import edu.umd.cs.findbugs.annotations.UnknownNullness;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import org.apache.parquet.io.api.RecordConsumer;
import org.apache.parquet.schema.LogicalTypeAnnotation;
import org.apache.parquet.schema.PrimitiveType;
/**
* Implementation of {@link Value} for the Parquet data format.
*/
@EqualsAndHashCode(callSuper = false)
public abstract class ParquetValue extends Value {
/**
* What the deserialized data type is.
*/
@Getter
private final ParquetDataType parquetDataType;
/**
* Byte array encoding of the value. Uses big-endian format for numerical values.
*/
private final byte[] bytes;
/**
* Associates a data type with a binary encoded value.
*
* @param parquetDataType Underlying data type
* @param bytes Binary serialization of value
* @throws C3rIllegalArgumentException Type not supported
*/
ParquetValue(@NonNull final ParquetDataType parquetDataType, final byte[] bytes) {
this.parquetDataType = parquetDataType;
this.bytes = bytes;
if (!validateAnnotation()) {
throw new C3rIllegalArgumentException("Parquet " + parquetDataType.getParquetType() + " type has invalid logical type " +
"annotations.");
}
}
/**
* Verify annotations on Parquet type are allowed on this primitive type.
*
* @return {@code true} if annotations are accepted on type
*/
abstract boolean validateAnnotation();
/**
* Associates a data type with a binary encoded value.
*
* @param type Underlying data type
* @param bytes Binary serialization of value
* @return Binary value with metadata
* @throws C3rIllegalArgumentException If the data type is not supported
*/
public static ParquetValue fromBytes(final ParquetDataType type, final byte[] bytes) {
if (!ParquetDataType.isSupportedType(type.getParquetType())) {
throw new C3rIllegalArgumentException("Unsupported parquet type: " + type.getParquetType());
}
// asPrimitiveType() is guaranteed to work here because ParquetDataType.isSupportedType only
// returns true for a subset of primitive types
switch (type.getParquetType().asPrimitiveType().getPrimitiveTypeName()) {
case BOOLEAN:
return new Boolean(type, ValueConverter.Boolean.fromBytes(bytes));
case INT32:
return new Int32(type, ValueConverter.Int.fromBytes(bytes));
case INT64:
return new Int64(type, ValueConverter.BigInt.fromBytes(bytes));
case FLOAT:
return new Float(type, ValueConverter.Float.fromBytes(bytes));
case FIXED_LEN_BYTE_ARRAY:
case BINARY:
return new Binary(type, (bytes != null) ? org.apache.parquet.io.api.Binary.fromReusedByteArray(bytes) : null);
case DOUBLE:
return new Double(type, ValueConverter.Double.fromBytes(bytes));
default:
throw new C3rIllegalArgumentException("Unrecognized data type: " + type);
}
}
/**
* Get a copy of the binary value.
*
* @return Copy of binary data
*/
public byte[] getBytes() {
if (bytes != null) {
return this.bytes.clone();
} else {
return null;
}
}
/**
* {@inheritDoc}
*/
@Override
public int byteLength() {
if (bytes != null) {
return this.bytes.length;
} else {
return 0;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isNull() {
return bytes == null;
}
/**
* {@inheritDoc}
*/
@Override
public ClientDataType getClientDataType() {
return parquetDataType.getClientDataType();
}
/**
* Write value to specified output.
*
* @param consumer Output location
*/
public abstract void writeValue(RecordConsumer consumer);
/**
* Specific implementation for binary Parquet values.
*/
@Getter
public static class Binary extends ParquetValue {
/**
* Binary value.
*/
private final org.apache.parquet.io.api.Binary value;
/**
* If this instance of {@code Binary} represents a {@code FIXED_WIDTH_BYTE_ARRAY} a length will be specified.
*/
private final int length;
/**
* Convert a Parquet binary value to its byte representation with data type metadata.
* This constructor takes the {@link ParquetDataType} as it contains information about
* the binary encoding such as if it's a string.
*
* @param type The binary type information
* @param value Binary value to store
* @throws C3rRuntimeException If a data type other than binary found
*/
public Binary(final ParquetDataType type, final org.apache.parquet.io.api.Binary value) {
super(type, binaryToBytes(value));
if (!(isExpectedType(PrimitiveType.PrimitiveTypeName.BINARY, type) ||
isExpectedType(PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY, type))) {
throw new C3rRuntimeException("Parquet Binary type expected but found " + type);
}
this.value = (value != null) ? value.copy() : null;
this.length = (value != null) ? value.length() : 0;
}
/**
* Convert a Parquet binary value to an array of bytes.
*
* @param value Parquet Binary
* @return Byte representation of value
*/
private static byte[] binaryToBytes(final org.apache.parquet.io.api.Binary value) {
if (value == null) {
return null;
}
return value.getBytes().clone();
}
/**
* The {@code Binary} Parquet type can represent the primitive type and the logical types {@code String} and {@code Decimal}.
*
* @return {@code true} if instance is a raw primitive or valid logical type
*/
@Override
boolean validateAnnotation() {
if (getParquetDataType().getParquetType().asPrimitiveType().getPrimitiveTypeName() == PrimitiveType.PrimitiveTypeName.BINARY) {
final LogicalTypeAnnotation annotations = getParquetDataType().getParquetType().getLogicalTypeAnnotation();
return (annotations == null) ||
(annotations instanceof LogicalTypeAnnotation.StringLogicalTypeAnnotation) ||
(annotations instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation);
} else if (getParquetDataType().getParquetType().asPrimitiveType().getPrimitiveTypeName() ==
PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) {
final LogicalTypeAnnotation annotations = getParquetDataType().getParquetType().getLogicalTypeAnnotation();
if (getParquetDataType().getParquetType().asPrimitiveType().getTypeLength() < 0) {
return false;
} else {
return (annotations == null) ||
(annotations instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation);
}
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addBinary(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
if (ClientDataType.STRING == getParquetDataType().getClientDataType() ||
ClientDataType.CHAR == getParquetDataType().getClientDataType()) {
return value.toStringUsingUTF8();
} else {
return value.toString();
}
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
case STRING:
if (getParquetDataType().getClientDataType() == ClientDataType.STRING) {
return getBytes();
} else {
throw new C3rRuntimeException("Could not convert Parquet Binary to " + type + ".");
}
default:
throw new C3rRuntimeException("Could not convert Parquet Binary to " + type + ".");
}
}
}
/**
* Specific implementation for boolean Parquet values.
*/
public static class Boolean extends ParquetValue {
/**
* Boolean value.
*/
private final java.lang.Boolean value;
/**
* Convert a boolean value to its byte representation with data type metadata.
*
* @param parquetDataType The boolean type information
* @param value Boolean to store
* @throws C3rRuntimeException If a data type other than boolean found
*/
public Boolean(final ParquetDataType parquetDataType, final java.lang.Boolean value) {
super(parquetDataType, ValueConverter.Boolean.toBytes(value));
if (!isExpectedType(PrimitiveType.PrimitiveTypeName.BOOLEAN, parquetDataType)) {
throw new C3rRuntimeException("Parquet Boolean type expected but found " + parquetDataType);
}
this.value = value;
}
/**
* Get stored value.
*
* @return {@code true}, {@code false} or {@code null}
*/
public java.lang.Boolean getValue() {
return value;
}
/**
* The {@code Boolean} Parquet type cannot have any logical type annotations.
*
* @return {@code true} if no logical type annotations exist
*/
@Override
boolean validateAnnotation() {
return getParquetDataType().getParquetType().getLogicalTypeAnnotation() == null;
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addBoolean(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
case BOOLEAN:
return getBytes();
default:
throw new C3rRuntimeException("Could not convert Parquet Boolean to " + type + ".");
}
}
}
/**
* Specific implementation for double Parquet values.
*/
@Getter
public static class Double extends ParquetValue {
/**
* Double value.
*/
private final java.lang.Double value;
/**
* Convert a double value to its byte representation with data type metadata.
*
* @param parquetDataType The double type information
* @param value Double to store
* @throws C3rRuntimeException If a data type other than double found
*/
public Double(final ParquetDataType parquetDataType, final java.lang.Double value) {
super(parquetDataType, ValueConverter.Double.toBytes(value));
if (!isExpectedType(PrimitiveType.PrimitiveTypeName.DOUBLE, parquetDataType)) {
throw new C3rRuntimeException("Parquet Double type expected but found " + parquetDataType);
}
this.value = value;
}
/**
* The {@code Double} Parquet type cannot have any logical type annotations.
*
* @return {@code true} if no logical type annotations exist
*/
@Override
boolean validateAnnotation() {
return getParquetDataType().getParquetType().getLogicalTypeAnnotation() == null;
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addDouble(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
default:
throw new C3rRuntimeException("Could not convert Parquet Double to " + type + ".");
}
}
}
/**
* Specific implementation for float Parquet values.
*/
@Getter
public static class Float extends ParquetValue {
/**
* Float value.
*/
private final java.lang.Float value;
/**
* Convert a double value to its byte representation with data type metadata.
*
* @param parquetDataType The float type information
* @param value Float to store
* @throws C3rRuntimeException If a data type other than float found
*/
public Float(final ParquetDataType parquetDataType, final java.lang.Float value) {
super(parquetDataType, ValueConverter.Float.toBytes(value));
if (!isExpectedType(PrimitiveType.PrimitiveTypeName.FLOAT, parquetDataType)) {
throw new C3rRuntimeException("Parquet Float type expected but found " + parquetDataType);
}
this.value = value;
}
/**
* The {@code Float} Parquet type cannot have any logical type annotations.
*
* @return {@code true} if no logical type annotations exist
*/
@Override
boolean validateAnnotation() {
return getParquetDataType().getParquetType().getLogicalTypeAnnotation() == null;
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addFloat(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
default:
throw new C3rRuntimeException("Could not convert Parquet Float to " + type + ".");
}
}
}
/**
* Specific implementation for integer Parquet values.
*/
@Getter
public static class Int32 extends ParquetValue {
/**
* Integer value.
*/
private final java.lang.Integer value;
/**
* Convert an integer value to its byte representation with data type metadata.
*
* @param parquetDataType The integer type data
* @param value Integer to store
* @throws C3rRuntimeException If a data type other than integer found
*/
public Int32(final ParquetDataType parquetDataType, final java.lang.Integer value) {
super(parquetDataType, ValueConverter.Int.toBytes(value));
if (!isExpectedType(PrimitiveType.PrimitiveTypeName.INT32, parquetDataType)) {
throw new C3rRuntimeException("Parquet Integer type expected but found " + parquetDataType);
}
this.value = value;
}
/**
* The {@code int32} Parquet value can have no annotations or have the logical type annotations of {@code Date}, {@code Decimal}
* or {@code Int32}.
*
* @return {@code true} if there is no annotation or the annotation is for Date, Decimal or Int32.
*/
@Override
boolean validateAnnotation() {
final LogicalTypeAnnotation logicalTypeAnnotation = getParquetDataType().getParquetType().getLogicalTypeAnnotation();
if (logicalTypeAnnotation != null && logicalTypeAnnotation instanceof LogicalTypeAnnotation.IntLogicalTypeAnnotation) {
final LogicalTypeAnnotation.IntLogicalTypeAnnotation intLogicalTypeAnnotation =
(LogicalTypeAnnotation.IntLogicalTypeAnnotation) logicalTypeAnnotation;
return intLogicalTypeAnnotation.isSigned() &&
(intLogicalTypeAnnotation.getBitWidth() == Byte.SIZE ||
intLogicalTypeAnnotation.getBitWidth() == ClientDataType.INT_BIT_SIZE ||
intLogicalTypeAnnotation.getBitWidth() == ClientDataType.SMALLINT_BIT_SIZE);
}
return (logicalTypeAnnotation == null) ||
(logicalTypeAnnotation instanceof LogicalTypeAnnotation.DateLogicalTypeAnnotation) ||
(logicalTypeAnnotation instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation);
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addInteger(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
case BIGINT:
return ValueConverter.BigInt.toBytes(value);
case DATE:
return ValueConverter.Date.toBytes(value);
default:
throw new C3rRuntimeException("Could not convert Parquet Int32 to " + type + ".");
}
}
}
/**
* Specific implementation for long Parquet values.
*/
@Getter
public static class Int64 extends ParquetValue {
/**
* Int64 value.
*/
private final java.lang.Long value;
/**
* Convert a long value to its byte representation with data type metadata.
*
* @param parquetDataType The long type data
* @param value Int64 to store
* @throws C3rRuntimeException If a data type other than long found
*/
public Int64(final ParquetDataType parquetDataType, final java.lang.Long value) {
super(parquetDataType, ValueConverter.BigInt.toBytes(value));
if (!isExpectedType(PrimitiveType.PrimitiveTypeName.INT64, parquetDataType)) {
throw new C3rRuntimeException("Parquet Int64 type expected but found " + parquetDataType);
}
this.value = value;
}
/**
* The {@code int64} Parquet type can have no annotations or the {@code Timestamp}, {@code Decimal} or {@code Int32} annotations.
*
* @return {@code true} if no annotations exist or the annotation is timestamp, decimal or int.
*/
@Override
boolean validateAnnotation() {
final LogicalTypeAnnotation logicalTypeAnnotation = getParquetDataType().getParquetType().getLogicalTypeAnnotation();
if (logicalTypeAnnotation instanceof LogicalTypeAnnotation.IntLogicalTypeAnnotation) {
final LogicalTypeAnnotation.IntLogicalTypeAnnotation intLogicalTypeAnnotation =
(LogicalTypeAnnotation.IntLogicalTypeAnnotation) logicalTypeAnnotation;
return intLogicalTypeAnnotation.isSigned() && intLogicalTypeAnnotation.getBitWidth() == ClientDataType.BIGINT_BIT_SIZE;
}
return logicalTypeAnnotation == null ||
logicalTypeAnnotation instanceof LogicalTypeAnnotation.TimestampLogicalTypeAnnotation ||
logicalTypeAnnotation instanceof LogicalTypeAnnotation.DecimalLogicalTypeAnnotation;
}
/**
* {@inheritDoc}
*/
@Override
public void writeValue(final RecordConsumer consumer) {
if (value != null) {
consumer.addLong(value);
}
}
/**
* {@inheritDoc}
*/
@Override
@UnknownNullness
public String toString() {
if (isNull()) {
return null;
}
return String.valueOf(value);
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getBytesAs(final ClientDataType type) {
switch (type) {
case BIGINT:
return ValueConverter.BigInt.toBytes(value);
default:
throw new C3rRuntimeException("Could not convert Parquet Int64 to " + type + ".");
}
}
}
/**
* Checks that the actual Parquet value is a primitive type and is the type that is expected by a particular constructor.
*
* @param expected Type expected by constructor
* @param actual Type passed into constructor
* @return If {@code expected} and {@code actual} match
*/
static boolean isExpectedType(final PrimitiveType.PrimitiveTypeName expected, final ParquetDataType actual) {
if (!actual.getParquetType().isPrimitive()) {
return false;
}
return expected == actual.getParquetType().asPrimitiveType().getPrimitiveTypeName();
}
}
| 2,502 |
0 | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-parquet/src/main/java/com/amazonaws/c3r/data/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Implementations of {@link com.amazonaws.c3r.data.Value}, {@link com.amazonaws.c3r.data.Row}, and
* {@link com.amazonaws.c3r.data.RowFactory} for Parquet data. The additional classes to support processing the data, such as schemas and
* type metadata classes are contained here as well.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r.data; | 2,503 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/TransformerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TransformerTest {
private Transformer transformer;
@BeforeEach
public void setup() {
final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, KeyUtil.KEY_ALG);
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
transformer = new SealedTransformer(Encryptor.getInstance(provider), ClientSettings.highAssuranceMode());
}
@Test
public void hasDescriptorTest() {
final ByteBuffer value = ByteBuffer.allocate(transformer.getVersion().length + transformer.getEncryptionDescriptor().length)
.put(transformer.getVersion())
.put(transformer.getEncryptionDescriptor());
assertTrue(Transformer.hasDescriptor(transformer, value.array()));
}
@Test
public void hasDescriptorEmptyTest() {
assertFalse(Transformer.hasDescriptor(transformer, new byte[0]));
}
@Test
public void hasDescriptorTooShortTest() {
// Not enough room for descriptor
assertFalse(Transformer.hasDescriptor(transformer, new byte[transformer.getVersion().length]));
}
@Test
public void hasDescriptorNotPresentTest() {
// Descriptor not present
final byte[] value = new byte[100];
Arrays.fill(value, (byte) 0);
assertFalse(Transformer.hasDescriptor(transformer, value));
}
}
| 2,504 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/SealedTransformerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.InitializationVector;
import com.amazonaws.c3r.internal.Nonce;
import com.amazonaws.c3r.internal.PadUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import static com.amazonaws.c3r.data.ClientDataType.INT_BYTE_SIZE;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SealedTransformerTest {
private final Nonce nonce = new Nonce("nonce01234567890nonce01234567890".getBytes(StandardCharsets.UTF_8));
private final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.clientDataType(CsvValue.CLIENT_DATA_TYPE)
.padType(PadType.NONE)
.build();
private final InitializationVector iv = InitializationVector.deriveIv(context.getColumnLabel(), nonce);
private final byte[] ciphertextContent = "fakeCiphertext".getBytes(StandardCharsets.UTF_8);
private final byte[] exampleDecodedCiphertextBody =
ByteBuffer.allocate(Nonce.NONCE_BYTE_LENGTH
+ InitializationVector.IV_BYTE_LENGTH
+ ciphertextContent.length)
.put(nonce.getBytes())
.put(iv.getBytes())
.put(ciphertextContent)
.array();
private final byte[] exampleDecodedCiphertextBodyBase64 = Base64.getEncoder().encode(exampleDecodedCiphertextBody);
private final byte[] exampleCiphertext =
ByteBuffer.allocate(SealedTransformer.DESCRIPTOR_PREFIX.length
+ exampleDecodedCiphertextBodyBase64.length)
.put(SealedTransformer.DESCRIPTOR_PREFIX)
.put(exampleDecodedCiphertextBodyBase64)
.array();
private SealedTransformer sealedTransformer;
private Encryptor encryptor;
@BeforeEach
public void setup() {
final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, KeyUtil.KEY_ALG);
final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
encryptor = Encryptor.getInstance(provider);
sealedTransformer = new SealedTransformer(encryptor, ClientSettings.highAssuranceMode());
}
private byte[] getDescriptorPrefix(final byte[] bytes) {
return Arrays.copyOfRange(bytes, 0, SealedTransformer.DESCRIPTOR_PREFIX.length);
}
@Test
public void buildBase64EncodedCiphertextEmptyMessageTest() {
// Expected byte[] is Base64 of nonce + IV
final byte[] expectedPrefix = "bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWfs=".getBytes(StandardCharsets.UTF_8);
final InitializationVector iv = InitializationVector.deriveIv(context.getColumnLabel(), nonce);
final byte[] emptyMessage = new byte[0];
final byte[] actualPrefix = sealedTransformer.buildBase64EncodedMessage(emptyMessage, nonce, iv);
assertArrayEquals(expectedPrefix, actualPrefix);
}
@Test
public void buildBase64EncodedCiphertextTest() {
// Expected byte[] is Base64 of nonce + IV + message
final byte[] expectedPrefix = "bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWftzb21lIG1lc3NhZ2U="
.getBytes(StandardCharsets.UTF_8);
final InitializationVector iv = InitializationVector.deriveIv(context.getColumnLabel(), nonce);
final byte[] message = "some message".getBytes(StandardCharsets.UTF_8);
final byte[] actualPrefix = sealedTransformer.buildBase64EncodedMessage(message, nonce, iv);
assertArrayEquals(expectedPrefix, actualPrefix);
}
@Test
public void marshalTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final byte[] encryptedText = sealedTransformer.marshal(cleartext, context);
assertArrayEquals(
SealedTransformer.DESCRIPTOR_PREFIX,
getDescriptorPrefix(encryptedText));
final byte[] expectedText =
"01:enc:bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWfthhMkpZDNxYAOeL9RWSNX8J7ByuBScwbxT/7vpSoRnTVWu0kXmHA=="
.getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, encryptedText);
final byte[] unmarshalledText = sealedTransformer.unmarshal(encryptedText);
assertArrayEquals(cleartext, unmarshalledText);
}
@Test
public void marshalMaxCleartextLengthWithinMaxStringLengthTest() {
final byte[] cleartext = new byte[PadUtil.MAX_PADDED_CLEARTEXT_BYTES - PadUtil.MAX_PAD_BYTES];
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.clientDataType(CsvValue.CLIENT_DATA_TYPE)
.maxValueLength(cleartext.length)
.padLength(PadUtil.MAX_PAD_BYTES)
.padType(PadType.MAX)
.nonce(nonce).build();
final byte[] encryptedText = sealedTransformer.marshal(cleartext, context);
assertArrayEquals(
SealedTransformer.DESCRIPTOR_PREFIX,
getDescriptorPrefix(encryptedText));
assertTrue(encryptedText.length < Transformer.MAX_GLUE_STRING_BYTES);
final byte[] unmarshalledText = sealedTransformer.unmarshal(encryptedText);
assertArrayEquals(cleartext, unmarshalledText);
}
@Test
public void marshalledValueTooLongTest() {
// The necessary bytes is really less than this, but it gets the point across
final byte[] cleartext = new byte[Transformer.MAX_GLUE_STRING_BYTES + 1];
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.clientDataType(CsvValue.CLIENT_DATA_TYPE)
.padType(PadType.NONE) // PadType must be none to avoid other restrictions preventing the error
.nonce(nonce).build();
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.marshal(cleartext, context));
}
@Test
public void marshalNullDataPreserveNullsFalseTest() {
final byte[] encryptedBytes = sealedTransformer.marshal(null, context);
final byte[] expectedBytes = ("01:enc:bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWftg96a4yADdecnBVZYmd8IxXr30")
.getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedBytes, encryptedBytes);
}
@Test
public void marshalNullDataPreserveNullsTrueTest() {
final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, KeyUtil.KEY_ALG);
final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
sealedTransformer = new SealedTransformer(Encryptor.getInstance(provider), ClientSettings.lowAssuranceMode());
final byte[] encryptedText = sealedTransformer.marshal(null, context);
assertNull(encryptedText);
}
@Test
public void marshalEmptyDataTest() {
final byte[] encryptedText = sealedTransformer.marshal("".getBytes(StandardCharsets.UTF_8), context);
// Strictly prefix and encrypted padding
final byte[] expectedText = "01:enc:bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWfth96bE3B6pNqPzS3k9XRM+joTw"
.getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, encryptedText);
final byte[] unmarshalledText = sealedTransformer.unmarshal(encryptedText);
assertArrayEquals("".getBytes(StandardCharsets.UTF_8), unmarshalledText);
}
@Test
public void marshalNullNonceTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final EncryptionContext context = EncryptionContext.builder()
.clientDataType(CsvValue.CLIENT_DATA_TYPE)
.columnLabel("label")
.padType(PadType.NONE)
.nonce(null).build();
assertThrows(C3rIllegalArgumentException.class, () -> sealedTransformer.marshal(cleartext, context));
}
@Test
public void marshalNullEncryptionContextTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> sealedTransformer.marshal(cleartext, null));
}
@Test
public void unmarshalInvalidNonceTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final byte[] encryptedBytes = sealedTransformer.marshal(cleartext, context);
encryptedBytes[6] = (byte) (encryptedBytes[6] - 1); // Manipulate a nonce byte
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.unmarshal(encryptedBytes));
}
@Test
public void unmarshalInvalidEncodingTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final ByteBuffer encryptedText = ByteBuffer.wrap(sealedTransformer.marshal(cleartext, context));
// Non-Base64 chars
final byte[] prefix = new byte[sealedTransformer.getEncryptionDescriptor().length + sealedTransformer.getVersion().length];
encryptedText.get(prefix);
// Make the file no longer formatted.
final byte[] encodedCiphertext = new byte[encryptedText.remaining()];
encryptedText.get(encodedCiphertext);
final byte[] nonBase64EncryptedText = Base64.getDecoder().decode(encodedCiphertext);
final byte[] badCiphertext = ByteBuffer.allocate(prefix.length + nonBase64EncryptedText.length)
.put(prefix)
.put(nonBase64EncryptedText)
.array();
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.unmarshal(badCiphertext));
}
@Test
public void unmarshalPreservedNullTest() {
assertNull(sealedTransformer.unmarshal(null));
}
@Test
public void unmarshalNullTest() {
final byte[] encryptedText = sealedTransformer.marshal(null, context);
// Strictly prefix and encrypted padding
final byte[] expectedText = "01:enc:bm9uY2UwMTIzNDU2Nzg5MG5vbmNlMDEyMzQ1Njc4OTBqfRYZ98t5KU6aWftg96a4yADdecnBVZYmd8IxXr30"
.getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, encryptedText);
final byte[] unmarshalledText = sealedTransformer.unmarshal(encryptedText);
assertArrayEquals(null, unmarshalledText);
}
@Test
public void prefixMessageTest() {
final byte[] message = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final InitializationVector iv = InitializationVector.deriveIv(context.getColumnLabel(), nonce);
final byte[] prefixedMessage = sealedTransformer.buildBase64EncodedMessage(message, nonce, iv);
final ByteBuffer decodedPrefixMessage = ByteBuffer.wrap(Base64.getDecoder().decode(prefixedMessage));
final byte[] prefixNonce = new byte[nonce.getBytes().length];
decodedPrefixMessage.get(prefixNonce);
assertArrayEquals(nonce.getBytes(), prefixNonce);
final byte[] prefixIv = new byte[iv.getBytes().length];
decodedPrefixMessage.get(prefixIv);
assertArrayEquals(iv.getBytes(), prefixIv);
final byte[] prefixMessage = new byte[message.length];
decodedPrefixMessage.get(prefixMessage);
assertArrayEquals(message, prefixMessage);
}
@Test
public void verifyFormatVersionTest() {
assertDoesNotThrow(() -> sealedTransformer.verifyFormatVersion(ByteBuffer.wrap(exampleCiphertext)));
}
@Test
public void verifyFormatVersionInvalidTest() {
// way too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyFormatVersion(
ByteBuffer.wrap("".getBytes(StandardCharsets.UTF_8))));
// one character too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyFormatVersion(
ByteBuffer.wrap(Arrays.copyOfRange(
exampleCiphertext,
0,
SealedTransformer.FORMAT_VERSION.length - 1))));
// flip the bits in one byte in an otherwise valid array of bytes, make sure it fails
final byte[] oneByteWrong = Arrays.copyOf(exampleCiphertext, exampleCiphertext.length);
// works before a bit flip
assertDoesNotThrow(() -> sealedTransformer.verifyFormatVersion(ByteBuffer.wrap(oneByteWrong)));
oneByteWrong[SealedTransformer.FORMAT_VERSION.length - 1] =
(byte) ~oneByteWrong[SealedTransformer.FORMAT_VERSION.length - 1];
// fails after a bit flip
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyFormatVersion(
ByteBuffer.wrap(oneByteWrong)));
}
@Test
public void verifyEncryptionDescriptorTest() {
assertDoesNotThrow(() -> sealedTransformer.verifyEncryptionDescriptor(ByteBuffer.wrap(exampleCiphertext)
.position(SealedTransformer.FORMAT_VERSION.length)));
}
@Test
public void verifyEncryptionDescriptorInvalidTest() {
// way too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyEncryptionDescriptor(
ByteBuffer.wrap("".getBytes(StandardCharsets.UTF_8))));
// one byte too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyEncryptionDescriptor(
ByteBuffer.wrap(Arrays.copyOfRange(
exampleCiphertext,
SealedTransformer.FORMAT_VERSION.length,
SealedTransformer.DESCRIPTOR_PREFIX.length - 1))));
// flip the bits in one byte in an otherwise valid array of bytes, make sure it fails
final byte[] oneByteWrong = Arrays.copyOfRange(
exampleCiphertext,
SealedTransformer.FORMAT_VERSION.length,
exampleCiphertext.length);
// works before a bit flip
assertDoesNotThrow(() -> sealedTransformer.verifyEncryptionDescriptor(ByteBuffer.wrap(oneByteWrong)));
oneByteWrong[SealedTransformer.FORMAT_VERSION.length] =
(byte) ~oneByteWrong[SealedTransformer.FORMAT_VERSION.length];
// fails after a bit flip
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyEncryptionDescriptor(
ByteBuffer.wrap(oneByteWrong)));
}
@Test
public void extractNonceTest() {
final Nonce extractedNonce = sealedTransformer.extractNonce(ByteBuffer.wrap(exampleDecodedCiphertextBody));
assertArrayEquals(nonce.getBytes(), extractedNonce.getBytes());
}
@Test
public void extractNonceBadTest() {
// way too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.extractNonce(
ByteBuffer.wrap("".getBytes(StandardCharsets.UTF_8))
));
// one byte too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.verifyEncryptionDescriptor(
ByteBuffer.wrap(Arrays.copyOfRange(
exampleDecodedCiphertextBody,
0,
Nonce.NONCE_BYTE_LENGTH - 1))));
}
@Test
public void extractIvTest() {
final InitializationVector extractedIv = sealedTransformer.extractIv(ByteBuffer.wrap(exampleDecodedCiphertextBody)
.position(Nonce.NONCE_BYTE_LENGTH));
assertArrayEquals(iv.getBytes(), extractedIv.getBytes());
}
@Test
public void extractIvBadTest() {
// way too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.extractIv(
ByteBuffer.wrap("".getBytes(StandardCharsets.UTF_8))
));
// one byte too short
assertThrows(C3rRuntimeException.class, () -> sealedTransformer.extractIv(
ByteBuffer.wrap(
Arrays.copyOfRange(
exampleDecodedCiphertextBody,
Nonce.NONCE_BYTE_LENGTH,
Nonce.NONCE_BYTE_LENGTH + InitializationVector.IV_BYTE_LENGTH - 1))));
}
@Test
public void extractCiphertextTest() {
final byte[] extractedContent = sealedTransformer.extractCiphertext(
ByteBuffer.wrap(exampleDecodedCiphertextBody)
.position(Nonce.NONCE_BYTE_LENGTH + InitializationVector.IV_BYTE_LENGTH));
assertArrayEquals(ciphertextContent, extractedContent);
}
@Test
public void getEncryptionDescriptorImmutableTest() {
final byte[] descriptor = sealedTransformer.getEncryptionDescriptor();
Arrays.fill(descriptor, (byte) 0);
assertFalse(Arrays.equals(sealedTransformer.getEncryptionDescriptor(), descriptor));
}
@Test
public void getVersionImmutableTest() {
final byte[] version = sealedTransformer.getVersion();
Arrays.fill(version, (byte) 0);
assertFalse(Arrays.equals(sealedTransformer.getVersion(), version));
}
@Test
public void descriptorStringTest() {
assertTrue(Transformer.hasDescriptor(
sealedTransformer,
SealedTransformer.DESCRIPTOR_PREFIX_STRING.getBytes(StandardCharsets.UTF_8)));
}
@Test
public void marshalMissingClientDataTypeTest() {
// Currently only encrypting strings is supported
final byte[] cleartext = ByteBuffer.allocate(INT_BYTE_SIZE).putInt(42).array();
final EncryptionContext context = EncryptionContext.builder()
.clientDataType(null)
.columnLabel("label")
.nonce(nonce)
.build();
assertThrows(C3rIllegalArgumentException.class, () -> sealedTransformer.marshal(cleartext, context));
}
@Test
public void marshalNonStringTest() {
// Currently only encrypting strings is supported
final byte[] cleartext = ByteBuffer.allocate(INT_BYTE_SIZE).putInt(42).array();
final EncryptionContext context = EncryptionContext.builder()
.clientDataType(ClientDataType.UNKNOWN)
.columnLabel("label")
.nonce(nonce)
.build();
assertThrows(C3rIllegalArgumentException.class, () -> sealedTransformer.marshal(cleartext, context));
}
}
| 2,505 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/CleartextTransformerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CleartextTransformerTest {
private CleartextTransformer transformer;
@BeforeEach
public void setup() {
transformer = new CleartextTransformer();
}
@Test
public void marshalTest() {
final byte[] cleartext = "Some cleartext".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(cleartext, transformer.marshal(cleartext, null));
}
@Test
public void marshalledValueTooLongTest() {
final byte[] cleartext = new byte[Transformer.MAX_GLUE_STRING_BYTES + 1];
assertThrows(C3rRuntimeException.class, () -> transformer.marshal(cleartext, null));
}
@Test
public void marshalNullTest() {
assertNull(transformer.marshal(null, null));
}
@Test
public void unmarshalTest() {
final byte[] ciphertext = "Some ciphertext".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(ciphertext, transformer.unmarshal(ciphertext));
}
@Test
public void unmarshalNullTest() {
assertNull(transformer.unmarshal(null));
}
@Test
public void getEncryptionDescriptorTest() {
assertThrows(C3rRuntimeException.class, () -> transformer.getEncryptionDescriptor());
}
@Test
public void getVersionImmutableTest() {
final byte[] version = transformer.getVersion();
Arrays.fill(version, (byte) 0);
assertFalse(Arrays.equals(transformer.getVersion(), version));
}
}
| 2,506 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/FingerprintTransformerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FingerprintTransformerTest {
private final EncryptionContext differentColumnContext = EncryptionContext.builder()
.columnLabel("differentLabel")
.clientDataType(ClientDataType.STRING)
.build();
private final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, "AES");
private final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.clientDataType(ClientDataType.STRING)
.build();
private FingerprintTransformer fingerprintTransformer;
@BeforeEach
public void setup() {
fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.highAssuranceMode(), false);
}
@Test
public void fingerprintTransformerNullSecretKeyTest() {
assertThrows(C3rRuntimeException.class,
() -> new FingerprintTransformer(null, salt, ClientSettings.highAssuranceMode(), false));
}
@Test
public void fingerprintTransformerNullSaltTest() {
assertThrows(C3rRuntimeException.class,
() -> new FingerprintTransformer(secretKey, null, ClientSettings.highAssuranceMode(),
false));
}
@Test
public void fingerprintTransformerEmptySaltTest() {
assertThrows(C3rRuntimeException.class, () -> new FingerprintTransformer(secretKey, new byte[0],
ClientSettings.highAssuranceMode(),
false));
}
@Test
public void marshalNullEncryptionContextTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> fingerprintTransformer.marshal(cleartext, null));
}
private byte[] getDescriptorPrefix(final byte[] bytes) {
return Arrays.copyOfRange(bytes, 0, FingerprintTransformer.DESCRIPTOR_PREFIX.length);
}
@Test
public void marshalAllowJoinsOnColumnsWithDifferentNamesFalseTest() {
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final byte[] hmacText = fingerprintTransformer.marshal(cleartext, context);
assertArrayEquals(
FingerprintTransformer.DESCRIPTOR_PREFIX,
getDescriptorPrefix(hmacText));
final byte[] expectedText = "02:hmac:WRtZMlbn+zFNU5YAR0UT1S9v128kUMhV2PAJSdjGzqw=".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, hmacText);
final byte[] differentColumnHmacText = fingerprintTransformer.marshal(cleartext, differentColumnContext);
assertFalse(Arrays.equals(hmacText, differentColumnHmacText));
}
@Test
public void marshalAllowJoinsOnColumnsWithDifferentNamesTrueTest() {
final FingerprintTransformer fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.lowAssuranceMode(),
false);
final byte[] cleartext = "some cleartext data".getBytes(StandardCharsets.UTF_8);
final byte[] hmacText = fingerprintTransformer.marshal(cleartext, context);
assertArrayEquals(
FingerprintTransformer.DESCRIPTOR_PREFIX,
getDescriptorPrefix(hmacText));
final byte[] expectedText = "02:hmac:7YchN4H6pV0CxfGNX51VXRjCNx0/V43fMkV0lkTfAeE=".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, hmacText);
final byte[] differentColumnHmacText = fingerprintTransformer.marshal(cleartext, differentColumnContext);
assertArrayEquals(hmacText, differentColumnHmacText);
}
@Test
public void marshalNullDataPreserveNullsFalseTest() {
final byte[] hmacText = fingerprintTransformer.marshal(null, context);
assertNotNull(hmacText);
}
@Test
public void marshalNullDataPreserveNullsTrueTest() {
fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.lowAssuranceMode(), false);
final byte[] hmacText = fingerprintTransformer.marshal(null, context);
assertNull(hmacText);
}
@Test
public void marshalEmptyDataTest() {
final byte[] cleartext = "".getBytes(StandardCharsets.UTF_8);
final byte[] hmacText = fingerprintTransformer.marshal(cleartext, context);
assertArrayEquals(
FingerprintTransformer.DESCRIPTOR_PREFIX,
getDescriptorPrefix(hmacText));
final byte[] expectedText = "02:hmac:+UJjyBG1kJXUe4u0C5FTM7WaEhGl9+PB5blhAURDvnQ=".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(expectedText, hmacText);
}
@Test
public void unmarshalFailOnUnmarshalTrueTest() {
fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.lowAssuranceMode(), true);
final byte[] hmacText = "02:hmac:i0Y63cL+J5DpQw3rd3lnnwT1LSBEv+MppUxrajPkz44=".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.unmarshal(hmacText));
}
@Test
public void unmarshalFailOnUnmarshalFalseTest() {
fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.lowAssuranceMode(), false);
final byte[] hmacText = "01:hmac:i0Y63cL+J5DpQw3rd3lnnwT1LSBEv+MppUxrajPkz44=".getBytes(StandardCharsets.UTF_8);
assertArrayEquals(hmacText, fingerprintTransformer.unmarshal(hmacText));
}
@Test
public void getEncryptionDescriptorImmutableTest() {
final byte[] descriptor = fingerprintTransformer.getEncryptionDescriptor();
Arrays.fill(descriptor, (byte) 0);
assertFalse(Arrays.equals(fingerprintTransformer.getEncryptionDescriptor(), descriptor));
}
@Test
public void getVersionImmutableTest() {
final byte[] version = fingerprintTransformer.getVersion();
Arrays.fill(version, (byte) 0);
assertFalse(Arrays.equals(fingerprintTransformer.getVersion(), version));
}
@Test
public void descriptorStringTest() {
assertTrue(Transformer.hasDescriptor(
fingerprintTransformer,
FingerprintTransformer.DESCRIPTOR_PREFIX_STRING.getBytes(StandardCharsets.UTF_8)));
}
}
| 2,507 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/EncryptorTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.AdditionalAuthenticatedData;
import com.amazonaws.c3r.internal.InitializationVector;
import com.amazonaws.c3r.internal.Nonce;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class EncryptorTest {
private final AdditionalAuthenticatedData aad = new AdditionalAuthenticatedData(new byte[]{1});
private final Nonce nonce = new Nonce("nonce01234567890nonce01234567890".getBytes(StandardCharsets.UTF_8));
private final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, "AES");
private final InitializationVector iv = InitializationVector.deriveIv("label", nonce);
private final EncryptionContext context = EncryptionContext.builder()
.nonce(nonce)
.columnLabel("label")
.build();
@Test
public void encryptionWithSymmetricStaticProviderTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
final byte[] cipherText = encryptor.encrypt(cleartext, iv, aad, context);
assertNotEquals(cleartext, cipherText);
final byte[] decryptedText = encryptor.decrypt(cipherText, iv, aad, context);
assertArrayEquals(cleartext, decryptedText);
}
@Test
public void encryptionWithSymmetricStaticProviderAndNullDataTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
assertThrows(C3rIllegalArgumentException.class, () -> encryptor.encrypt(null, iv, aad, context));
}
@Test
public void encryptionWithSymmetricStaticProviderAndNullAadTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final EncryptionContext context = EncryptionContext.builder()
.nonce(nonce)
.columnLabel("label")
.build();
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
final byte[] cipherText = encryptor.encrypt(cleartext, iv, null, context);
assertNotEquals(cleartext, cipherText);
final byte[] decryptedText = encryptor.decrypt(cipherText, iv, null, context);
assertArrayEquals(cleartext, decryptedText);
}
@Test
public void encryptionWithSymmetricStaticProviderAndNullNonceTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final EncryptionContext context = EncryptionContext.builder()
.nonce(null)
.columnLabel("label")
.build();
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> encryptor.encrypt(cleartext, iv, aad, context));
}
@Test
public void encryptionWithSymmetricStaticProviderAndNullEncryptionContextTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> encryptor.encrypt(cleartext, iv, aad, null));
}
@Test
public void encryptionWithSymmetricStaticProviderAndBadKeyMaterialsTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
final byte[] cipherText = encryptor.encrypt(cleartext, iv, aad, context);
assertNotEquals(cleartext, cipherText);
final byte[] badSecret = "SomeBadKey".getBytes(StandardCharsets.UTF_8);
final SecretKey badKey = new SecretKeySpec(badSecret, 0, badSecret.length, "AES");
final Encryptor badEncryptor = Encryptor.getInstance(new SymmetricStaticProvider(badKey, salt));
assertThrows(C3rRuntimeException.class, () -> badEncryptor.decrypt(cipherText, iv, aad, context));
}
@Test
public void encryptionWithSymmetricStaticProviderAndBadSaltTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final Encryptor encryptor = Encryptor.getInstance(provider);
final byte[] cleartext = "some plain text".getBytes(StandardCharsets.UTF_8);
final byte[] cipherText = encryptor.encrypt(cleartext, iv, aad, context);
assertNotEquals(cleartext, cipherText);
final byte[] badSalt = "AnIncorrectSalt".getBytes(StandardCharsets.UTF_8);
final Encryptor badEncryptor = Encryptor.getInstance(new SymmetricStaticProvider(secretKey, badSalt));
assertThrows(C3rRuntimeException.class, () -> badEncryptor.decrypt(cipherText, iv, aad, context));
}
}
| 2,508 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/EncryptionContextTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Nonce;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class EncryptionContextTest {
private final Nonce nonce = new Nonce("nonce01234567890nonce01234567890".getBytes(StandardCharsets.UTF_8));
@Test
public void constructorTest() {
final String label = "label";
final int padLength = 1;
final int maxValueLength = 5;
final EncryptionContext context = EncryptionContext.builder()
.padLength(padLength)
.columnLabel(label)
.padType(PadType.FIXED)
.nonce(nonce)
.maxValueLength(maxValueLength)
.build();
assertEquals(label, context.getColumnLabel());
assertEquals(padLength, context.getPadLength());
assertEquals(maxValueLength, context.getMaxValueLength());
assertEquals(PadType.FIXED, context.getPadType());
assertArrayEquals(nonce.getBytes(), context.getNonce().getBytes());
}
@Test
public void constructorNullLabelTest() {
final int padLength = 1;
assertThrows(C3rIllegalArgumentException.class, () -> EncryptionContext.builder()
.padLength(padLength)
.columnLabel(null)
.nonce(nonce)
.build());
}
@Test
public void constructorEmptyLabelTest() {
final int padLength = 1;
assertThrows(C3rIllegalArgumentException.class, () -> EncryptionContext.builder()
.padLength(padLength)
.columnLabel("")
.nonce(nonce)
.build());
}
}
| 2,509 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/materials/SymmetricRawMaterialsTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
import org.junit.jupiter.api.Test;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class SymmetricRawMaterialsTest {
private final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final DerivedRootEncryptionKey secretKey =
new DerivedRootEncryptionKey(new SecretKeySpec(secret, 0, secret.length, "AES"), salt);
@Test
public void constructorTest() {
final SymmetricRawMaterials materials = new SymmetricRawMaterials(secretKey);
final byte[] encryptionKey = materials.getRootEncryptionKey().getEncoded();
final byte[] decryptionKey = materials.getRootDecryptionKey().getEncoded();
assertArrayEquals(encryptionKey, decryptionKey);
}
}
| 2,510 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/config/ClientSettingsTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.config;
import com.amazonaws.c3r.config.ClientSettings;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClientSettingsTest {
@Test
public void builderTest() {
final ClientSettings settings = ClientSettings.builder()
.allowDuplicates(true)
.allowJoinsOnColumnsWithDifferentNames(true)
.allowCleartext(true)
.preserveNulls(true).build();
assertTrue(settings.isAllowDuplicates());
assertTrue(settings.isAllowJoinsOnColumnsWithDifferentNames());
assertTrue(settings.isAllowCleartext());
assertTrue(settings.isPreserveNulls());
}
@Test
public void highAssuranceModeTest() {
final ClientSettings settings = ClientSettings.highAssuranceMode();
assertFalse(settings.isAllowDuplicates());
assertFalse(settings.isAllowJoinsOnColumnsWithDifferentNames());
assertFalse(settings.isAllowCleartext());
assertFalse(settings.isPreserveNulls());
}
@Test
public void lowAssuranceModeTest() {
final ClientSettings settings = ClientSettings.lowAssuranceMode();
assertTrue(settings.isAllowDuplicates());
assertTrue(settings.isAllowJoinsOnColumnsWithDifferentNames());
assertTrue(settings.isAllowCleartext());
assertTrue(settings.isPreserveNulls());
}
}
| 2,511 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/providers/SymmetricStaticProviderTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.providers;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public class SymmetricStaticProviderTest {
private final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, "AES");
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
@Test
public void constructorTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final byte[] encryptionKey = provider.getEncryptionMaterials(null).getRootEncryptionKey().getEncoded();
final byte[] decryptionKey = provider.getDecryptionMaterials(null).getRootDecryptionKey().getEncoded();
assertArrayEquals(encryptionKey, decryptionKey);
}
@Test
public void refreshTest() {
final SymmetricStaticProvider provider = new SymmetricStaticProvider(secretKey, salt);
final byte[] encryptionKey = provider.getEncryptionMaterials(null).getRootEncryptionKey().getEncoded();
final byte[] decryptionKey = provider.getDecryptionMaterials(null).getRootDecryptionKey().getEncoded();
provider.refresh();
final byte[] refreshedEncryptionKey = provider.getEncryptionMaterials(null).getRootEncryptionKey().getEncoded();
final byte[] refreshedDecryptionKey = provider.getDecryptionMaterials(null).getRootDecryptionKey().getEncoded();
assertArrayEquals(encryptionKey, refreshedEncryptionKey);
assertArrayEquals(decryptionKey, refreshedDecryptionKey);
}
}
| 2,512 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/KeyTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Nonce;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class KeyTest {
@Test
public void nullKeyValidationTest() {
final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedRootEncryptionKey(null, salt));
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedEncryptionKey(null, Nonce.nextNonce()));
}
}
| 2,513 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/DerivedRootEncryptionKeyTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static com.amazonaws.c3r.encryption.keys.KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DerivedRootEncryptionKeyTest {
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey =
new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, 0, SHARED_SECRET_KEY_BYTE_LENGTH, KeyUtil.KEY_ALG);
@Test
public void deriveRootEncryptionKeyTest() {
final DerivedRootEncryptionKey derivedRootEncryptionKey = new DerivedRootEncryptionKey(secretKey, salt);
assertEquals(KeyUtil.KEY_ALG, derivedRootEncryptionKey.getAlgorithm());
assertEquals(SHARED_SECRET_KEY_BYTE_LENGTH, derivedRootEncryptionKey.getEncoded().length);
}
@Test
public void deriveRootEncryptionKeyNullKeyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedRootEncryptionKey(null, salt));
}
@Test
public void deriveRootEncryptionKeyNullSaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedRootEncryptionKey(secretKey, null));
}
@Test
public void deriveRootEncryptionKeyEmptySaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedRootEncryptionKey(secretKey, new byte[0]));
}
}
| 2,514 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/SaltedHkdfTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static com.amazonaws.c3r.encryption.keys.KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class SaltedHkdfTest {
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey =
new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, 0, SHARED_SECRET_KEY_BYTE_LENGTH, KeyUtil.KEY_ALG);
@Test
public void saltedHkdfNullKeyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new SaltedHkdf(null, salt));
}
@Test
public void saltedHkdfNullSaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new SaltedHkdf(secretKey, null));
}
@Test
public void saltedHkdfEmptySaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new SaltedHkdf(secretKey, new byte[0]));
}
}
| 2,515 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/DerivedEncryptionKeyTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Nonce;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static com.amazonaws.c3r.encryption.keys.KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DerivedEncryptionKeyTest {
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey =
new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, 0, SHARED_SECRET_KEY_BYTE_LENGTH, KeyUtil.KEY_ALG);
private final DerivedRootEncryptionKey derivedRootEncryptionKey = new DerivedRootEncryptionKey(secretKey, salt);
@Test
public void deriveEncryptionKeyTest() {
final DerivedEncryptionKey derivedEncryptionKey = new DerivedEncryptionKey(derivedRootEncryptionKey, Nonce.nextNonce());
assertEquals(KeyUtil.KEY_ALG, derivedEncryptionKey.getAlgorithm());
assertEquals(SHARED_SECRET_KEY_BYTE_LENGTH, derivedEncryptionKey.getEncoded().length);
assertFalse(Arrays.equals(derivedRootEncryptionKey.getEncoded(), derivedEncryptionKey.getEncoded()));
}
@Test
public void deriveEncryptionKeySmallKeyTest() {
final DerivedRootEncryptionKey derivedRootEncryptionKey = mock(DerivedRootEncryptionKey.class);
when(derivedRootEncryptionKey.getEncoded()).thenReturn(new byte[SHARED_SECRET_KEY_BYTE_LENGTH - 1]); // less than required
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedEncryptionKey(derivedRootEncryptionKey, Nonce.nextNonce()));
}
@Test
public void deriveEncryptionKeyWithSameNonceTest() {
final Nonce nonce = Nonce.nextNonce();
final DerivedEncryptionKey derivedEncryptionKey1 = new DerivedEncryptionKey(derivedRootEncryptionKey, nonce);
final DerivedEncryptionKey derivedEncryptionKey2 = new DerivedEncryptionKey(derivedRootEncryptionKey, nonce);
assertArrayEquals(derivedEncryptionKey1.getEncoded(), derivedEncryptionKey2.getEncoded());
}
@Test
public void deriveEncryptionKeyChangesWithNonceTest() {
final DerivedEncryptionKey derivedEncryptionKey1 = new DerivedEncryptionKey(derivedRootEncryptionKey, Nonce.nextNonce());
final DerivedEncryptionKey derivedEncryptionKey2 = new DerivedEncryptionKey(derivedRootEncryptionKey, Nonce.nextNonce());
assertFalse(Arrays.equals(derivedEncryptionKey1.getEncoded(), derivedEncryptionKey2.getEncoded()));
}
@Test
public void deriveEncryptionKeyNullNonceTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedEncryptionKey(derivedRootEncryptionKey, null));
}
@Test
public void deriveEncryptionKeyNullRootKeyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new DerivedEncryptionKey(null, Nonce.nextNonce()));
}
}
| 2,516 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/HmacKeyDerivationFunctionTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class HmacKeyDerivationFunctionTest {
private static final TestCase[] TEST_CASES =
new TestCase[]{
new TestCase(
"HmacSHA256",
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"),
fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"),
fromHex("3CB25F25FAACD57A90434F64D0362F2A2D2D0A90CF1A5A4C5DB02D56ECC4C5BF34007208D5B887185865")),
new TestCase(
"HmacSHA256",
fromCHex(
"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d"
+ "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b"
+ "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29"
+ "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37"
+ "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45"
+ "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"),
fromCHex(
"\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6a\\x6b\\x6c\\x6d"
+ "\\x6e\\x6f\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7a\\x7b"
+ "\\x7c\\x7d\\x7e\\x7f\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89"
+ "\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97"
+ "\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\\xa0\\xa1\\xa2\\xa3\\xa4\\xa5"
+ "\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf"),
fromCHex(
"\\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd"
+ "\\xbe\\xbf\\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb"
+ "\\xcc\\xcd\\xce\\xcf\\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9"
+ "\\xda\\xdb\\xdc\\xdd\\xde\\xdf\\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7"
+ "\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5"
+ "\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"),
fromHex(
"B11E398DC80327A1C8E7F78C596A4934"
+ "4F012EDA2D4EFAD8A050CC4C19AFA97C"
+ "59045A99CAC7827271CB41C65E590E09"
+ "DA3275600C2F09B8367793A9ACA3DB71"
+ "CC30C58179EC3E87C14C01D5C1F3434F"
+ "1D87")),
new TestCase(
"HmacSHA256",
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
new byte[0],
new byte[0],
fromHex(
"8DA4E775A563C18F715F802A063C5A31"
+ "B8A11F5C5EE1879EC3454E5F3C738D2D"
+ "9D201395FAA4B61A96C8")),
new TestCase(
"HmacSHA1",
fromCHex("\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
fromCHex("\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c"),
fromCHex("\\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9"),
fromHex(
"085A01EA1B10F36933068B56EFA5AD81"
+ "A4F14B822F5B091568A9CDD4F155FDA2"
+ "C22E422478D305F3F896")),
new TestCase(
"HmacSHA1",
fromCHex(
"\\x00\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d"
+ "\\x0e\\x0f\\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b"
+ "\\x1c\\x1d\\x1e\\x1f\\x20\\x21\\x22\\x23\\x24\\x25\\x26\\x27\\x28\\x29"
+ "\\x2a\\x2b\\x2c\\x2d\\x2e\\x2f\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37"
+ "\\x38\\x39\\x3a\\x3b\\x3c\\x3d\\x3e\\x3f\\x40\\x41\\x42\\x43\\x44\\x45"
+ "\\x46\\x47\\x48\\x49\\x4a\\x4b\\x4c\\x4d\\x4e\\x4f"),
fromCHex(
"\\x60\\x61\\x62\\x63\\x64\\x65\\x66\\x67\\x68\\x69\\x6A\\x6B\\x6C\\x6D"
+ "\\x6E\\x6F\\x70\\x71\\x72\\x73\\x74\\x75\\x76\\x77\\x78\\x79\\x7A\\x7B"
+ "\\x7C\\x7D\\x7E\\x7F\\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89"
+ "\\x8A\\x8B\\x8C\\x8D\\x8E\\x8F\\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97"
+ "\\x98\\x99\\x9A\\x9B\\x9C\\x9D\\x9E\\x9F\\xA0\\xA1\\xA2\\xA3\\xA4\\xA5"
+ "\\xA6\\xA7\\xA8\\xA9\\xAA\\xAB\\xAC\\xAD\\xAE\\xAF"),
fromCHex(
"\\xB0\\xB1\\xB2\\xB3\\xB4\\xB5\\xB6\\xB7\\xB8\\xB9\\xBA\\xBB\\xBC\\xBD"
+ "\\xBE\\xBF\\xC0\\xC1\\xC2\\xC3\\xC4\\xC5\\xC6\\xC7\\xC8\\xC9\\xCA\\xCB"
+ "\\xCC\\xCD\\xCE\\xCF\\xD0\\xD1\\xD2\\xD3\\xD4\\xD5\\xD6\\xD7\\xD8\\xD9"
+ "\\xDA\\xDB\\xDC\\xDD\\xDE\\xDF\\xE0\\xE1\\xE2\\xE3\\xE4\\xE5\\xE6\\xE7"
+ "\\xE8\\xE9\\xEA\\xEB\\xEC\\xED\\xEE\\xEF\\xF0\\xF1\\xF2\\xF3\\xF4\\xF5"
+ "\\xF6\\xF7\\xF8\\xF9\\xFA\\xFB\\xFC\\xFD\\xFE\\xFF"),
fromHex(
"0BD770A74D1160F7C9F12CD5912A06EB"
+ "FF6ADCAE899D92191FE4305673BA2FFE"
+ "8FA3F1A4E5AD79F3F334B3B202B2173C"
+ "486EA37CE3D397ED034C7F9DFEB15C5E"
+ "927336D0441F4C4300E2CFF0D0900B52D3B4")),
new TestCase(
"HmacSHA1",
fromCHex(
"\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"
+ "\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b\\x0b"),
new byte[0],
new byte[0],
fromHex("0AC1AF7002B3D761D1E55298DA9D0506" + "B9AE52057220A306E07B6B87E8DF21D0")),
new TestCase(
"HmacSHA1",
fromCHex(
"\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"
+ "\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c\\x0c"),
null,
new byte[0],
fromHex(
"2C91117204D745F3500D636A62F64F0A"
+ "B3BAE548AA53D423B0D1F27EBBA6F5E5"
+ "673A081D70CCE7ACFC48"))
};
private static byte[] fromHex(final String data) {
final byte[] result = new byte[data.length() / 2];
for (int x = 0; x < result.length; x++) {
result[x] = (byte) Integer.parseInt(data.substring(2 * x, 2 * x + 2), 16);
}
return result;
}
private static byte[] fromCHex(final String data) {
final byte[] result = new byte[data.length() / 4];
for (int x = 0; x < result.length; x++) {
result[x] = (byte) Integer.parseInt(data.substring(4 * x + 2, 4 * x + 4), 16);
}
return result;
}
@Test
public void rfc5869Tests() {
for (TestCase trial : TEST_CASES) {
final HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf.init(trial.ikm, trial.salt);
final byte[] result = kdf.deriveKey(trial.info, trial.expected.length);
assertArrayEquals(trial.expected, result);
}
}
@Test
public void nullTests() {
final TestCase trial = TEST_CASES[0];
final HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf.init(trial.ikm, trial.salt);
// Just ensuring no exceptions are thrown
kdf.deriveKey(null, 16);
}
@Test
public void invalidLength() {
final TestCase trial = TEST_CASES[0];
final HmacKeyDerivationFunction kdf = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf.init(trial.ikm, trial.salt);
assertThrows(C3rIllegalArgumentException.class, () -> kdf.deriveKey(trial.info, -1));
}
@Test
public void defaultSalt() {
// Tests all the different ways to get the default salt
final TestCase trial = TEST_CASES[0];
final HmacKeyDerivationFunction kdf1 = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf1.init(trial.ikm, null);
final HmacKeyDerivationFunction kdf2 = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf2.init(trial.ikm, new byte[0]);
final HmacKeyDerivationFunction kdf3 = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf3.init(trial.ikm);
final HmacKeyDerivationFunction kdf4 = HmacKeyDerivationFunction.getInstance(trial.algo);
kdf4.init(trial.ikm, new byte[32]);
final byte[] testBytes = "Test".getBytes(StandardCharsets.UTF_8);
final byte[] key1 = kdf1.deriveKey(testBytes, 16);
final byte[] key2 = kdf2.deriveKey(testBytes, 16);
final byte[] key3 = kdf3.deriveKey(testBytes, 16);
final byte[] key4 = kdf4.deriveKey(testBytes, 16);
assertArrayEquals(key1, key2);
assertArrayEquals(key1, key3);
assertArrayEquals(key1, key4);
}
private static class TestCase {
public final String algo;
public final byte[] ikm;
public final byte[] salt;
public final byte[] info;
public final byte[] expected;
TestCase(final String algo, final byte[] ikm, final byte[] salt, final byte[] info, final byte[] expected) {
super();
this.algo = algo;
this.ikm = ikm;
this.salt = salt;
this.info = info;
this.expected = expected;
}
}
} | 2,517 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/encryption/keys/KeyUtilTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import static com.amazonaws.c3r.encryption.keys.KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class KeyUtilTest {
@Test
public void getAes256KeyFromEnvVarTest() {
final String keyMaterial = "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8=";
final String secretKeyBase64 = Base64.getEncoder().encodeToString(GeneralTestUtility.EXAMPLE_KEY_BYTES);
assertEquals(secretKeyBase64, keyMaterial);
final byte[] keyBytes = Base64.getDecoder().decode(keyMaterial);
assertArrayEquals(GeneralTestUtility.EXAMPLE_KEY_BYTES, keyBytes);
final SecretKey secretKey =
new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, 0, SHARED_SECRET_KEY_BYTE_LENGTH, KeyUtil.KEY_ALG);
assertEquals(secretKey, KeyUtil.sharedSecretKeyFromString(keyMaterial));
}
@Test
public void getAes256KeyFromEnvVarMissingTest() {
final String keyMaterial = System.getenv(KeyUtil.KEY_ENV_VAR);
assertNull(keyMaterial);
assertThrows(C3rIllegalArgumentException.class, () -> KeyUtil.sharedSecretKeyFromString(null));
}
@Test
public void getAes256KeyFromEnvVarTooShortTest() {
assertThrows(C3rIllegalArgumentException.class, () -> KeyUtil.sharedSecretKeyFromString("12345"));
}
@Test
public void getAes256KeyFromEnvVarLongerThanNecessaryTest() {
final String keyMaterial = "11111111222222223333333344444444555555556666666677777777";
final byte[] expected = Base64.getDecoder().decode(keyMaterial);
assertArrayEquals(expected, KeyUtil.sharedSecretKeyFromString(keyMaterial).getEncoded());
}
}
| 2,518 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/PadTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.reflection.ReflectionMemberAccessor;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
public class PadTest {
@Test
public void defaultPadTypeNoneTest() {
final Pad pad = Pad.builder().build();
assertNull(pad.getType());
assertNull(pad.getLength());
}
@Test
public void padLengthPadTypeMaxTest() {
assertThrows(C3rIllegalArgumentException.class,
() -> Pad.builder().type(PadType.MAX).build());
}
@Test
public void padLengthPadTypeFixedTest() {
assertThrows(C3rIllegalArgumentException.class,
() -> Pad.builder().type(PadType.FIXED).build());
}
@Test
public void padLengthTest() {
final Pad pad = Pad.builder().type(PadType.MAX).length(10).build();
assertEquals(10, pad.getLength());
}
@Test
public void badPadTest() throws NoSuchFieldException, IllegalAccessException {
final Pad p = mock(Pad.class);
doCallRealMethod().when(p).validate();
final var rma = new ReflectionMemberAccessor();
final Field type = Pad.class.getDeclaredField("type");
final Field length = Pad.class.getDeclaredField("length");
rma.set(type, p, null);
rma.set(length, p, 10);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, p::validate);
assertEquals("A pad type is required if a pad length is specified but only a pad length was provided.", e.getMessage());
}
}
| 2,519 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/TableSchemaCommonTestInterface.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
// Defines a common set of tests all schema types should implement.
public interface TableSchemaCommonTestInterface {
// Verify that headers are correctly autogenerated as needed.
void verifyAutomaticHeaderConstructionTest();
// Verify one source column can be mapped to multiple output columns as long as they have unique target header names.
void oneSourceToManyTargetsTest();
// Verify that is the same target header name is used more than once in a schema, it fails validation.
void repeatedTargetFailsTest();
// Validate that the column is null the schema is not accepted.
void validateNullColumnValueIsRejectedTest();
// Validate that if the output column list is empty, the schema is not accepted.
void validateEmptyColumnValueIsRejectedTest();
// Test the implementation of equals and hash to make sure results are as expected.
void equalsAndHashTest();
// Verify the header row can't be the wrong value and the schema will still work.
void verifyHeaderRowValueTest();
// Check the results from {@code getColumns()} matches the ones used in the schema and not the ones in the file.
void verifyColumnsInResultsTest();
// Check that {@code getColumns()} returns properly validated columns.
void verifyGetColumnsTest() throws IllegalAccessException, NoSuchFieldException;
// Make sure the various states of unspecified headers are correct for the child implementation.
void verifyGetUnspecifiedHeadersReturnValueTest() throws IllegalAccessException, NoSuchFieldException;
// Make sure child implementation rejects all invalid headers for its type.
void verifyChildSpecificInvalidHeaderConstructionTest();
// Check the child specific {@code verification} function to be sure it works as expected.
void checkClassSpecificVerificationTest() throws IllegalAccessException, NoSuchFieldException;
}
| 2,520 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/MappedTableSchemaTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.action.CsvRowMarshaller;
import com.amazonaws.c3r.action.RowMarshaller;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.CsvTestUtility;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.reflection.ReflectionMemberAccessor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class MappedTableSchemaTest implements TableSchemaCommonTestInterface {
private static final ColumnSchema CS_S_1_TO_UNNAMED_CLEARTEXT = GeneralTestUtility.cleartextColumn("S1", null);
private static final ColumnSchema CS_S_1_TO_UNNAMED_CLEARTEXT_FINAL = GeneralTestUtility.cleartextColumn("S1", "s1");
private static final ColumnSchema CS_S_1_TO_UNNAMED_FINGERPRINT = GeneralTestUtility.fingerprintColumn("S1", null);
private static final ColumnSchema CS_S_1_TO_UNNAMED_FINGERPRINT_FINAL = GeneralTestUtility.fingerprintColumn("S1", "s1" +
ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX);
private static final ColumnSchema CS_S_1_TO_UNNAMED_SEALED = GeneralTestUtility.sealedColumn("S1", null, PadType.FIXED, 50);
private static final ColumnSchema CS_S_1_TO_UNNAMED_SEALED_FINAL = GeneralTestUtility.sealedColumn("S1", "s1" +
ColumnHeader.DEFAULT_SEALED_SUFFIX, PadType.FIXED, 50);
private static final ColumnSchema CS_S_1_TO_T_1 = GeneralTestUtility.cleartextColumn("S1", "T1");
private static final ColumnSchema CS_S_2_TO_T_1 = GeneralTestUtility.cleartextColumn("S2", "T1");
private String tempDir;
private String output;
@BeforeEach
public void setup() throws IOException {
tempDir = FileTestUtility.createTempDir().toString();
output = FileTestUtility.resolve("output.csv").toString();
}
// Verify that target headers are created automatically when unspecified in the schema
@Override
@Test
public void verifyAutomaticHeaderConstructionTest() {
final var createdTargetHeaders = new MappedTableSchema(List.of(CS_S_1_TO_UNNAMED_CLEARTEXT, CS_S_1_TO_UNNAMED_FINGERPRINT,
CS_S_1_TO_UNNAMED_SEALED));
final var knownGoodValues = List.of(CS_S_1_TO_UNNAMED_CLEARTEXT_FINAL, CS_S_1_TO_UNNAMED_FINGERPRINT_FINAL,
CS_S_1_TO_UNNAMED_SEALED_FINAL);
assertEquals(knownGoodValues, createdTargetHeaders.getColumns());
}
// Confirm one source column can be mapped to many output columns
@Override
@Test
public void oneSourceToManyTargetsTest() {
final var schema = new MappedTableSchema(List.of(CS_S_1_TO_T_1, CS_S_1_TO_UNNAMED_CLEARTEXT));
assertTrue(schema.getColumns().stream().map(ColumnSchema::getSourceHeader).map(ColumnHeader::toString).allMatch("s1"::equals));
assertEquals(schema.getColumns().size(), schema.getColumns().stream().map(ColumnSchema::getTargetHeader).distinct().count());
}
// Confirm that if a target header is reused, the mapping is not accepted.
@Override
@Test
public void repeatedTargetFailsTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> new MappedTableSchema(List.of(CS_S_1_TO_T_1, CS_S_2_TO_T_1)));
assertEquals("Target header name can only be used once. Duplicates found: t1", e.getMessage());
}
// Confirm that if columns is null, the schema is rejected.
@Override
@Test
public void validateNullColumnValueIsRejectedTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> new MappedTableSchema(null));
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
// Confirm that if an empty schema is used, the schema is rejected
@Override
@Test
public void validateEmptyColumnValueIsRejectedTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> new MappedTableSchema(List.of()));
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
// Check equality operator and hashing work as expected
@Override
@Test
public void equalsAndHashTest() {
final MappedTableSchema m1 = new MappedTableSchema(List.of(CS_S_1_TO_T_1));
final MappedTableSchema m2 = new MappedTableSchema(List.of(CS_S_1_TO_T_1));
final MappedTableSchema m3 = new MappedTableSchema(List.of(CS_S_1_TO_UNNAMED_FINGERPRINT));
final MappedTableSchema m1Copy = new MappedTableSchema(m1.getColumns());
final TableSchema p = new PositionalTableSchema(List.of(List.of(GeneralTestUtility.cleartextColumn(null, "t1"))));
final TableSchema mP = new MappedTableSchema(p.getColumns());
assertEquals(m1, m2);
assertEquals(m1.hashCode(), m2.hashCode());
assertNotEquals(m1, m3);
assertNotEquals(m1.hashCode(), m3.hashCode());
assertEquals(m1, m1Copy);
assertEquals(m1.hashCode(), m1Copy.hashCode());
assertNotEquals(p, mP);
}
// Verify header row value must be true for Mapped schemas to work.
@Override
@Test
public void verifyHeaderRowValueTest() {
final MappedTableSchema schema = new MappedTableSchema(List.of(CS_S_1_TO_T_1, CS_S_1_TO_UNNAMED_CLEARTEXT));
schema.setHeaderRowFlag(false);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Mapped Table Schemas require a header row in the data.", e.getMessage());
}
// Confirm getColumns returns the ones in the schema specification, not the file.
@Override
@Test
public void verifyColumnsInResultsTest() {
final MappedTableSchema schema = new MappedTableSchema(List.of(GeneralTestUtility.cleartextColumn("firstname")));
final EncryptConfig config = EncryptConfig.builder()
.secretKey(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.tempDir(tempDir)
.salt(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getSettings())
.tableSchema(schema)
.overwrite(true)
.build();
final RowMarshaller<CsvValue> rowMarshaller = CsvRowMarshaller.newInstance(config);
rowMarshaller.marshal();
rowMarshaller.close();
final var values = CsvTestUtility.readRows(output);
for (var r : values) {
assertEquals(1, r.size());
assertTrue(r.containsKey("firstname"));
}
}
// Make sure mapped columns are correctly interpreted.
@Override
@Test
public void verifyGetColumnsTest() throws IllegalAccessException, NoSuchFieldException {
final var schema = mock(MappedTableSchema.class);
doCallRealMethod().when(schema).getColumns();
doCallRealMethod().when(schema).validate();
final var rma = new ReflectionMemberAccessor();
final Field validatedColumns = MappedTableSchema.class.getDeclaredField("validatedColumns");
rma.set(validatedColumns, schema, null);
final Field columns = MappedTableSchema.class.getDeclaredField("columns");
final List<ColumnSchema> nullSource = List.of(GeneralTestUtility.cleartextColumn(null, "target"));
rma.set(columns, schema, nullSource);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Mapped Table Schemas require a header row in the data.", e.getMessage());
rma.set(validatedColumns, schema, null);
final List<ColumnSchema> makeTarget = List.of(GeneralTestUtility.fingerprintColumn("source", null));
rma.set(columns, schema, makeTarget);
final var finalizedCols = schema.getColumns();
assertEquals(1, finalizedCols.size());
assertEquals(new ColumnHeader("source" + ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX), finalizedCols.get(0).getTargetHeader());
rma.set(validatedColumns, schema, null);
final List<ColumnSchema> completeTarget = List.of(GeneralTestUtility.sealedColumn("source", "target", PadType.FIXED, 50));
rma.set(columns, schema, completeTarget);
final var unchangedCols = schema.getColumns();
assertEquals(1, unchangedCols.size());
assertEquals(completeTarget.get(0).getTargetHeader(), unchangedCols.get(0).getTargetHeader());
}
// Make sure unspecified headers is empty since this is a mapped schema so everything must be specified.
@Override
@Test
public void verifyGetUnspecifiedHeadersReturnValueTest() {
final MappedTableSchema schema = new MappedTableSchema(List.of(CS_S_1_TO_UNNAMED_FINGERPRINT, CS_S_1_TO_UNNAMED_SEALED));
assertNull(schema.getPositionalColumnHeaders());
}
// Verify missing a source header leads to failure but missing a target header does not.
@Override
@Test
public void verifyChildSpecificInvalidHeaderConstructionTest() {
final ColumnSchema invalid = ColumnSchema.builder().targetHeader(new ColumnHeader("target")).type(ColumnType.CLEARTEXT).build();
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> new MappedTableSchema(List.of(invalid)));
assertEquals("Source header is required.", e.getMessage());
final ColumnSchema needsTarget = ColumnSchema.builder().sourceHeader(new ColumnHeader("source")).type(ColumnType.FINGERPRINT)
.build();
final var schema = new MappedTableSchema(List.of(needsTarget));
final var columns = schema.getColumns();
assertEquals(1, columns.size());
final var column = columns.get(0);
assertEquals("source", column.getSourceHeader().toString());
assertEquals("source" + ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX, column.getTargetHeader().toString());
}
/*
* Confirm validate() checks the required properties of a mapped type:
* - headerRow is not null and is true
* - No unspecified source headers are present
*/
@Override
@Test
public void checkClassSpecificVerificationTest() throws NoSuchFieldException, IllegalAccessException {
final var schema = mock(MappedTableSchema.class);
final var rma = new ReflectionMemberAccessor();
final Field headerRow = TableSchema.class.getDeclaredField("headerRow");
doCallRealMethod().when(schema).validate();
rma.set(headerRow, schema, null);
final Exception e1 = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Mapped Table Schemas require a header row in the data.", e1.getMessage());
rma.set(headerRow, schema, false);
final Exception e2 = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Mapped Table Schemas require a header row in the data.", e2.getMessage());
rma.set(headerRow, schema, true);
when(schema.getPositionalColumnHeaders()).thenReturn(List.of(CS_S_1_TO_T_1.getSourceHeader()));
when(schema.getHeaderRowFlag()).thenReturn(true);
final Exception e3 = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Mapped schemas should not have any unspecified input headers.", e3.getMessage());
}
}
| 2,521 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/ColumnInsightTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ColumnInsightTest {
private ColumnInsight createTestSealedColumnInsight(final PadType type, final Integer length) {
return new ColumnInsight(
ColumnSchema.builder()
.pad(Pad.builder().length(length).type(type).build())
.sourceHeader(new ColumnHeader("source"))
.targetHeader(new ColumnHeader("target"))
.type(ColumnType.SEALED)
.build());
}
@Test
public void maxValueLengthInitToZero() {
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.MAX, 42);
assertEquals(columnInsight.getMaxValueLength(), 0);
}
@Test
public void updateWhenPadTypeMax() {
final var len9 = new CsvValue("012345678");
final var len10 = new CsvValue("0123456789");
final var len8 = new CsvValue("01234567");
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.MAX, 10);
columnInsight.observe(len9);
columnInsight.observe(len10);
columnInsight.observe(len8);
assertEquals(columnInsight.getMaxValueLength(), 10);
}
@Test
public void noUpdateWhenNotPadTypeMax() {
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.FIXED, 42);
columnInsight.observe(new CsvValue("0123456789"));
assertEquals(columnInsight.getMaxValueLength(), 0);
}
@Test
public void allowsUpdateWithSameType() {
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.NONE, null);
columnInsight.observe(new CsvValue("test"));
columnInsight.observe(new CsvValue((String) null));
}
@Test
public void noErrorsWhenValuesAreNull() {
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.NONE, null);
columnInsight.observe(new CsvValue((String) null));
columnInsight.observe(new CsvValue((String) null));
}
@Test
public void errorWhenDifferentTypesAreInColumn() {
final ColumnInsight columnInsight = createTestSealedColumnInsight(PadType.NONE, null);
columnInsight.observe(new CsvValue("test"));
final CsvValue nonStringCsv = mock(CsvValue.class);
when(nonStringCsv.getClientDataType()).thenReturn(ClientDataType.DATE);
assertThrowsExactly(C3rRuntimeException.class, () -> columnInsight.observe(nonStringCsv));
}
}
| 2,522 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/EncryptConfigTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.action.CsvRowMarshaller;
import com.amazonaws.c3r.action.RowMarshaller;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT;
import static com.amazonaws.c3r.utils.GeneralTestUtility.cleartextColumn;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class EncryptConfigTest {
private String tempDir;
private String output;
private EncryptConfig.EncryptConfigBuilder minimalConfigBuilder(final String sourceFile) {
return EncryptConfig.builder()
.secretKey(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getKey())
.sourceFile(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.sourceFile(sourceFile)
.targetFile(output)
.tempDir(tempDir)
.salt(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getSalt())
.settings(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getSettings())
.tableSchema(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getSchema());
}
// Helper function for calling row marshaller on settings.
private void runConfig(final EncryptConfig config) {
final RowMarshaller<CsvValue> rowMarshaller = CsvRowMarshaller.newInstance(config);
rowMarshaller.marshal();
rowMarshaller.close();
}
@BeforeEach
public void setup() throws IOException {
tempDir = FileTestUtility.createTempDir().toString();
output = FileTestUtility.resolve("output.csv").toString();
}
@Test
public void minimumViableConstructionTest() {
assertDoesNotThrow(() -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.build());
}
// Make sure input file must be specified.
@Test
public void validateInputBlankTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(
TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.sourceFile("").build());
}
@Test
public void validateOutputEmptyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.targetFile("").build());
}
@Test
public void validateNoOverwriteTest() throws IOException {
output = FileTestUtility.createTempFile("output", ".csv").toString();
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.overwrite(false).build());
}
@Test
public void validateOverwriteTest() throws IOException {
output = FileTestUtility.createTempFile("output", ".csv").toString();
assertDoesNotThrow(() -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.overwrite(true).build());
}
@Test
public void validateEmptySaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.salt("").build());
}
@Test
public void unknownFileExtensionTest() throws IOException {
final String pathWithUnknownExtension = FileTestUtility.createTempFile("input", ".unknown").toString();
// unknown extensions cause failure if no FileFormat is specified
assertThrowsExactly(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(pathWithUnknownExtension).build());
// specifying a FileFormat makes it work
assertDoesNotThrow(() ->
minimalConfigBuilder(pathWithUnknownExtension)
.fileFormat(FileFormat.CSV)
.build());
}
@Test
public void csvOptionsNonCsvFileFormatTest() throws IOException {
final String parquetPath = FileTestUtility.createTempFile("input", ".parquet").toString();
// parquet file is fine
assertDoesNotThrow(() ->
minimalConfigBuilder(parquetPath).build());
// parquet file with csvInputNullValue errors
assertThrowsExactly(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(parquetPath)
.csvInputNullValue("")
.build());
// parquet file with csvOutputNullValue errors
assertThrowsExactly(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(parquetPath)
.csvOutputNullValue("")
.build());
}
// Make sure positional schema and file that are equivalent to file and schema with headers.
@Test
public void noHeaderFileProducesCorrectResultsTest() throws IOException {
final String noHeadersFile = "../samples/csv/data_sample_no_headers.csv";
final TableSchema noHeadersSchema = new PositionalTableSchema(List.of(
List.of(cleartextColumn(null, "FirstName")),
List.of(cleartextColumn(null, "LastName")),
List.of(cleartextColumn(null, "Address")),
List.of(cleartextColumn(null, "City")),
List.of(cleartextColumn(null, "State")),
List.of(cleartextColumn(null, "PhoneNumber")),
List.of(cleartextColumn(null, "Title")),
List.of(cleartextColumn(null, "Level")),
List.of(cleartextColumn(null, "Notes"))
));
final String headersFile = "../samples/csv/data_sample_without_quotes.csv";
final TableSchema headersSchema = new MappedTableSchema(List.of(
cleartextColumn("FirstName"),
cleartextColumn("LastName"),
cleartextColumn("Address"),
cleartextColumn("City"),
cleartextColumn("State"),
cleartextColumn("PhoneNumber"),
cleartextColumn("Title"),
cleartextColumn("Level"),
cleartextColumn("Notes")
));
final EncryptConfig noHeadersConfig = EncryptConfig.builder()
.sourceFile(noHeadersFile)
.targetFile(FileTestUtility.createTempFile().toString())
.tempDir(tempDir)
.overwrite(true)
.csvInputNullValue(null)
.csvOutputNullValue(null)
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.tableSchema(noHeadersSchema)
.build();
runConfig(noHeadersConfig);
final EncryptConfig headersConfig = EncryptConfig.builder()
.sourceFile(headersFile)
.targetFile(FileTestUtility.createTempFile().toString())
.tempDir(tempDir)
.overwrite(true)
.csvInputNullValue(null)
.csvOutputNullValue(null)
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.tableSchema(headersSchema)
.build();
runConfig(headersConfig);
final List<String> noHeaderLines = Files.readAllLines(Path.of(noHeadersConfig.getTargetFile()));
final List<String> headerLines = Files.readAllLines(Path.of(headersConfig.getTargetFile()));
assertEquals(headerLines.size(), noHeaderLines.size());
noHeaderLines.sort(String::compareTo);
headerLines.sort(String::compareTo);
for (int i = 0; i < headerLines.size(); i++) {
assertEquals(0, headerLines.get(i).compareTo(noHeaderLines.get(i)));
}
}
// Make sure custom null values work with positional schemas.
@Test
public void customNullValueWithPositionalSchemaTest() throws IOException {
final String noHeadersFile = "../samples/csv/data_sample_no_headers.csv";
final TableSchema noHeadersSchema = new PositionalTableSchema(List.of(
List.of(cleartextColumn(null, "FirstName")),
List.of(cleartextColumn(null, "LastName")),
List.of(cleartextColumn(null, "Address")),
List.of(cleartextColumn(null, "City")),
List.of(cleartextColumn(null, "State")),
List.of(cleartextColumn(null, "PhoneNumber")),
List.of(cleartextColumn(null, "Title")),
List.of(cleartextColumn(null, "Level")),
List.of(cleartextColumn(null, "Notes"))
));
final EncryptConfig noHeadersConfig = EncryptConfig.builder()
.sourceFile(noHeadersFile)
.targetFile(output)
.tempDir(tempDir)
.overwrite(true)
.csvInputNullValue("John")
.csvOutputNullValue("NULLJOHNNULL")
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.tableSchema(noHeadersSchema)
.build();
runConfig(noHeadersConfig);
final List<String> noHeaderLines = Files.readAllLines(Path.of(noHeadersConfig.getTargetFile()));
boolean foundNull = false;
for (String row : noHeaderLines) {
foundNull |= row.startsWith("NULLJOHNNULL,Smith");
}
assertTrue(foundNull);
}
// Check that validation fails because cleartext columns aren't allowed but cleartext columns are in the schema.
@Test
void checkAllowCleartextValidationTest() {
final String noHeadersFile = "../samples/csv/data_sample_no_headers.csv";
final TableSchema schema = new MappedTableSchema(List.of(GeneralTestUtility.cleartextColumn("cleartext")));
final var config = EncryptConfig.builder()
.sourceFile(noHeadersFile)
.targetFile(output)
.tempDir(tempDir)
.overwrite(true)
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.tableSchema(schema);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> config.settings(ClientSettings.highAssuranceMode()).build());
assertEquals("Cleartext columns found in the schema, but allowCleartext is false. Target column names: [`cleartext`]",
e.getMessage());
assertDoesNotThrow(() -> config.settings(ClientSettings.lowAssuranceMode()).build());
}
} | 2,523 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/TableSchemaTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Limits;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.reflection.ReflectionMemberAccessor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
// Test class for implementation done in TableSchema using mocks to be independent of child implementations.
public class TableSchemaTest {
// Use to mock a TableSchema with specified column data and header status.
private TableSchema generateMockTableSchema(final Boolean hasHeaders, final List<ColumnSchema> columns)
throws NoSuchFieldException, IllegalAccessException {
final var tableSchema = mock(TableSchema.class);
final var rma = new ReflectionMemberAccessor();
final Field header = TableSchema.class.getDeclaredField("headerRow");
rma.set(header, tableSchema, hasHeaders);
when(tableSchema.getColumns()).thenReturn(columns);
doCallRealMethod().when(tableSchema).validate();
return tableSchema;
}
// Check that logic for when preprocessing is needed is correct.
@Test
public void mappedSchemaRequiresPreprocessingTest() {
final var tableSchema = mock(TableSchema.class);
doCallRealMethod().when(tableSchema).requiresPreprocessing();
final List<ColumnSchema> noPreProcessingSchemas = List.of(GeneralTestUtility.cleartextColumn("u1"));
when(tableSchema.getColumns()).thenReturn(noPreProcessingSchemas);
assertFalse(tableSchema.requiresPreprocessing());
final List<ColumnSchema> sealedRequiresPreProcessing = List.of(GeneralTestUtility.sealedColumn("s1"),
GeneralTestUtility.sealedColumn("s2", "t2", PadType.FIXED, 50));
when(tableSchema.getColumns()).thenReturn(sealedRequiresPreProcessing);
assertTrue(tableSchema.requiresPreprocessing());
final List<ColumnSchema> fingerprintRequiresPreProcessing = List.of(GeneralTestUtility.fingerprintColumn("j1"));
when(tableSchema.getColumns()).thenReturn(fingerprintRequiresPreProcessing);
assertTrue(tableSchema.requiresPreprocessing());
}
// Make sure the schema does not allow more than the maximum number of columns.
@Test
public void validateTooManyColumnsTest() {
// make a fake column list that says it's bigger than we allow
@SuppressWarnings("unchecked")
final ArrayList<ColumnSchema> fakeBigList = mock(ArrayList.class);
when(fakeBigList.isEmpty()).thenReturn(false);
when(fakeBigList.size()).thenReturn(Limits.ENCRYPTED_OUTPUT_COLUMN_COUNT_MAX);
// make a fake table schema with the fake column list
final var maxColumnCountSchema = mock(TableSchema.class);
when(maxColumnCountSchema.getColumns()).thenReturn(fakeBigList);
doCallRealMethod().when(maxColumnCountSchema).validate();
assertEquals(Limits.ENCRYPTED_OUTPUT_COLUMN_COUNT_MAX, maxColumnCountSchema.getColumns().size());
when(fakeBigList.size()).thenReturn(Limits.ENCRYPTED_OUTPUT_COLUMN_COUNT_MAX + 1);
assertThrows(C3rIllegalArgumentException.class, maxColumnCountSchema::validate);
}
// Tests that the source and header set collapses duplicates correctly.
@Test
public void validateGetSourceAndTargetHeadersTest() throws NoSuchFieldException, IllegalAccessException {
final List<ColumnSchema> columnSchemas = List.of(
GeneralTestUtility.cleartextColumn("s1", "t1"),
GeneralTestUtility.cleartextColumn("s1", "t2"),
GeneralTestUtility.cleartextColumn("s2", "t3")
);
final var tableSchema = generateMockTableSchema(false, columnSchemas);
doCallRealMethod().when(tableSchema).getSourceAndTargetHeaders();
final Set<ColumnHeader> knownValid = Set.of(
new ColumnHeader("s1"),
new ColumnHeader("s2"),
new ColumnHeader("t1"),
new ColumnHeader("t2"),
new ColumnHeader("t3")
);
final var results = tableSchema.getSourceAndTargetHeaders();
assertEquals(knownValid, results);
}
// Checks for the same target header being reused is rejected during validations.
@Test
public void checkDuplicateTargetsTest() throws NoSuchFieldException, IllegalAccessException {
final List<ColumnSchema> noDuplicates = List.of(
GeneralTestUtility.cleartextColumn("s1", "t1"),
GeneralTestUtility.cleartextColumn("s2", "t2")
);
final var tableSchema = generateMockTableSchema(true, noDuplicates);
assertDoesNotThrow(tableSchema::validate);
final List<ColumnSchema> duplicates1 = List.of(
GeneralTestUtility.cleartextColumn("s1", "t1"),
GeneralTestUtility.cleartextColumn("s2", "t2"),
GeneralTestUtility.cleartextColumn("s3", "t2")
);
final var tableSchemaDuplicates = generateMockTableSchema(true, duplicates1);
final Exception e1 = assertThrows(C3rIllegalArgumentException.class, tableSchemaDuplicates::validate);
assertEquals("Target header name can only be used once. Duplicates found: t2", e1.getMessage());
// Check that normalization happens prior to deduplication checks, i.e. that" T2 " counts as a duplicate
final List<ColumnSchema> duplicates2 = List.of(
GeneralTestUtility.cleartextColumn("s1", "t1"),
GeneralTestUtility.cleartextColumn("s2", "t2"),
GeneralTestUtility.cleartextColumn("s3", " T2 ")
);
final var tableSchemaDuplicates2 = generateMockTableSchema(true, duplicates2);
final Exception e2 = assertThrows(C3rIllegalArgumentException.class, tableSchemaDuplicates2::validate);
assertEquals("Target header name can only be used once. Duplicates found: t2", e2.getMessage());
}
// Test that a null value for the header and a null value for the columns causes construction to fail.
@Test
public void nullHeaderRowAndNullColumnsTest() throws NoSuchFieldException, IllegalAccessException {
final var tableSchema = generateMockTableSchema(null, null);
final Exception e = assertThrows(C3rIllegalArgumentException.class, tableSchema::validate);
assertEquals("Schema was not initialized.", e.getMessage());
}
// Test that if the header is null the schema won't be created.
@Test
public void nullHeaderRowTest() throws IllegalAccessException, NoSuchFieldException {
final var tableSchema = generateMockTableSchema(null, new ArrayList<>());
final Exception e = assertThrows(C3rIllegalArgumentException.class, tableSchema::validate);
assertEquals("Schema must specify whether or not data has a header row.", e.getMessage());
}
// Check that validation fails because no value was given for columns.
@Test
public void nullColumnsTest() throws NoSuchFieldException, IllegalAccessException {
final var tableSchema = generateMockTableSchema(false, null);
final Exception e = assertThrows(C3rIllegalArgumentException.class, tableSchema::validate);
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
// Check that validations fails because the column list is empty
@Test
public void emptyColumnsTest() throws NoSuchFieldException, IllegalAccessException {
final var tableSchema = generateMockTableSchema(true, new ArrayList<>());
final Exception e = assertThrows(C3rIllegalArgumentException.class, tableSchema::validate);
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
}
| 2,524 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/ConfigTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.FileUtil;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import static com.amazonaws.c3r.config.Config.getDefaultTargetFile;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ConfigTest {
@Test
public void defaultTargetFileWithExtensionTest() {
assertEquals("input.out.csv", getDefaultTargetFile("input.csv"));
assertEquals("input.misc.out.csv", getDefaultTargetFile("input.misc.csv"));
}
@Test
public void getDefaultTargetFileTest() throws IOException {
final Path sourceFile = FileTestUtility.resolve("sourceFile.csv");
final String defaultTargetFile = Config.getDefaultTargetFile(sourceFile.toFile().getAbsolutePath());
// assert sourceFile directory is stripped and targetFile is associated with the working directory.
final File targetFile = new File(defaultTargetFile);
assertNotNull(sourceFile.getParent());
assertNull(targetFile.getParentFile());
assertTrue(targetFile.getAbsolutePath().contains(FileUtil.CURRENT_DIR));
}
@Test
public void defaultTargetFileWithoutExtensionTest() {
assertEquals("input.out", getDefaultTargetFile("input"));
}
}
| 2,525 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/DecryptConfigTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.utils.FileTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class DecryptConfigTest {
private String output;
private DecryptConfig.DecryptConfigBuilder minimalConfigBuilder(final String sourceFile) {
return DecryptConfig.builder()
.secretKey(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getKey())
.sourceFile(sourceFile)
.targetFile(output)
.salt(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getSalt());
}
@BeforeEach
public void setup() throws IOException {
output = FileTestUtility.resolve("output.csv").toString();
}
@Test
public void minimumViableConstructionTest() {
assertDoesNotThrow(() -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput()).build());
}
@Test
public void validateInputEmptyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.sourceFile("").build());
}
@Test
public void validateOutputEmptyTest() {
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.targetFile("").build());
}
@Test
public void validateNoOverwriteTest() throws IOException {
output = FileTestUtility.createTempFile().toString();
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.overwrite(false).build());
}
@Test
public void validateOverwriteTest() throws IOException {
output = FileTestUtility.createTempFile().toString();
assertDoesNotThrow(() -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.overwrite(true).build());
}
@Test
public void validateEmptySaltTest() {
assertThrows(C3rIllegalArgumentException.class, () -> minimalConfigBuilder(TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT.getInput())
.salt("").build());
}
@Test
public void unknownFileExtensionTest() throws IOException {
final String pathWithUnknownExtension = FileTestUtility.createTempFile("input", ".unknown").toString();
// unknown extensions cause failure if no FileFormat is specified
assertThrows(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(pathWithUnknownExtension).build());
// specifying a FileFormat makes it work
assertDoesNotThrow(() ->
minimalConfigBuilder(pathWithUnknownExtension)
.fileFormat(FileFormat.CSV)
.build());
}
@Test
public void csvOptionsNonCsvFileFormatTest() throws IOException {
final String parquetPath = FileTestUtility.createTempFile("input", ".parquet").toString();
// parquet file is fine
assertDoesNotThrow(() ->
minimalConfigBuilder(parquetPath).build());
// parquet file with csvInputNullValue errors
assertThrows(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(parquetPath)
.csvInputNullValue("")
.build());
// parquet file with csvOutputNullValue errors
assertThrows(C3rIllegalArgumentException.class, () ->
minimalConfigBuilder(parquetPath)
.csvOutputNullValue("")
.build());
}
}
| 2,526 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/ColumnSchemaTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/*
* This test class is for maintaining the schema specification rules. This is why reflection is used to modify some values in tests.
* These tests care that the schema dealt correctly with unspecified values or unique parameter rules. We are concerned with throwing
* errors for missing required values, handling the few default value cases correctly and handling required unspecified values correctly.
* Defaults related to value normalization are checked as well as selecting control conditions based off of settings.
*/
public class ColumnSchemaTest {
// Canary information to ensure we catch changes to the schema
private static final int NUMBER_OF_COLUMN_SETTINGS = 5;
private static final int NUMBER_OF_PAD_TYPES = 3;
private static final int NUMBER_OF_COLUMN_TYPES = 3;
/*
* When creating a source column header programmatically, ensure leading and trailing white space is removed. If the remaining value
* is empty, the value should be rejected.
*/
@Test
public void whiteSpaceInSourceHeaderTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn(" "));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn("\n"));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn("\t \n"));
assertEquals(new ColumnHeader("test"), GeneralTestUtility.fingerprintColumn(" test \t").getSourceHeader());
}
/*
* When creating a target column header and the value is specified, the leading and trailing white space should be removed. If the
* result is empty, alert the user with an error as they may have intended to have a value. If there is a non-empty value, use that
* as the target column header name.
*/
@Test
public void whiteSpaceInTargetHeaderTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn("NA", " "));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn("NA", "\n"));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GeneralTestUtility.fingerprintColumn("NA", "\t \n"));
assertEquals(new ColumnHeader("test"), GeneralTestUtility.fingerprintColumn("NA", "\ntest").getTargetHeader());
}
// If a column is cleartext and cleartext, it should not require preprocessing.
@Test
public void requiresPreprocessingFalseTest() {
final ColumnSchema columnSchema = GeneralTestUtility.cleartextColumn("source");
assertFalse(columnSchema.requiresPreprocessing());
}
// If a column type is fingerprint, preprocessing should be required.
@Test
public void requiresPreprocessingAllowDuplicatesTest() {
final ColumnSchema columnSchema = GeneralTestUtility.fingerprintColumn("source");
assertTrue(columnSchema.requiresPreprocessing());
}
// If a column is encrypted then preprocessing is required.
@Test
public void requiresPreprocessingNotCleartextTest() {
final ColumnSchema columnSchema = GeneralTestUtility.sealedColumn("source");
assertTrue(columnSchema.requiresPreprocessing());
}
// If a column is encrypted and has a pad, preprocessing is required.
@Test
public void requiresPreprocessingWithPaddingTest() {
final ColumnSchema columnSchema = GeneralTestUtility.sealedColumn("source", "source", PadType.FIXED, 1);
assertTrue(columnSchema.requiresPreprocessing());
}
/*
* This test is a canary for the schema changing. If we change the configuration options in the future, we'll either be adding
* parameters or removing parameters. This test will alert us as a reminder to update the tests on schema configuration definition
* rules. We should see three versions explicitly declared. One is actually the Object() constructor here and isn't actually
* reachable, but it is detected as declared. Then we have the copy constructor and the declared constructor for ColumnSchema. The
* number of parameters for ColumnSchema should match the CURRENT_PARAMETER_COUNT declared as part of this class. That value changing
* should set off the canary that we need to update this class for the new schema rules.
*/
@Test
public void validateConstructorParameterCountsCanaryTest() {
final Class<?> colObj = ColumnSchema.class;
final Constructor<?>[] colCons = colObj.getDeclaredConstructors();
// Check to make sure we only have the expected constructors:
// Object() (though the empty constructor isn't accessible)
// ColumnSchema(ColumnSchema) copy constructor
for (Constructor<?> con : colCons) {
assert (con.getParameterCount() == 0 || con.getParameterCount() == 1 ||
con.getParameterCount() == NUMBER_OF_COLUMN_SETTINGS);
if (con.getParameterCount() == 0) {
assert con.isSynthetic();
} else if (con.getParameterCount() == 1) {
assertEquals("public com.amazonaws.c3r.config.ColumnSchema(com.amazonaws.c3r.config.ColumnSchema)", con.toString());
} else {
final String signature = "private com.amazonaws.c3r.config.ColumnSchema(com.amazonaws.c3r.config.ColumnHeader," +
"com.amazonaws.c3r.config.ColumnHeader,com.amazonaws.c3r.config.ColumnHeader,com.amazonaws.c3r.config.Pad," +
"com.amazonaws.c3r.config.ColumnType)";
assertEquals(signature, con.toString());
}
}
}
/*
* This test is a canary for the pad types changing. If we change the configuration options in the future, we'll either be adding,
* removing or renaming options. This test will alert us as a reminder to update the tests on schema configuration definition
* rules.
*/
@Test
public void validatePadTypeOptionsCanaryTest() {
assertEquals(NUMBER_OF_PAD_TYPES, PadType.values().length);
assertEquals(PadType.FIXED, PadType.valueOf("FIXED"));
assertEquals(PadType.MAX, PadType.valueOf("MAX"));
assertEquals(PadType.NONE, PadType.valueOf("NONE"));
}
/*
* This test is a canary for the column types changing. If we change the configuration options in the future, we'll either be adding,
* removing or renaming options. This test will alert us as a reminder to update the tests on schema configuration definition
* rules.
*/
@Test
public void validateColumnTypeOptionsCanaryTest() {
assertEquals(NUMBER_OF_COLUMN_TYPES, ColumnType.values().length);
assertEquals(ColumnType.FINGERPRINT, ColumnType.valueOf("FINGERPRINT"));
assertEquals(ColumnType.SEALED, ColumnType.valueOf("SEALED"));
assertEquals(ColumnType.CLEARTEXT, ColumnType.valueOf("CLEARTEXT"));
}
// This test verifies that the copy constructor does not propagate bad state data for when the SDK is made public.
@Test
public void verifyCopyConstructorFailsOnBadSchemaTest() {
// Use reflection to make an invalid Column without a source name
final ColumnSchema c = GeneralTestUtility.cleartextColumn("s", "t");
// Check bad pad is not propagated
try {
final Field targetField = c.getClass().getDeclaredField("targetHeader");
targetField.setAccessible(true);
targetField.set(c, new ColumnHeader("t"));
final Pad p = Pad.builder().type(PadType.MAX).length(100).build();
final Field padLen = p.getClass().getDeclaredField("length");
padLen.setAccessible(true);
padLen.set(p, -100);
final Field pad = c.getClass().getDeclaredField("pad");
pad.setAccessible(true);
pad.set(c, p);
} catch (NoSuchFieldException | SecurityException | IllegalAccessException e) {
fail("Error mutating target column header or pad using reflection");
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> new ColumnSchema(c));
// Check that bad pad/type combo is not propagated
try {
final Field pad = c.getClass().getDeclaredField("pad");
pad.setAccessible(true);
pad.set(c, Pad.builder().type(PadType.MAX).length(100).build());
} catch (NoSuchFieldException | SecurityException | IllegalAccessException e) {
fail("Error mutating pad using reflection");
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> new ColumnSchema(c));
}
@Test
public void padTypeNoneCannotHaveNonZeroLengthTest() {
// Test that Pad type none does not accept a length
assertThrowsExactly(C3rIllegalArgumentException.class, () -> Pad.builder().type(PadType.NONE).length(32).build());
}
@Test
public void padLengthCannotBeOutOfRangeTest() {
// Assert that out of range values are not accepted
assertThrowsExactly(C3rIllegalArgumentException.class, () -> Pad.builder().type(PadType.MAX).length(-10).build());
assertThrowsExactly(C3rIllegalArgumentException.class, () -> Pad.builder().type(PadType.MAX).length(17000).build());
assertThrowsExactly(C3rIllegalArgumentException.class, () -> Pad.builder().type(PadType.FIXED).length(-10).build());
assertThrowsExactly(C3rIllegalArgumentException.class, () -> Pad.builder().type(PadType.FIXED).length(17000).build());
}
@Test
public void columnMissingTypeFailTest() {
// Test that Pad type none does not accept a length
assertThrowsExactly(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder()
.sourceHeader(new ColumnHeader("source"))
.targetHeader(new ColumnHeader("target"))
.type(null)
.build());
}
@Test
public void columnMissingPadFailTest() {
// Test that Pad type none does not accept a length
assertThrowsExactly(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder()
.sourceHeader(new ColumnHeader("source"))
.targetHeader(new ColumnHeader("target"))
.type(ColumnType.SEALED)
.pad(null)
.build());
}
@Test
public void columnTypeToStringTest() {
assertEquals("fingerprint", ColumnType.FINGERPRINT.toString());
assertEquals("sealed", ColumnType.SEALED.toString());
assertEquals("cleartext", ColumnType.CLEARTEXT.toString());
}
}
| 2,527 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/PositionalTableSchemaTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.action.CsvRowMarshaller;
import com.amazonaws.c3r.action.RowMarshaller;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.CsvTestUtility;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.internal.util.reflection.ReflectionMemberAccessor;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.mock;
public class PositionalTableSchemaTest implements TableSchemaCommonTestInterface {
private static final ColumnSchema CS_1 = GeneralTestUtility.cleartextColumn(null, "t1");
private static final ColumnSchema CS_2 = GeneralTestUtility.fingerprintColumn(null, "t2");
private static final ColumnSchema CS_2_DUPLICATE_TARGET = GeneralTestUtility.fingerprintColumn(null, "t2");
private static final ColumnSchema CS_3 = GeneralTestUtility.sealedColumn(null, "t3", PadType.NONE, null);
private static final ColumnSchema CS_4 = GeneralTestUtility.sealedColumn(null, "t4", PadType.FIXED, 50);
private static final ColumnSchema CS_5 = GeneralTestUtility.sealedColumn(null, "t5", PadType.MAX, 100);
private String tempDir;
private String output;
@BeforeEach
public void setup() throws IOException {
tempDir = FileTestUtility.createTempDir().toString();
output = FileTestUtility.resolve("output.csv").toString();
}
/*
* Add an extra column row to a known valid schema and make sure it's not accepted because it doesn't have the same number
* of columns as the csv file. Easiest to run through the CLI since we need the CSV parser for verification.
*/
@Test
public void tooManyRowsPositionalSchemaTest() throws IOException {
final Path csvFile = FileTestUtility.resolve("tooManyRows.csv");
Files.writeString(csvFile, "1,2,3\n4,5,6");
final var schema = new PositionalTableSchema(List.of(
List.of(GeneralTestUtility.cleartextColumn(null, "t1")),
List.of(GeneralTestUtility.cleartextColumn(null, "t2")),
List.of(GeneralTestUtility.cleartextColumn(null, "t3")),
List.of(GeneralTestUtility.cleartextColumn(null, "t4"))
));
final EncryptConfig config = EncryptConfig.builder()
.secretKey(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile(csvFile.toString())
.targetFile(output)
.tempDir(tempDir)
.salt("1234")
.settings(ClientSettings.lowAssuranceMode())
.tableSchema(schema)
.overwrite(true)
.build();
final Exception e = assertThrowsExactly(C3rRuntimeException.class, () -> CsvRowMarshaller.newInstance(config));
assertEquals("Positional table schemas must match the same number of columns as the data. Expected: 4, found: 3.", e.getMessage());
}
/*
* Remove a column row to a known valid schema and make sure it's not accepted because it doesn't have the same number
* of columns as the csv file. Easiest to run through the CLI since we need the CSV parser for verification.
*/
@Test
public void tooFewRowsPositionalSchemaTest() throws IOException {
final Path csvFile = FileTestUtility.resolve("tooManyRows.csv");
Files.writeString(csvFile, "1,2,3\n4,5,6");
final var schema = new PositionalTableSchema(List.of(
List.of(GeneralTestUtility.cleartextColumn(null, "t1")),
List.of(GeneralTestUtility.cleartextColumn(null, "t2"))
));
final EncryptConfig config = EncryptConfig.builder()
.secretKey(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile(csvFile.toString())
.targetFile(output)
.tempDir(tempDir)
.salt("1234")
.settings(ClientSettings.lowAssuranceMode())
.tableSchema(schema)
.overwrite(true)
.build();
final Exception e = assertThrowsExactly(C3rRuntimeException.class, () -> CsvRowMarshaller.newInstance(config));
assertEquals("Positional table schemas must match the same number of columns as the data. Expected: 2, found: 3.", e.getMessage());
}
// Verify that headers are correctly autogenerated as needed.
@Override
@Test
public void verifyAutomaticHeaderConstructionTest() {
final List<ColumnHeader> knownGoodHeaders = List.of(
ColumnHeader.of(0),
ColumnHeader.of(1),
ColumnHeader.of(2),
ColumnHeader.of(3),
ColumnHeader.of(4),
ColumnHeader.of(5)
);
final List<ColumnHeader> knownGoodHeadersInUse = List.of(
ColumnHeader.of(1),
ColumnHeader.of(2),
ColumnHeader.of(4),
ColumnHeader.of(5)
);
final List<List<ColumnSchema>> positionalColumns = List.of(
new ArrayList<>(),
List.of(CS_1),
List.of(CS_2, CS_3),
new ArrayList<>(),
List.of(CS_4),
List.of(CS_5)
);
final PositionalTableSchema schema = new PositionalTableSchema(positionalColumns);
assertEquals(knownGoodHeaders, schema.getPositionalColumnHeaders());
assertEquals(knownGoodHeadersInUse,
schema.getColumns().stream().map(ColumnSchema::getSourceHeader).distinct().collect(Collectors.toList()));
}
// Verify one source column can be mapped to multiple output columns as long as they have unique target header names.
@Override
@Test
public void oneSourceToManyTargetsTest() {
final ColumnHeader knownGoodHeader = ColumnHeader.of(0);
final PositionalTableSchema schema = new PositionalTableSchema(
List.of(
List.of(CS_1, CS_2, CS_3, CS_4, CS_5)
)
);
for (ColumnSchema c : schema.getColumns()) {
assertEquals(knownGoodHeader, c.getSourceHeader());
}
}
// Verify that is the same target header name is used more than once in a schema, it fails validation.
@Override
@Test
public void repeatedTargetFailsTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> new PositionalTableSchema(List.of(List.of(CS_2, CS_2_DUPLICATE_TARGET))));
assertEquals("Target header name can only be used once. Duplicates found: " + CS_2.getTargetHeader().toString(), e.getMessage());
}
// Validate that the column is null the schema is not accepted.
@Override
@Test
public void validateNullColumnValueIsRejectedTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> new PositionalTableSchema(null));
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
// Validate that if the output column list is empty, the schema is not accepted.
@Override
@Test
public void validateEmptyColumnValueIsRejectedTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> new PositionalTableSchema(List.of(List.of(),
List.of())));
assertEquals("At least one data column must provided in the config file.", e.getMessage());
}
// Test the implementation of equals and hash to make sure results are as expected.
@Override
@Test
public void equalsAndHashTest() {
final PositionalTableSchema p1 = new PositionalTableSchema(List.of(
List.of(CS_1, CS_2),
List.of(CS_3, CS_4),
List.of(CS_5)
));
final PositionalTableSchema p2 = new PositionalTableSchema(List.of(
List.of(CS_1, CS_2),
List.of(CS_3, CS_4),
List.of(CS_5)
));
final PositionalTableSchema p3 = new PositionalTableSchema(List.of(
List.of(CS_1, CS_2),
List.of(CS_3, CS_4),
List.of(CS_5),
List.of()
));
final PositionalTableSchema p4 = new PositionalTableSchema(List.of(
List.of(CS_1, CS_2),
List.of(),
List.of(CS_3, CS_4),
List.of(CS_5)
));
final PositionalTableSchema p5 = new PositionalTableSchema(List.of(
List.of(CS_1),
List.of(CS_3),
List.of(CS_5)
));
final TableSchema m = new MappedTableSchema(List.of(GeneralTestUtility.cleartextColumn("Column 1", "t1")));
final TableSchema pM = new PositionalTableSchema(List.of(List.of(CS_1)));
assertEquals(p1, p2);
assertEquals(p1.hashCode(), p2.hashCode());
assertEquals(p1, p3);
assertEquals(p1.hashCode(), p3.hashCode());
assertNotEquals(p3, p4);
assertNotEquals(p3.hashCode(), p4.hashCode());
assertNotEquals(p1, p5);
assertNotEquals(p1.hashCode(), p5.hashCode());
assertNotEquals(m, pM);
assertNotEquals(m.hashCode(), pM.hashCode());
}
// Verify the header row can't be the wrong value and the schema will still work.
@Override
@Test
public void verifyHeaderRowValueTest() {
final PositionalTableSchema schema = new PositionalTableSchema(List.of(List.of(CS_1, CS_2)));
schema.setHeaderRowFlag(true);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Positional Table Schemas cannot use data containing a header row", e.getMessage());
}
// Check the results from {@code getColumns()} matches the ones used in the schema and not the ones in the file.
@Override
@Test
public void verifyColumnsInResultsTest() {
final Set<String> knownGoodHeaders = Set.of("t1", "t2", "t3", "t4", "t5");
final var knownGoodValues = CsvTestUtility.readContentAsArrays("../samples/csv/data_sample_no_headers.csv", true);
final PositionalTableSchema schema = new PositionalTableSchema(List.of(
List.of(GeneralTestUtility.cleartextColumn(null, "t1")),
List.of(),
List.of(GeneralTestUtility.cleartextColumn(null, "t2"), GeneralTestUtility.cleartextColumn(null, "t3")),
List.of(),
List.of(),
List.of(GeneralTestUtility.cleartextColumn(null, "t4")),
List.of(),
List.of(),
List.of(GeneralTestUtility.cleartextColumn(null, "t5"))
));
final EncryptConfig config = EncryptConfig.builder()
.secretKey(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile("../samples/csv/data_sample_no_headers.csv")
.targetFile(output)
.tempDir(tempDir)
.salt(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE.getSettings())
.tableSchema(schema)
.overwrite(true)
.build();
final RowMarshaller<CsvValue> rowMarshaller = CsvRowMarshaller.newInstance(config);
rowMarshaller.marshal();
rowMarshaller.close();
final List<Map<String, String>> results = CsvTestUtility.readRows(output);
final Map<String, Map<String, String>> lookupMap = new HashMap<>();
for (var row : results) {
lookupMap.put(row.get("t1"), row);
}
assertEquals(knownGoodValues.size(), lookupMap.size());
for (String[] knownGoodRow : knownGoodValues) {
final Map<String, String> r = lookupMap.get(knownGoodRow[0]);
assertEquals(5, r.size());
assertEquals(knownGoodHeaders, r.keySet());
assertEquals(knownGoodRow[0], r.get("t1"));
assertEquals(knownGoodRow[2], r.get("t2"));
assertEquals(knownGoodRow[2], r.get("t3"));
assertEquals(knownGoodRow[5], r.get("t4"));
assertEquals(knownGoodRow[8], r.get("t5"));
}
}
// Check that getColumns() returns properly validated columns.
@Override
@Test
public void verifyGetColumnsTest() throws IllegalAccessException, NoSuchFieldException {
final var schema = mock(PositionalTableSchema.class);
doCallRealMethod().when(schema).getColumns();
final var rma = new ReflectionMemberAccessor();
final Field mappedColumns = PositionalTableSchema.class.getDeclaredField("mappedColumns");
rma.set(mappedColumns, schema, null);
final Field columns = PositionalTableSchema.class.getDeclaredField("columns");
final List<List<ColumnSchema>> emptyColumn = List.of(List.of(), List.of(GeneralTestUtility.cleartextColumn(null, "target")));
rma.set(columns, schema, emptyColumn);
final var skippedEmpty = schema.getColumns();
assertEquals(1, skippedEmpty.size());
assertNull(emptyColumn.get(1).get(0).getSourceHeader());
assertEquals(ColumnHeader.of(1), skippedEmpty.get(0).getSourceHeader());
}
// Make sure the various states of unspecified headers are correct for the child implementation.
@Override
@Test
public void verifyGetUnspecifiedHeadersReturnValueTest() throws IllegalAccessException, NoSuchFieldException {
final List<ColumnHeader> knownGoodColumns = List.of(
ColumnHeader.of(0),
ColumnHeader.of(1),
ColumnHeader.of(2)
);
final var schema = mock(PositionalTableSchema.class);
doCallRealMethod().when(schema).getPositionalColumnHeaders();
doCallRealMethod().when(schema).validate();
final var rma = new ReflectionMemberAccessor();
final Field headers = PositionalTableSchema.class.getDeclaredField("sourceHeaders");
rma.set(headers, schema, null);
final Field columns = PositionalTableSchema.class.getDeclaredField("columns");
final List<List<ColumnSchema>> columnsWithSkippedFields = List.of(List.of(CS_1), List.of(), List.of(CS_2));
rma.set(columns, schema, columnsWithSkippedFields);
assertEquals(knownGoodColumns, schema.getPositionalColumnHeaders());
}
// Make sure child implementation rejects all invalid headers for its type.
@Override
@Test
public void verifyChildSpecificInvalidHeaderConstructionTest() {
final ColumnSchema hasSourceHeader = GeneralTestUtility.cleartextColumn("source");
final Exception e1 = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> new PositionalTableSchema(List.of(List.of(hasSourceHeader))));
assertEquals("Positional table schemas cannot have `sourceHeader` properties in column schema, but found one in column 1.",
e1.getMessage());
final ColumnSchema noTargetHeader = GeneralTestUtility.cleartextColumn(null, null);
final Exception e2 = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> new PositionalTableSchema(List.of(List.of(noTargetHeader))));
assertEquals("Positional table schemas must have a target header name for each column schema. Missing target header in column 1.",
e2.getMessage());
}
// Check the child specific {@code verification} function to be sure it works as expected.
@Override
@Test
public void checkClassSpecificVerificationTest() {
final PositionalTableSchema schema = new PositionalTableSchema(List.of(List.of(CS_1)));
schema.setHeaderRowFlag(true);
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, schema::validate);
assertEquals("Positional Table Schemas cannot use data containing a header row", e.getMessage());
}
@Test
public void positionalSourceHeadersTest() {
assertTrue(PositionalTableSchema.generatePositionalSourceHeaders(0).isEmpty());
assertEquals(
List.of(ColumnHeader.of(0), ColumnHeader.of(1)),
PositionalTableSchema.generatePositionalSourceHeaders(2));
}
}
| 2,528 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/config/ColumnHeaderTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Limits;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ColumnHeaderTest {
@Test
public void checkNullValueToConstructorTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new ColumnHeader(null));
}
@Test
public void ofRawErrorsOnNullTest() {
assertThrows(C3rIllegalArgumentException.class, () -> ColumnHeader.ofRaw(null));
}
@Test
public void checkEmptyStringToConstructorTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new ColumnHeader(""));
}
@Test
public void checkBlankStringToConstructorTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new ColumnHeader("\n \t "));
}
private static void assertMatchesPattern(final Pattern pattern, final String value) {
assertTrue(pattern.matcher(value).matches(), "Pattern " + pattern.pattern() + " matches " + value);
}
private static void assertNotMatchesPattern(final Pattern pattern, final String value) {
assertFalse(pattern.matcher(value).matches(), "Pattern " + pattern.pattern() + " does not match " + value);
}
/*
* Verify normalization of headers along with equality and hashing.
* - White space is trimmed
* - Header is all lowercase
*/
@Test
public void checkRegexpAllowedNames() {
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, " ");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "A");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, " a");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a-");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a-b");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a_b-");
assertNotMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "\tThIs iS a WEIrD StrING \n");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "0");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "_");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "ab");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a ");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a_");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a_b");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "ab-b");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "a_b ");
assertMatchesPattern(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP, "this is a weird string");
}
/*
* Verify normalization of headers along with equality and hashing.
* - White space is trimmed
* - Header is all lowercase
*/
@Test
public void checkMixedCaseStringTest() {
final String str = "\tThIs iS a WEIrD StrING \n";
final String expected = "this is a weird string";
final ColumnHeader ch = new ColumnHeader(str);
final ColumnHeader chExpected = new ColumnHeader(expected);
final ColumnHeader notMatch = new ColumnHeader("test");
assertNotNull(ch);
assertEquals(chExpected, ch);
assertNotEquals(notMatch, ch);
assertEquals(expected, ch.toString());
assertNotEquals(notMatch.toString(), ch.toString());
assertEquals(chExpected.hashCode(), ch.hashCode());
assertNotEquals(notMatch.hashCode(), ch.hashCode());
}
@Test
public void noNormalizationToStringTest() {
final String rawString = "ThIs iS a WEIrD StrING ";
final ColumnHeader rawHeader = ColumnHeader.ofRaw(rawString);
assertEquals(rawString, rawHeader.toString());
}
@Test
public void maxLengthTest() {
assertDoesNotThrow(
() -> new ColumnHeader("a".repeat(Limits.AWS_CLEAN_ROOMS_HEADER_MAX_LENGTH)));
assertThrows(
C3rIllegalArgumentException.class,
() -> new ColumnHeader("a".repeat(Limits.AWS_CLEAN_ROOMS_HEADER_MAX_LENGTH + 1)));
}
@Test
public void invalidHeaderNameTest() {
assertFalse(Limits.AWS_CLEAN_ROOMS_HEADER_REGEXP.matcher("Multi Line\n Header").matches());
assertThrows(
C3rIllegalArgumentException.class,
() -> new ColumnHeader("Multi Line\n Header"));
}
// Check that we generate the expected valid and invalid results when creating a header from index.
@Test
public void columnHeaderFromIndexTest() {
assertEquals(new ColumnHeader("_c0"), ColumnHeader.of(0));
assertThrows(C3rIllegalArgumentException.class, () -> ColumnHeader.of(-10));
}
// Make sure we check all cases of configuring potentially unnamed target headers and verify output.
@Test
public void deriveTargetColumnHeaderTest() {
final ColumnHeader source = new ColumnHeader("source");
final ColumnHeader target = new ColumnHeader("target");
final ArrayList<ArrayList<ColumnHeader>> cases = new ArrayList<>() {
{
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, target, ColumnType.CLEARTEXT));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, target, ColumnType.FINGERPRINT));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, target, ColumnType.SEALED));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, target, null));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, null, ColumnType.CLEARTEXT));
add(source);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, null, ColumnType.FINGERPRINT));
add(new ColumnHeader(source + ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX));
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, null, ColumnType.SEALED));
add(new ColumnHeader(source + ColumnHeader.DEFAULT_SEALED_SUFFIX));
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(source, null, null));
add(null);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(null, target, ColumnType.CLEARTEXT));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(null, target, ColumnType.FINGERPRINT));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(null, target, ColumnType.SEALED));
add(target);
}
});
add(new ArrayList<>() {
{
add(ColumnHeader.deriveTargetColumnHeader(null, target, null));
add(target);
}
});
}
};
for (int i = 0; i < cases.size(); i++) {
final List<ColumnHeader> pair = cases.get(i);
assertEquals(2, pair.size());
assertEquals(pair.get(0), pair.get(1), "On case index " + i + " value calculated " + pair.get(0) + " does not match " +
pair.get(1) + ".");
}
}
}
| 2,529 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/SqlRowWriterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnInsight;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.data.CsvRow;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.Row;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.sql.SqlTable;
import com.amazonaws.c3r.io.sql.TableGenerator;
import com.amazonaws.c3r.utils.FileUtil;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SqlRowWriterTest {
private static final ColumnHeader NONCE_HEADER_DEFAULT = new ColumnHeader("c3r_nonce");
private final CsvRow row1 = GeneralTestUtility.csvRow(
NONCE_HEADER_DEFAULT.toString(), "nonce",
"firstname", "Ada",
"lastname", "Lovelace",
"address", "Ada's house",
"city", "London",
"state", "England",
"phonenumber", "123-456-7890",
"title", "Computing Pioneer",
"level", "Countess",
"notes", "MIL-STD-1815"
);
private List<ColumnInsight> columnInsights;
private Map<ColumnHeader, Integer> columnStatementPositions;
private Map<ColumnHeader, ColumnHeader> internalToTargetColumnHeaders;
private TableSchema tableSchema;
private SqlTable sqlTable;
@BeforeEach
public void setup() {
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(GeneralTestUtility.sealedColumn("firstname", "firstname", PadType.FIXED, 100));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("lastname", "lastname"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("address", "address"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("city", "city"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("state", "state"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("phonenumber", "phonenumber"));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("title", "title"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("level", "level"));
columnSchemas.add(GeneralTestUtility.sealedColumn("notes", "notes", PadType.MAX, 100));
columnInsights = columnSchemas.stream().map(ColumnInsight::new).collect(Collectors.toList());
columnStatementPositions = new HashMap<>();
for (int i = 0; i < columnInsights.size(); i++) {
columnStatementPositions.put(columnInsights.get(i).getInternalHeader(), i + 1);
}
columnStatementPositions.put(NONCE_HEADER_DEFAULT, columnInsights.size() + 1);
tableSchema = new MappedTableSchema(columnSchemas);
sqlTable = null;
internalToTargetColumnHeaders = columnInsights.stream()
.collect(Collectors.toMap(ColumnSchema::getTargetHeader, ColumnSchema::getInternalHeader));
internalToTargetColumnHeaders.put(NONCE_HEADER_DEFAULT, NONCE_HEADER_DEFAULT);
}
private void initTable() {
sqlTable = TableGenerator.initTable(tableSchema, NONCE_HEADER_DEFAULT, FileUtil.CURRENT_DIR);
}
@Test
public void getHeaderTest() {
initTable();
final SqlRowWriter<CsvValue> sqlRecordWriter = new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable);
assertEquals(new HashSet<>(sqlRecordWriter.getHeaders()), columnStatementPositions.keySet());
}
@Test
public void getInsertStatementSqlTest() throws SQLException {
initTable();
final Statement statement = mock(Statement.class);
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenAnswer((Answer<String>) invocation -> {
final Object[] args = invocation.getArguments();
return "\"" + args[0] + "\""; // enquote the column names
});
final String insertStatement = SqlRowWriter.getInsertStatementSql(statement, columnStatementPositions);
final StringBuilder expectedInsertStatement = new StringBuilder("INSERT INTO ").append(TableGenerator.DEFAULT_TABLE_NAME)
.append(" (");
for (ColumnInsight column : columnInsights) {
expectedInsertStatement.append("\"").append(column.getInternalHeader()).append("\",");
}
expectedInsertStatement.append("\"").append(NONCE_HEADER_DEFAULT).append("\")\nVALUES (?,?,?,?,?,?,?,?,?,?)");
assertEquals(expectedInsertStatement.toString(), insertStatement);
}
@Test
public void getInsertStatementSqlSqlExceptionTest() throws SQLException {
initTable();
final Statement statement = mock(Statement.class);
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenThrow(SQLException.class);
assertThrows(C3rRuntimeException.class, () -> SqlRowWriter.getInsertStatementSql(statement, columnStatementPositions));
}
@Test
public void initInsertStatementSqlExceptionTest() throws SQLException {
initTable();
sqlTable = mock(SqlTable.class);
final Connection connection = mock(Connection.class);
when(sqlTable.getConnection()).thenReturn(connection);
when(connection.createStatement()).thenThrow(SQLException.class);
assertThrows(C3rRuntimeException.class, () -> new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable));
}
@Test
public void closeDoesNotCloseConnectionTest() throws SQLException {
initTable();
final SqlRowWriter<CsvValue> sqlRecordWriter = new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable);
assertFalse(sqlTable.getConnection().isClosed());
sqlRecordWriter.close();
assertFalse(sqlTable.getConnection().isClosed());
}
@Test
public void writeRowTest() throws SQLException {
initTable();
final SqlRowWriter<CsvValue> sqlRecordWriter = new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable);
sqlRecordWriter.writeRow(row1);
final String selectSql = "SELECT * FROM " + TableGenerator.DEFAULT_TABLE_NAME;
try (Statement statement = sqlTable.getConnection().createStatement()) {
final ResultSet rs = statement.executeQuery(selectSql);
for (var column : row1.getHeaders()) {
assertArrayEquals(row1.getValue(column).getBytes(), rs.getBytes(internalToTargetColumnHeaders.get(column).toString()));
}
}
}
@Test
public void writeRowNullValuesTest() throws SQLException {
initTable();
// clone row1, modify some entries to be blank
final Row<CsvValue> row = new CsvRow(row1);
row.putValue(new ColumnHeader("address"), new CsvValue((String) null));
row.putValue(new ColumnHeader("notes"), new CsvValue((String) null));
final SqlRowWriter<CsvValue> sqlRecordWriter = new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable);
sqlRecordWriter.writeRow(row);
final String selectSql = "SELECT * FROM " + TableGenerator.DEFAULT_TABLE_NAME;
try (Statement statement = sqlTable.getConnection().createStatement()) {
final ResultSet rs = statement.executeQuery(selectSql);
for (var column : row.getHeaders()) {
assertArrayEquals(row.getValue(column).getBytes(), rs.getBytes(internalToTargetColumnHeaders.get(column).toString()));
}
// These two columns were omitted from the insert and should be null.
assertNull(rs.getString(internalToTargetColumnHeaders.get(new ColumnHeader("address")).toString()));
assertNull(rs.getString(internalToTargetColumnHeaders.get(new ColumnHeader("notes")).toString()));
}
}
@Test
public void getSourceNameTest() throws SQLException {
sqlTable = mock(SqlTable.class);
final Connection connection = mock(Connection.class);
when(sqlTable.getConnection()).thenReturn(connection);
when(connection.getCatalog()).thenReturn("the_database");
when(connection.createStatement()).thenReturn(mock(Statement.class));
final SqlRowWriter<CsvValue> sqlRecordWriter = new SqlRowWriter<>(columnInsights, NONCE_HEADER_DEFAULT, sqlTable);
assertEquals(
connection.getCatalog(),
sqlRecordWriter.getTargetName());
}
}
| 2,530 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/RowReaderTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.data.CsvRow;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.Limits;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RowReaderTest {
@Test
public void setTooManyRecordsInATableTest() {
@SuppressWarnings("unchecked")
final RowReader<CsvValue> reader = mock(RowReader.class, Mockito.CALLS_REAL_METHODS);
when(reader.peekNextRow()).thenReturn(new CsvRow());
assertThrows(C3rRuntimeException.class, () -> reader.setReadRowCount(Limits.ROW_COUNT_MAX + 1));
}
@Test
public void readTooManyRecordsInATableTest() {
@SuppressWarnings("unchecked")
final RowReader<CsvValue> reader = mock(RowReader.class, Mockito.CALLS_REAL_METHODS);
when(reader.peekNextRow()).thenReturn(new CsvRow());
reader.setReadRowCount(Limits.ROW_COUNT_MAX);
assertThrows(C3rRuntimeException.class, reader::next);
}
}
| 2,531 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/FileFormatTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class FileFormatTest {
@Test
public void fromFileNameCsvTest() {
assertEquals(FileFormat.CSV, FileFormat.fromFileName("hello.csv"));
}
@Test
public void fromFileNameParquetTest() {
assertEquals(FileFormat.PARQUET, FileFormat.fromFileName("hello.parquet"));
}
@Test
public void fromFileNameUnknownTest() {
assertNull(FileFormat.fromFileName("hello.unknown"));
}
@Test
public void fromFileNameEmptyTest() {
assertNull(FileFormat.fromFileName(""));
}
@Test
public void fromFileNameNoSuffixTest() {
assertNull(FileFormat.fromFileName("hello"));
}
}
| 2,532 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/SqlRowReaderTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnInsight;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.data.CsvRowFactory;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.Row;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.sql.SqlTable;
import com.amazonaws.c3r.io.sql.TableGenerator;
import com.amazonaws.c3r.utils.FileUtil;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class SqlRowReaderTest {
private static final ColumnHeader NONCE_HEADER_DEFAULT = new ColumnHeader("c3r_nonce");
private List<ColumnInsight> columnInsights;
private List<ColumnHeader> columnNames;
private SqlTable sqlTable;
@BeforeEach
public void setup() {
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(GeneralTestUtility.sealedColumn("firstname", "firstname", PadType.FIXED, 100));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("lastname", "lastname"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("address", "address"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("city", "city"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("state", "state"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("phonenumber", "phonenumber"));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("title", "title"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("level", "level"));
columnSchemas.add(GeneralTestUtility.sealedColumn("notes", "notes", PadType.MAX, 100));
columnInsights = columnSchemas.stream().map(ColumnInsight::new).collect(Collectors.toList());
columnNames = columnInsights.stream().map(ColumnSchema::getTargetHeader).collect(Collectors.toList());
final TableSchema tableSchema = new MappedTableSchema(columnSchemas);
sqlTable = TableGenerator.initTable(tableSchema, NONCE_HEADER_DEFAULT, FileUtil.CURRENT_DIR);
}
@Test
public void getHeadersTest() {
final SqlRowReader<CsvValue> sqlRowReader = new SqlRowReader<>(
columnInsights,
NONCE_HEADER_DEFAULT,
mock(CsvRowFactory.class),
sqlTable);
assertEquals(
sqlRowReader.getHeaders(),
columnInsights.stream().map(ColumnSchema::getInternalHeader).collect(Collectors.toList()));
}
@Test
public void getSourceNameTest() throws SQLException {
final SqlRowReader<CsvValue> sqlRowReader = new SqlRowReader<>(
columnInsights,
NONCE_HEADER_DEFAULT,
mock(CsvRowFactory.class),
sqlTable);
assertEquals(
sqlTable.getConnection().getCatalog(),
sqlRowReader.getSourceName());
}
@Test
public void getInsertStatementSqlTest() throws SQLException {
final Statement statement = mock(Statement.class);
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenAnswer((Answer<String>) invocation -> {
final Object[] args = invocation.getArguments();
return "\"" + args[0] + "\""; // enquote the column names
});
final String insertStatement = SqlRowReader.getSelectStatementSql(statement, columnNames, NONCE_HEADER_DEFAULT);
final String expectedInsertStatement = "SELECT \"firstname\",\"lastname\",\"address\",\"city\",\"state\",\"phonenumber\""
+ ",\"title\",\"level\",\"notes\",\"" + NONCE_HEADER_DEFAULT + "\" FROM " + TableGenerator.DEFAULT_TABLE_NAME
+ " ORDER BY \"" + NONCE_HEADER_DEFAULT + "\"";
assertEquals(expectedInsertStatement, insertStatement);
}
@Test
public void getInsertStatementSqlSqlExceptionTest() throws SQLException {
try (Statement statement = mock(Statement.class)) {
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenThrow(SQLException.class);
assertThrows(C3rRuntimeException.class, () -> SqlRowReader.getSelectStatementSql(statement, columnNames, NONCE_HEADER_DEFAULT));
}
}
@Test
public void initInsertStatementSqlExceptionTest() throws SQLException {
sqlTable = mock(SqlTable.class);
final Connection connection = mock(Connection.class);
when(sqlTable.getConnection()).thenReturn(connection);
when(connection.createStatement()).thenThrow(SQLException.class);
assertThrows(C3rRuntimeException.class, () -> new SqlRowReader<>(
columnInsights,
NONCE_HEADER_DEFAULT,
mock(CsvRowFactory.class),
sqlTable));
}
@Test
public void closeDoesNotCloseConnectionTest() throws SQLException {
final SqlRowReader<CsvValue> sqlRowReader = new SqlRowReader<>(
columnInsights,
NONCE_HEADER_DEFAULT,
mock(CsvRowFactory.class),
sqlTable);
assertFalse(sqlTable.getConnection().isClosed());
sqlRowReader.close();
assertFalse(sqlTable.getConnection().isClosed());
}
@Test
public void readRowsOrderByTest() throws SQLException {
// Grab a couple column headers. What they are doesn't matter.
final ColumnHeader firstHeader = columnInsights.get(0).getInternalHeader();
final ColumnHeader secondHeader = columnInsights.get(1).getInternalHeader();
try (Statement statement = sqlTable.getConnection().createStatement()) {
String insertSql = "INSERT INTO " + TableGenerator.DEFAULT_TABLE_NAME + " (\"" + firstHeader
+ "\", \"" + secondHeader + "\", \"" + NONCE_HEADER_DEFAULT
+ "\") VALUES (\"John\", \"Smith\", \"00000000000000000000000000000002\")";
statement.execute(insertSql);
insertSql = "INSERT INTO " + TableGenerator.DEFAULT_TABLE_NAME + " (\"" + firstHeader
+ "\", \"" + secondHeader + "\", \"" + NONCE_HEADER_DEFAULT
+ "\") VALUES (\"Jane\", \"Mac\", \"00000000000000000000000000000001\")";
statement.execute(insertSql);
insertSql = "INSERT INTO " + TableGenerator.DEFAULT_TABLE_NAME + " (\"" + firstHeader
+ "\", \"" + secondHeader + "\", \"" + NONCE_HEADER_DEFAULT
+ "\") VALUES (\"Frank\", \"Beans\", \"00000000000000000000000000000003\")";
statement.execute(insertSql);
}
final SqlRowReader<CsvValue> sqlRowReader = new SqlRowReader<>(
columnInsights,
NONCE_HEADER_DEFAULT,
new CsvRowFactory(),
sqlTable);
byte[] largestNonce = new byte[]{};
while (sqlRowReader.hasNext()) {
final Row<CsvValue> row = sqlRowReader.next();
final byte[] currentNonce = row.getValue(NONCE_HEADER_DEFAULT).getBytes();
assertTrue(Arrays.compare(largestNonce, currentNonce) < 0);
largestNonce = currentNonce;
}
assertEquals(3L, sqlRowReader.getReadRowCount());
}
}
| 2,533 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/CsvRowReaderTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.Row;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.Limits;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CsvRowReaderTest {
private final List<String> dataSampleRawHeaderNames =
List.of("FirstName",
"LastName",
"Address",
"City",
"State",
"PhoneNumber",
"Title",
"Level",
"Notes"
);
private final List<ColumnHeader> dataSampleHeaders =
dataSampleRawHeaderNames.stream().map(ColumnHeader::new).collect(Collectors.toList());
private final List<ColumnHeader> dataSampleHeadersNoNormalization =
dataSampleRawHeaderNames.stream().map(ColumnHeader::ofRaw).collect(Collectors.toList());
// ColumnSchema Name -> ColumnSchema Value mappings used for convenient testing data
// LinkedHashMap to ensure ordering of entries for tests that may care
private final Map<String, String> exampleCsvEntries = new LinkedHashMap<>() {
{
put("foo", "foo");
put("quoted-foo", "\"foo\"");
put("blank", "");
put("1space", " ");
put("quoted-blank", "\"\"");
put("quoted-1space", "\" \"");
put("backslash-N", "\\N");
put("quoted-backslash-N", "\"\\N\"");
put("spaced-backslash-N", " \\N ");
put("quoted-spaced-backslash-N", "\" \\N \"");
}
};
private CsvRowReader cReader;
private Path input;
@BeforeEach
public void setup() throws IOException {
input = FileTestUtility.createTempFile("input", ".csv");
writeTestData(input, exampleCsvEntries);
}
private void writeTestData(final Path path, final Map<String, String> data) throws IOException {
final String headerRow = String.join(",", data.keySet());
final String valueRow = String.join(",", data.values());
Files.writeString(path,
String.join("\n",
headerRow,
valueRow),
StandardCharsets.UTF_8);
}
@AfterEach
public void shutdown() {
if (cReader != null) {
cReader.close();
cReader = null;
}
}
@Test
public void getHeadersTest() {
cReader = CsvRowReader.builder().sourceName("../samples/csv/data_sample_without_quotes.csv").build();
assertEquals(dataSampleHeaders, cReader.getHeaders());
}
@Test
public void getHeadersNormalizationTest() {
// explicitly normalize the headers and make sure they match the expected values
cReader = CsvRowReader.builder().sourceName("../samples/csv/data_sample_without_quotes.csv").skipHeaderNormalization(false).build();
assertEquals(dataSampleHeaders, cReader.getHeaders());
}
@Test
public void getHeadersNoNormalizationTest() {
cReader = CsvRowReader.builder().sourceName("../samples/csv/data_sample_without_quotes.csv").skipHeaderNormalization(true).build();
assertEquals(dataSampleHeadersNoNormalization, cReader.getHeaders());
}
@Test
public void missingHeadersThrowsTest() throws IOException {
final String input = FileTestUtility.createTempFile("headerless", ".csv").toString();
assertThrowsExactly(
C3rRuntimeException.class,
() -> CsvRowReader.builder().sourceName(input).build());
}
@Test
public void badCharEncodingTest() {
assertThrowsExactly(C3rRuntimeException.class,
() -> CsvRowReader.builder().sourceName("../samples/csv/nonUtf8Encoding.csv").build());
}
@Test
public void tooManyColumnsTest() {
assertThrowsExactly(C3rRuntimeException.class,
() -> CsvRowReader.builder().sourceName("../samples/csv/one_row_too_many_columns.csv").build());
}
@Test
public void tooFewColumnsTest() {
assertThrowsExactly(C3rRuntimeException.class,
() -> CsvRowReader.builder().sourceName("../samples/csv/one_row_too_few_columns.csv").build());
}
@Test
public void rowsAreExpectedSizeTest() {
cReader = CsvRowReader.builder().sourceName("../samples/csv/data_sample_without_quotes.csv").build();
while (cReader.hasNext()) {
final Row<CsvValue> row = cReader.next();
assertEquals(row.size(), dataSampleHeaders.size());
}
assertNull(cReader.next());
}
@Test
public void customNullValuesTest() {
cReader = CsvRowReader.builder().sourceName("../samples/csv/data_sample_without_quotes.csv").inputNullValue("null").build();
final ColumnHeader notesColumn = new ColumnHeader("Notes");
boolean hasNull = false;
while (cReader.hasNext()) {
final Row<CsvValue> row = cReader.next();
hasNull |= row.getValue(notesColumn).toString() == null;
}
assertTrue(hasNull);
}
private Row<CsvValue> readCsvValuesPathRow(final String inputNullValue) {
cReader = CsvRowReader.builder().sourceName(input.toString()).inputNullValue(inputNullValue).build();
final List<Row<CsvValue>> rows = new ArrayList<>();
while (cReader.hasNext()) {
rows.add(cReader.next());
}
// sanity check the file is still just one row...
assertEquals(1, rows.size());
return rows.get(0);
}
@Test
public void omittedInputNullValueTest() {
// When NULL is not specified, any blank (i.e., no non-whitespace characters) quoted or unquoted
// is treated as NULL.
final Row<CsvValue> actual = readCsvValuesPathRow(null);
final var expected = GeneralTestUtility.csvRow(
"foo", "foo",
"quoted-foo", "foo",
"blank", null,
"1space", null,
"quoted-blank", null,
"quoted-1space", " ",
"backslash-N", "\\N",
"quoted-backslash-N", "\\N",
"spaced-backslash-N", "\\N",
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void emptyStringInputNullValueTest() {
// When NULL is specified as just space characters (e.g., `""`, `" "`, etc), any unquoted
// blank entries will be considered NULL, but quoted values (`"\"...\""`) will not
// regardless of content between the quotes.
final Row<CsvValue> actual = readCsvValuesPathRow("");
final var expected = GeneralTestUtility.csvRow(
"foo", "foo",
"quoted-foo", "foo",
"blank", null,
"1space", null,
"quoted-blank", "",
"quoted-1space", " ",
"backslash-N", "\\N",
"quoted-backslash-N", "\\N",
"spaced-backslash-N", "\\N",
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void spaceStringInputNullValueTest() {
// specifying `" "` is equivalent to specifying `""`: any unquoted blank string is NULL
final Row<CsvValue> actual = readCsvValuesPathRow(" ");
final var expected = GeneralTestUtility.csvRow(
"foo", "foo",
"quoted-foo", "foo",
"blank", null,
"1space", null,
"quoted-blank", "",
"quoted-1space", " ",
"backslash-N", "\\N",
"quoted-backslash-N", "\\N",
"spaced-backslash-N", "\\N",
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void quotedEmptyStringInputNullValueTest() {
// specifying `"\"\""` means only exactly that syntactic value is parsed as NULL
final Row<CsvValue> actual = readCsvValuesPathRow("\"\"");
final var expected = GeneralTestUtility.csvRow(
"foo", "foo",
"quoted-foo", "foo",
"blank", "",
"1space", "",
"quoted-blank", null,
"quoted-1space", " ",
"backslash-N", "\\N",
"quoted-backslash-N", "\\N",
"spaced-backslash-N", "\\N",
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void customStringInputNullValue1Test() {
final Row<CsvValue> actual = readCsvValuesPathRow("foo");
final var expected = GeneralTestUtility.csvRow(
"foo", null,
"quoted-foo", null,
"blank", "",
"1space", "",
"quoted-blank", "",
"quoted-1space", " ",
"backslash-N", "\\N",
"quoted-backslash-N", "\\N",
"spaced-backslash-N", "\\N",
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void customStringInputNullValue2Test() {
final Row<CsvValue> actual = readCsvValuesPathRow("\\N");
final var expected = GeneralTestUtility.csvRow(
"foo", "foo",
"quoted-foo", "foo",
"blank", "",
"1space", "",
"quoted-blank", "",
"quoted-1space", " ",
"backslash-N", null,
"quoted-backslash-N", null,
"spaced-backslash-N", null,
"quoted-spaced-backslash-N", " \\N "
);
assertEquals(expected, actual);
}
@Test
public void maxColumnCountTest() throws IOException {
final Map<String, String> columns = new HashMap<>();
// The <= is to make sure there's 1 more than the allowed max columns
for (int i = 0; i <= CsvRowReader.MAX_COLUMN_COUNT; i++) {
columns.put("column" + i, "value" + i);
}
writeTestData(input, columns);
// header row is enough to throw error on MAX_COLUMN_COUNT
assertThrowsExactly(C3rRuntimeException.class, () -> CsvRowReader.builder().sourceName(input.toString()).build());
}
@Test
public void maxVarcharByteCountHeaderTest() throws IOException {
final Map<String, String> columns = new HashMap<>();
final byte[] varcharBytes = new byte[Limits.AWS_CLEAN_ROOMS_HEADER_MAX_LENGTH + 1];
Arrays.fill(varcharBytes, (byte) 'a');
final String oversizedVarchar = new String(varcharBytes, StandardCharsets.UTF_8);
columns.put(oversizedVarchar, "value");
writeTestData(input, columns);
assertThrowsExactly(C3rIllegalArgumentException.class, () -> CsvRowReader.builder().sourceName(input.toString()).build());
}
@Test
public void getCsvColumnCountTest() {
assertEquals(
dataSampleHeaders.size(),
CsvRowReader.getCsvColumnCount("../samples/csv/data_sample_without_quotes.csv", StandardCharsets.UTF_8));
}
@Test
public void getCsvColumnCountInvalidHeadersInFirstRowTest() throws IOException {
final List<String> fileContentWith6Columns = List.of(
",,,,,",
"\"\",\"\",\"\",\"\",\"\",\"\"",
"\",\",\",\",\",\",\",\",\",\",\",\"",
",,,,,\n",
"a".repeat(Limits.AWS_CLEAN_ROOMS_HEADER_MAX_LENGTH + 1) + ",,,,,"
);
for (var content : fileContentWith6Columns) {
final Path nullsCsv = FileTestUtility.createTempFile();
Files.writeString(nullsCsv, content, StandardCharsets.UTF_8);
// ensure even when the first row has invalid headers, this method works as expected (i.e., that we're not using
// ColumnHeader on accident somewhere when we don't need to)
assertEquals(
6,
CsvRowReader.getCsvColumnCount(nullsCsv.toString(), StandardCharsets.UTF_8));
}
}
@Test
public void getCsvColumnCountEmptyFileTest() throws IOException {
final Path emptyFile = FileTestUtility.createTempFile("missing", ".csv");
assertEquals(0, Files.size(emptyFile));
assertThrows(C3rRuntimeException.class, () ->
CsvRowReader.getCsvColumnCount(emptyFile.toString(), StandardCharsets.UTF_8));
}
@Test
public void getCsvColumnCountMissingFileTest() throws IOException {
final String missingFile = FileTestUtility.resolve("missing.csv").toString();
assertThrows(C3rRuntimeException.class, () ->
CsvRowReader.getCsvColumnCount(missingFile, StandardCharsets.UTF_8));
}
@Test
public void getCsvColumnCountNonCsvFileTest() {
assertThrows(C3rRuntimeException.class, () ->
CsvRowReader.getCsvColumnCount("../samples/parquet/data_sample.parquet", StandardCharsets.UTF_8));
}
}
| 2,534 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/CsvRowWriterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.data.CsvRow;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CsvRowWriterTest {
// ColumnSchema Name -> ColumnSchema Value mappings used for convenient testing data
private static final CsvRow EXAMPLE_CSV_ROW = GeneralTestUtility.csvRow(
"NULL", null,
"foo", "foo",
"foo-space-bar", "foo bar",
"foo-newline-bar", "foo\nbar",
"blank", "",
"1space", " ",
"quoted-blank", "\"\"",
"quoted-1space", "\" \""
);
private static final List<ColumnHeader> HEADERS = Stream.of(
"NULL",
"foo",
"foo-space-bar",
"foo-newline-bar",
"blank",
"1space",
"quoted-blank",
"quoted-1space"
).map(ColumnHeader::new)
.collect(Collectors.toList());
private CsvRowWriter cWriter;
private Path output;
@BeforeEach
public void setup() throws IOException {
output = FileTestUtility.resolve("csv-values.csv");
output.toFile().deleteOnExit();
}
@AfterEach
public void shutdown() {
if (cWriter != null) {
cWriter.close();
cWriter = null;
}
}
private Map<String, String> readSingleCsvRow(final Path path) {
final var rows = CsvTestUtility.readRows(path.toString());
assertEquals(1, rows.size());
return rows.get(0);
}
@Test
public void defaultOutputNull_WriteRowTest() {
cWriter = CsvRowWriter.builder()
.headers(HEADERS)
.targetName(output.toString())
.fileCharset(StandardCharsets.UTF_8)
.build();
cWriter.writeRow(EXAMPLE_CSV_ROW);
cWriter.close();
final var actualRow = readSingleCsvRow(output);
// assertRowEntryPredicates
final var expectedRow = GeneralTestUtility.row(
"null", "",
"foo", "foo",
"foo-space-bar", "\"foo bar\"",
"foo-newline-bar", "\"foo\nbar\"",
// Non-NULL blank gets written as `,"",` by default, so it can be distinguished from NULL
"blank", "\"\"",
// Writing out a space has to use quotes to preserve the space
"1space", "\" \"",
// Writing out quotes requires double quotes
"quoted-blank", "\"\"\"\"",
// Writing out quotes requires double quotes
"quoted-1space", "\"\" \"\""
);
assertEquals(expectedRow, actualRow);
}
@Test
public void customOutputNull_WriteRowTest() {
cWriter = CsvRowWriter.builder()
.headers(HEADERS)
.outputNullValue("baz")
.targetName(output.toString())
.fileCharset(StandardCharsets.UTF_8)
.build();
cWriter.writeRow(EXAMPLE_CSV_ROW);
cWriter.close();
final var actualRow = readSingleCsvRow(output);
// assertRowEntryPredicates
final var expectedRow = GeneralTestUtility.row(
"null", "baz",
"foo", "foo",
"foo-space-bar", "\"foo bar\"",
"foo-newline-bar", "\"foo\nbar\"",
"blank", "",
"1space", "\" \"",
"quoted-blank", "\"\"\"\"",
"quoted-1space", "\"\" \"\""
);
assertEquals(expectedRow, actualRow);
}
}
| 2,535 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/RowReaderTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.data.CsvRow;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.Row;
import org.mockito.Mockito;
import org.mockito.stubbing.Answer;
import java.util.List;
import java.util.function.Function;
/**
* Utilities to replace a {@link RowReader} by using mocks and value generators.
*/
public final class RowReaderTestUtility {
/**
* Hidden utility class constructor.
*/
private RowReaderTestUtility() {
}
/**
* Creates a mocked CSV row reader using the specified headers and value generators.
*
* @param headers Names of the column headers
* @param valueProducer Functions for generating row values
* @param readRowCount How many rows have been read
* @param totalRowCount How many rows total should be produces
* @return Mocked row reader that will return rows based on function inputs
*/
@SuppressWarnings("unchecked")
public static RowReader<CsvValue> getMockCsvReader(final List<ColumnHeader> headers,
final Function<ColumnHeader, String> valueProducer,
final int readRowCount,
final int totalRowCount) {
final RowReader<CsvValue> mockReader = (RowReader<CsvValue>) Mockito.mock(RowReader.class,
Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS));
Mockito.when(mockReader.getHeaders()).thenReturn(headers);
Mockito.when(mockReader.peekNextRow()).thenAnswer((Answer<?>) invocation -> {
if (mockReader.getReadRowCount() >= totalRowCount) {
return null;
}
final Row<CsvValue> row = new CsvRow();
for (ColumnHeader header : headers) {
row.putValue(header, new CsvValue(valueProducer.apply(header)));
}
return row;
});
mockReader.setReadRowCount(readRowCount);
Mockito.when(mockReader.getSourceName()).thenReturn("rowSource");
return mockReader;
}
}
| 2,536 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/CsvTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Utility functions for common CSV data manipulation needed during testing.
*/
public final class CsvTestUtility {
/**
* Hidden utility class constructor.
*/
private CsvTestUtility() {
}
/**
* Create basic parser settings that don't modify/NULL any values
* aside from the default whitespace trimming.
*
* @param keepQuotes If quotes should be kept as part of the string being read in or not
* @return Settings to bring up a simple CSV parser
*/
private static CsvParserSettings getBasicParserSettings(final boolean keepQuotes) {
final CsvParserSettings settings = new CsvParserSettings();
settings.setLineSeparatorDetectionEnabled(true);
settings.setNullValue("");
settings.setEmptyValue("\"\"");
settings.setKeepQuotes(keepQuotes);
return settings;
}
/**
* Read the contents of the CSV file as rows, mapping column names to content.
*
* <p>
* The column names are normalized per the C3R's normalizing (lower-cased and whitespace trimmed).
*
* @param fileName File to read
* @return Rows read in the order they appear
* @throws C3rIllegalArgumentException If the file does not have the same number of entries in each row
*/
public static List<Map<String, String>> readRows(final String fileName) {
final CsvParserSettings settings = getBasicParserSettings(true);
settings.setHeaderExtractionEnabled(true);
final CsvParser parser = new CsvParser(settings);
return parser.parseAllRecords(new File(fileName), StandardCharsets.UTF_8)
.stream()
.map(r -> r.toFieldMap())
.collect(Collectors.toList());
}
/**
* Read the file content with rows as arrays. There is no mapping to column headers, if any, in the file.
*
* @param fileName Location of file to read
* @param keepQuotes If quotes should be kept as part of the string being read in or not
* @return List of rows where each row is an array of values
* @throws RuntimeException If the file is not found
*/
public static List<String[]> readContentAsArrays(final String fileName, final boolean keepQuotes) {
final CsvParserSettings settings = getBasicParserSettings(keepQuotes);
return new CsvParser(settings).parseAll(new File(fileName), StandardCharsets.UTF_8);
}
}
| 2,537 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/io/sql/TableGeneratorTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.io.sql;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.Limits;
import com.amazonaws.c3r.utils.FileUtil;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.stubbing.Answer;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static com.amazonaws.c3r.utils.FileUtil.isWindows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TableGeneratorTest {
private Statement statement;
private TableSchema schema;
@BeforeEach
public void setup() throws SQLException {
statement = mock(Statement.class);
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenAnswer((Answer<String>) invocation -> {
final Object[] args = invocation.getArguments();
return "\"" + args[0] + "\""; // enquote the column names
});
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(GeneralTestUtility.cleartextColumn("source", "target1"));
columnSchemas.add(GeneralTestUtility.sealedColumn("source", "target2", PadType.FIXED, 100));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("source", "target3"));
schema = new MappedTableSchema(columnSchemas);
}
@Test
public void generateNonceHeaderTest() {
final String nonceBaseName = "nonce_row";
final Set<ColumnSchema> columnSchemas = new HashSet<>();
// if there's no columns we're guaranteed to get the "default" nonce header:
final ColumnHeader defaultNonceHeader = TableGenerator.generateUniqueHeader(new HashSet<>(), nonceBaseName);
// add some silly, obviously not the nonce header columns
columnSchemas.add(GeneralTestUtility.cleartextColumn("not_nonce_but_header"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("not_nonce_but_title"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("not_nonce_but_other"));
ColumnHeader otherNonceHeader = TableGenerator.generateUniqueHeader(columnSchemas.stream()
.map(ColumnSchema::getTargetHeader)
.collect(Collectors.toUnmodifiableSet()),
nonceBaseName);
// check that we get the same header since there are no name conflicts yet
assertEquals(defaultNonceHeader, otherNonceHeader);
// check that the nonce is indeed not in the original column set
assertFalse(columnSchemas.stream().map(ColumnSchema::getTargetHeader).collect(Collectors.toSet()).contains(otherNonceHeader));
// Test that we can add many possible collisions, and we always get fresh
// nonce headers (by adding the previously generated nonce header each loop)
for (int i = 0; i < 100; i++) {
// add the last nonce header to the column list to introduce another conflict
columnSchemas.add(GeneralTestUtility.cleartextColumn(otherNonceHeader.toString()));
// generate a _new_ nonce header
otherNonceHeader = TableGenerator.generateUniqueHeader(columnSchemas.stream()
.map(ColumnSchema::getTargetHeader)
.collect(Collectors.toUnmodifiableSet()),
nonceBaseName);
// check that the new nonce header is still not the list
assertFalse(columnSchemas.stream().map(ColumnSchema::getTargetHeader).collect(Collectors.toSet()).contains(otherNonceHeader));
}
}
@Test
public void createTableTest() throws SQLException {
final Connection connection = TableGenerator.initTable(
GeneralTestUtility.CONFIG_SAMPLE,
new ColumnHeader("nonce"),
FileUtil.CURRENT_DIR)
.getConnection();
final String url = connection.getMetaData().getURL().replaceFirst("jdbc:sqlite:", "");
final File dbFile = new File(url);
assertTrue(dbFile.exists());
}
@Test
public void initTableFileTest() {
final File dbFile = TableGenerator.initTableFile(FileUtil.CURRENT_DIR);
assertTrue(dbFile.exists());
}
@Test
public void initTableFileBadDirTest() {
assertThrows(C3rRuntimeException.class, () -> TableGenerator.initTableFile(FileUtil.TEMP_DIR + FileUtil.TEMP_DIR));
}
@Test
public void initTableFileFilePathTooLongOnWindowsTest() {
if (isWindows()) {
final byte[] filePathBytes = new byte[500];
Arrays.fill(filePathBytes, (byte) 'a');
final String longFilePath = new String(filePathBytes, StandardCharsets.UTF_8);
assertThrows(C3rRuntimeException.class, () -> TableGenerator.initTableFile(longFilePath));
}
}
@Test
public void initTableTargetColumnHeaderBadSqlHeaderTest() {
final char[] sqlHeaderTooLong = new char[Limits.AWS_CLEAN_ROOMS_HEADER_MAX_LENGTH];
Arrays.fill(sqlHeaderTooLong, 'a');
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(GeneralTestUtility.cleartextColumn("source", String.valueOf(sqlHeaderTooLong)));
columnSchemas.add(GeneralTestUtility.cleartextColumn("source", "_Starts_With_Illegal_Char"));
schema = new MappedTableSchema(columnSchemas);
assertDoesNotThrow(() -> TableGenerator.initTable(
schema,
new ColumnHeader("nonce"),
FileUtil.CURRENT_DIR));
}
@Test
public void getTableSchemaFromConfigTest() throws SQLException {
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(GeneralTestUtility.sealedColumn("firstname", "firstname", PadType.FIXED, 100));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("lastname", "lastname"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("address", "address"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("city", "city"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("state", "state"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("phonenumber", "phonenumber"));
columnSchemas.add(GeneralTestUtility.fingerprintColumn("title", "title"));
columnSchemas.add(GeneralTestUtility.cleartextColumn("level", "level"));
columnSchemas.add(GeneralTestUtility.sealedColumn("notes", "notes", PadType.MAX, 100));
final Statement statement = mock(Statement.class);
when(statement.enquoteIdentifier(anyString(), anyBoolean())).thenAnswer((Answer<String>) invocation -> {
final Object[] args = invocation.getArguments();
return "\"" + args[0] + "\""; // enquote the column names
});
final TableSchema tableConfig = new MappedTableSchema(columnSchemas);
final String tableSchema = TableGenerator.getTableSchemaFromConfig(
statement, tableConfig, new ColumnHeader("nonce"));
final StringBuilder expectedSchema = new StringBuilder("CREATE TABLE c3rTmp (\n\"nonce\" TEXT");
for (ColumnSchema column : columnSchemas) {
expectedSchema.append(",\n\"").append(column.getInternalHeader()).append("\" TEXT");
}
expectedSchema.append(")");
assertEquals(expectedSchema.toString(), tableSchema);
}
@Test
public void oneSourceToMultipleTargetsTest() {
final String tableSchema = TableGenerator.getTableSchemaFromConfig(
statement, schema, new ColumnHeader("nonce"));
final StringBuilder expectedSchema = new StringBuilder("CREATE TABLE c3rTmp (\n\"nonce\" TEXT");
for (ColumnSchema column : schema.getColumns()) {
expectedSchema.append(",\n\"").append(column.getInternalHeader()).append("\" TEXT");
}
expectedSchema.append(")");
assertEquals(expectedSchema.toString(), tableSchema);
}
@Test
public void getIndexStatementTest() {
assertEquals(
"CREATE UNIQUE INDEX \"row_nonce_idx\" ON \"c3rTmp\"(\"nonce\", \"target1\", \"target2\", \"target3\");",
TableGenerator.getCoveringIndexStatement(statement, schema, new ColumnHeader("nonce"))
);
}
}
| 2,538 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/internal/NonceTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.internal;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class NonceTest {
@RepeatedTest(100)
public void getNonceTest() {
// Ensure nonces aren't equal
final Nonce nonce1 = Nonce.nextNonce();
final Nonce nonce2 = Nonce.nextNonce();
assertFalse(Arrays.equals(nonce1.getBytes(), nonce2.getBytes()));
}
@Test
public void validateNullNonceTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new Nonce(null));
}
@Test
public void validateEmptyNonceTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new Nonce(new byte[0]));
}
@Test
public void validateSmallNonceTest() {
final byte[] nonceBytes = "small".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> new Nonce(nonceBytes));
}
@Test
public void validateLargeNonceTest() {
final byte[] nonceBytes = ("ANonceMayOnlyBe" + Nonce.NONCE_BYTE_LENGTH + "BytesLong").getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> new Nonce(nonceBytes));
}
}
| 2,539 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/internal/ColumnTypeTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.internal;
import com.amazonaws.c3r.CleartextTransformer;
import com.amazonaws.c3r.FingerprintTransformer;
import com.amazonaws.c3r.SealedTransformer;
import com.amazonaws.c3r.config.ColumnType;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ColumnTypeTest {
@Test
public void cleartextColumnTypeTest() {
assertEquals(CleartextTransformer.class, ColumnType.CLEARTEXT.getTransformerType());
}
@Test
public void fingerprintColumnTypeTest() {
assertEquals(FingerprintTransformer.class, ColumnType.FINGERPRINT.getTransformerType());
}
@Test
public void sealedColumnTypeTest() {
assertEquals(SealedTransformer.class, ColumnType.SEALED.getTransformerType());
}
}
| 2,540 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/internal/InitializationVectorTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.internal;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class InitializationVectorTest {
@Test
public void deriveIvTest() {
// Expected byte[] SHA-256 hash of column label + nonce
final InitializationVector expectedIv = new InitializationVector(new byte[]{106, 125, 22, 25, -9, -53, 121, 41, 78, -102, 89, -5});
final Nonce nonce = new Nonce("nonce01234567890nonce01234567890".getBytes(StandardCharsets.UTF_8));
final InitializationVector actualIv = InitializationVector.deriveIv("label", nonce);
assertEquals(InitializationVector.IV_BYTE_LENGTH, actualIv.getBytes().length);
assertArrayEquals(expectedIv.getBytes(), actualIv.getBytes());
}
@Test
public void deriveIvChangesWithNonceTest() {
final InitializationVector iv1 = InitializationVector.deriveIv("label", Nonce.nextNonce());
final InitializationVector iv2 = InitializationVector.deriveIv("label", Nonce.nextNonce());
assertFalse(Arrays.equals(iv1.getBytes(), iv2.getBytes()));
}
@Test
public void deriveIvChangesWithLabelNonceTest() {
final Nonce nonce = Nonce.nextNonce();
final InitializationVector iv1 = InitializationVector.deriveIv("label1", nonce);
final InitializationVector iv2 = InitializationVector.deriveIv("label2", nonce);
assertFalse(Arrays.equals(iv1.getBytes(), iv2.getBytes()));
}
@Test
public void deriveIvNullNonceTest() {
assertThrows(C3rIllegalArgumentException.class, () -> InitializationVector.deriveIv("label", null));
}
@Test
public void deriveIvNullLabelTest() {
assertThrows(C3rIllegalArgumentException.class, () -> InitializationVector.deriveIv(null, Nonce.nextNonce()));
}
@Test
public void deriveIvEmptyLabelTest() {
assertThrows(C3rIllegalArgumentException.class, () -> InitializationVector.deriveIv("", Nonce.nextNonce()));
}
@Test
public void validateNullIvTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new InitializationVector(null));
}
@Test
public void validateEmptyIvTest() {
assertThrows(C3rIllegalArgumentException.class, () -> new InitializationVector(new byte[0]));
}
@Test
public void validateSmallIvTest() {
final byte[] ivBytes = "small".getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> new InitializationVector(ivBytes));
}
@Test
public void validateLargeIvTest() {
final byte[] ivBytes = ("AnIvMayOnlyBe" + InitializationVector.IV_BYTE_LENGTH + "BytesLong").getBytes(StandardCharsets.UTF_8);
assertThrows(C3rIllegalArgumentException.class, () -> new InitializationVector(ivBytes));
}
}
| 2,541 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/internal/PadUtilTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.internal;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PadUtilTest {
private final Nonce nonce = new Nonce("nonce01234567890nonce01234567890".getBytes(StandardCharsets.UTF_8));
@Test
public void generatePadEmptyTest() {
final byte[] pad = PadUtil.generatePad(0);
assertArrayEquals(new byte[0], pad);
}
@Test
public void generatePadTest() {
final int padSize = 1000;
final byte[] pad = PadUtil.generatePad(padSize);
assertEquals(padSize, pad.length);
}
@Test
public void padMessageNullEncryptionContextTest() {
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(new byte[0], null));
}
@Test
public void padMessagePadTypeFixedTest() {
final byte[] message = "Some message to pad".getBytes(StandardCharsets.UTF_8);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.FIXED)
.padLength(100)
.build();
final byte[] paddedMessage = PadUtil.padMessage(message, context);
assertEquals(100 + PadUtil.PAD_LENGTH_BYTES, paddedMessage.length);
final byte[] unpaddedMessage = PadUtil.removePadding(paddedMessage);
assertArrayEquals(message, unpaddedMessage);
}
@Test
public void padMessagePadTypeFixedNotEnoughSpaceTest() {
final byte[] message = "Some message to pad".getBytes(StandardCharsets.UTF_8);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.FIXED)
.padLength(1) // A value shorter than the message itself + PAD_LENGTH_SIZE
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(message, context));
}
@Test
public void padMessagePadTypeMaxTest() {
final byte[] message = "Some message to pad".getBytes(StandardCharsets.UTF_8);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.MAX)
.padLength(100)
.maxValueLength(50)
.build();
final byte[] paddedMessage = PadUtil.padMessage(message, context);
assertEquals(150 + PadUtil.PAD_LENGTH_BYTES, paddedMessage.length);
final byte[] unpaddedMessage = PadUtil.removePadding(paddedMessage);
assertArrayEquals(message, unpaddedMessage);
}
@Test
public void padMessagePadTypeMaxMaximumLengthTest() {
final byte[] message = new byte[PadUtil.MAX_PADDED_CLEARTEXT_BYTES - PadUtil.MAX_PAD_BYTES];
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.MAX)
.padLength(PadUtil.MAX_PAD_BYTES)
.maxValueLength(message.length)
.build();
final byte[] paddedMessage = PadUtil.padMessage(message, context);
assertEquals(PadUtil.MAX_PADDED_CLEARTEXT_BYTES + PadUtil.PAD_LENGTH_BYTES, paddedMessage.length);
}
@Test
public void padMessagePadTypeMaxNotEnoughSpaceTest() {
final byte[] message = "Some message to pad".getBytes(StandardCharsets.UTF_8);
final EncryptionContext contextPadTooBig = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.MAX)
.padLength(PadUtil.MAX_PAD_BYTES)
.maxValueLength(PadUtil.MAX_PADDED_CLEARTEXT_BYTES - PadUtil.MAX_PAD_BYTES + 1) // A value too big to pad
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(message, contextPadTooBig));
final EncryptionContext contextMaxValueTooBig = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.MAX)
.padLength(100)
.maxValueLength(PadUtil.MAX_PADDED_CLEARTEXT_BYTES) // A value too big to pad
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(new byte[PadUtil.MAX_PADDED_CLEARTEXT_BYTES],
contextMaxValueTooBig));
}
@Test
public void padMessagePadTypeFixedNotEnoughSpaceMaxStringTest() {
final byte[] message = new byte[PadUtil.MAX_PADDED_CLEARTEXT_BYTES + 1];
Arrays.fill(message, (byte) 0x00);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.FIXED)
.padLength(1)
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(message, context));
}
@Test
public void padMessagePadTooLargeTest() {
final byte[] message = new byte[1];
Arrays.fill(message, (byte) 0x00);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.FIXED)
.padLength(PadUtil.MAX_PAD_BYTES + 1) // The maximum size of a pad
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(message, context));
}
@Test
public void padMessagePadNegativeTest() {
final byte[] message = new byte[1];
Arrays.fill(message, (byte) 0x00);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.FIXED)
.padLength(-1) // The maximum size of a pad
.build();
assertThrows(C3rIllegalArgumentException.class, () -> PadUtil.padMessage(message, context));
}
@Test
public void padMessagePadTypeNoneTest() {
final byte[] message = "Some message to pad".getBytes(StandardCharsets.UTF_8);
final EncryptionContext context = EncryptionContext.builder()
.columnLabel("label")
.nonce(nonce)
.padType(PadType.NONE)
.padLength(100) // to assert NONE is respected over length
.build();
final byte[] paddedMessage = PadUtil.padMessage(message, context);
assertEquals(message.length, paddedMessage.length - PadUtil.PAD_LENGTH_BYTES);
final byte[] unpaddedMessage = PadUtil.removePadding(paddedMessage);
assertArrayEquals(message, unpaddedMessage);
}
}
| 2,542 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/DecryptSdkConfigTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import lombok.Builder;
import lombok.Getter;
import javax.crypto.spec.SecretKeySpec;
/**
* Basic Decryption settings.
*/
@Builder
@Getter
public class DecryptSdkConfigTestUtility {
/**
* Key to use for decryption.
*/
@Builder.Default
private SecretKeySpec key = null;
/**
* Salt for key generation.
*/
@Builder.Default
private String salt = null;
/**
* Input file.
*/
@Builder.Default
private String input = null;
/**
* Column header names.
*/
@Builder.Default
private String[] columnHeaders = null;
}
| 2,543 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/FileUtilTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.AclEntry;
import java.nio.file.attribute.AclEntryPermission;
import java.nio.file.attribute.AclEntryType;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import static com.amazonaws.c3r.utils.FileUtil.isWindows;
import static com.amazonaws.c3r.utils.FileUtil.setWindowsFilePermissions;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class FileUtilTest {
@Test
public void verifyBlankLocationRejectedByVerifyReadableFile() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableFile(""));
}
@Test
public void verifyDirectoryRejectedByVerifyReadableFile() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableFile(FileUtil.TEMP_DIR));
}
@Test
public void verifyMissingFileRejectedByVerifyReadableFile() throws IOException {
final String file = FileTestUtility.resolve("missing.csv").toString();
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableFile(file));
}
@Test
public void verifyNoReadPermissionsRejectedByVerifyReadableFile() throws IOException {
final File file = FileTestUtility.createTempFile("NotReadable", ".tmp").toFile();
if (isWindows()) {
setWindowsFilePermissions(file.toPath(), AclEntryType.DENY, Set.of(AclEntryPermission.READ_DATA));
} else {
assertTrue(file.setReadable(false, false));
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableFile(file.getAbsolutePath()));
}
@Test
public void verifyFileAcceptedByVerifyReadableFile() throws IOException {
final File file = FileTestUtility.createTempFile("Readable", ".tmp").toFile();
if (isWindows()) {
setWindowsFilePermissions(file.toPath(), AclEntryType.ALLOW, Set.of(AclEntryPermission.READ_DATA));
} else {
assertTrue(file.setReadable(true, true));
}
assertDoesNotThrow(() -> FileUtil.verifyReadableFile(file.getAbsolutePath()));
}
@Test
public void verifyBlankLocationRejectedByVerifyReadableDirectory() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableDirectory(""));
}
@Test
public void verifyFileRejectedByVerifyReadableDirectory() {
assertThrowsExactly(C3rIllegalArgumentException.class,
() -> FileUtil.verifyReadableDirectory(FileTestUtility.createTempFile().toString()));
}
@Test
public void verifyMissingDirectoryRejectedByVerifyReadableDirectory() throws IOException {
final String file = FileTestUtility.resolve("directory").toString();
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableDirectory(file));
}
@Test
public void verifyNoReadPermissionsRejectedByVerifyReadableDirectory() throws IOException {
final File file = FileTestUtility.createTempDir().toFile();
if (isWindows()) {
setWindowsFilePermissions(file.toPath(), AclEntryType.DENY, Set.of(AclEntryPermission.READ_DATA));
} else {
assertTrue(file.setReadable(false, false));
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyReadableDirectory(file.getAbsolutePath()));
}
@Test
public void verifyDirectoryAcceptedByVerifyReadableDirectory() throws IOException {
final File file = FileTestUtility.createTempDir().toFile();
if (isWindows()) {
setWindowsFilePermissions(file.toPath(), AclEntryType.ALLOW, Set.of(AclEntryPermission.READ_DATA));
} else {
assertTrue(file.setReadable(true, true));
}
assertDoesNotThrow(() -> FileUtil.verifyReadableDirectory(file.getAbsolutePath()));
}
@Test
public void verifyBlankLocationRejectedByVerifyWritableFile() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile("", false));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile("", true));
}
@Test
public void verifyDirectoryRejectedByVerifyFileWriteable() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile(FileUtil.TEMP_DIR, false));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile(FileUtil.TEMP_DIR, true));
}
@Test
public void verifyFileWithoutWritePermissionsRejectedByVerifyFileWriteable() throws IOException {
final File file = FileTestUtility.createTempFile("NotWriteable", ".tmp").toFile();
if (isWindows()) {
setWindowsFilePermissions(file.toPath(), AclEntryType.DENY, Set.of(AclEntryPermission.WRITE_DATA));
} else {
assertTrue(file.setWritable(false, false));
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile(file.getAbsolutePath(), false));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile(file.getAbsolutePath(), true));
}
@Test
public void verifyNewFileAcceptedByVerifyFileWriteable() throws IOException {
final String file = FileTestUtility.resolve("newFile.csv").toString();
assertDoesNotThrow(() -> FileUtil.verifyWritableFile(file, false));
assertDoesNotThrow(() -> FileUtil.verifyWritableFile(file, true));
}
@Test
public void verifyExistingFileAndNoOverwriteRejectedByVerifyFileWriteable() throws IOException {
final String file = FileTestUtility.createTempFile().toString();
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableFile(file, false));
}
@Test
public void verifyExistingFileAndOverwriteAcceptedByVerifyFileWriteable() throws IOException {
final String file = FileTestUtility.createTempFile().toString();
assertDoesNotThrow(() -> FileUtil.verifyWritableFile(file, true));
}
@Test
public void verifyBlankLocationRejectedByVerifyWriteableDirectory() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableDirectory(""));
}
@Test
public void verifyFileIsRejectedByVerifyWriteableDirectory() throws IOException {
final String file = FileTestUtility.createTempFile().toString();
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableDirectory(file));
}
@Test
public void verifyDirectoryWithoutWritePermissionsRejectedByVerifyWriteableDirectory() throws IOException {
final File dir = FileTestUtility.createTempDir().toFile();
if (isWindows()) {
setWindowsFilePermissions(dir.toPath(), AclEntryType.DENY, Set.of(AclEntryPermission.WRITE_DATA));
} else {
assertTrue(dir.setWritable(false, false));
}
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableDirectory(dir.getAbsolutePath()));
}
@Test
public void verifyDirectoryAcceptedByVerifyWriteableDirectory() throws IOException {
final String dir = FileTestUtility.createTempDir().toFile().toString();
assertDoesNotThrow(() -> FileUtil.verifyWritableDirectory(dir));
}
@Test
public void verifyNewDirectoryAcceptedByVerifyWriteableDirectory() throws IOException {
final String dir = FileTestUtility.createTempDir().toString();
assertDoesNotThrow(() -> FileUtil.verifyWritableDirectory(dir));
}
@Test
public void verifyExistingDirectoryAndNoOverwriteRejectedByVerifyDirectoryWriteable() throws IOException {
final String file = FileTestUtility.createTempDir().toString();
assertThrowsExactly(C3rIllegalArgumentException.class, () -> FileUtil.verifyWritableDirectory(file, false));
}
@Test
public void verifyExistingDirectoryAndOverwriteAcceptedByVerifyDirectoryWriteable() throws IOException {
final String file = FileTestUtility.createTempDir().toString();
assertDoesNotThrow(() -> FileUtil.verifyWritableDirectory(file, true));
}
@Test
public void initFileIfNotExistsTest() throws IOException {
final File tempFile = FileTestUtility.resolve("output.csv").toFile();
assertFalse(tempFile.exists());
FileUtil.initFileIfNotExists(tempFile.getAbsolutePath());
assertTrue(tempFile.exists());
if (!isWindows()) {
assertTrue(tempFile.canWrite());
assertTrue(tempFile.canRead());
} else {
verifyWindowsPermissions(tempFile.toPath(), Set.of(AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA));
}
}
@Test
public void initFileIfNotExistsRespectsExistingPermissionsTest() throws IOException {
final File tempFile = FileTestUtility.createTempFile().toFile();
if (isWindows()) {
setWindowsFilePermissions(tempFile.toPath(), AclEntryType.ALLOW, Set.of(AclEntryPermission.READ_DATA,
AclEntryPermission.EXECUTE));
} else {
assertTrue(tempFile.setReadable(true, true));
assertTrue(tempFile.setExecutable(true, true));
assertTrue(tempFile.setWritable(false, false));
}
FileUtil.initFileIfNotExists(tempFile.getAbsolutePath());
assertTrue(tempFile.exists());
if (!isWindows()) {
assertFalse(tempFile.canWrite());
assertTrue(tempFile.canRead());
assertTrue(tempFile.canExecute());
} else {
verifyWindowsPermissions(tempFile.toPath(), Set.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE));
}
}
@Test
public void readWriteOnlyFilePermissionsTest() throws IOException {
final File tempFile = FileTestUtility.createTempFile().toFile();
FileUtil.setOwnerReadWriteOnlyPermissions(tempFile);
assertTrue(tempFile.exists());
if (!isWindows()) {
assertTrue(tempFile.canWrite());
assertTrue(tempFile.canRead());
} else {
verifyWindowsPermissions(tempFile.toPath(), Set.of(AclEntryPermission.READ_DATA, AclEntryPermission.WRITE_DATA));
}
}
@Test
public void initFileIfNotExistsFilePathTooLongOnWindowsTest() {
if (isWindows()) {
final byte[] filePathBytes = new byte[500];
Arrays.fill(filePathBytes, (byte) 'a');
final String longFilePath = new String(filePathBytes, StandardCharsets.UTF_8);
assertThrows(C3rRuntimeException.class, () -> FileUtil.initFileIfNotExists(longFilePath));
}
}
@SuppressWarnings("unchecked")
private void verifyWindowsPermissions(final Path path, final Set<AclEntryPermission> permissions) throws IOException {
final List<AclEntry> acls = (List<AclEntry>) Files.getAttribute(path, "acl:acl");
final AclEntryPermission[] actual = acls.get(0).permissions().toArray(new AclEntryPermission[0]);
Arrays.sort(actual);
final AclEntryPermission[] expected = permissions == null ? new AclEntryPermission[0] :
permissions.toArray(new AclEntryPermission[0]);
Arrays.sort(expected);
assertArrayEquals(expected, actual);
}
} | 2,544 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/GeneralTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.data.CsvRow;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Set of Utilities used for Testing. A combination of file settings and helper functions.
*/
public abstract class GeneralTestUtility {
/**
* A 32-byte key used for testing.
*/
public static final byte[] EXAMPLE_KEY_BYTES =
new byte[]{
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31
};
/**
* Example salt for testing.
*/
public static final UUID EXAMPLE_SALT = UUID.fromString("00000000-1111-2222-3333-444444444444");
/**
* Schema for data_sample.csv.
*/
public static final TableSchema CONFIG_SAMPLE = new MappedTableSchema(List.of(
cleartextColumn("firstname"),
cleartextColumn("lastname"),
sealedColumn("address", PadType.MAX, 32),
sealedColumn("city", PadType.MAX, 16),
fingerprintColumn("state"),
cleartextColumn("phonenumber", "phonenumber_cleartext"),
sealedColumn("phonenumber", "phonenumber_sealed"),
fingerprintColumn("phonenumber", "phonenumber_fingerprint"),
sealedColumn("title", PadType.FIXED, 128),
cleartextColumn("level"),
sealedColumn("notes", PadType.MAX, 100)
));
/**
* Schema for null5by6.csv.
*/
public static final TableSchema TEST_CONFIG_6COLUMN = new MappedTableSchema(List.of(
cleartextColumn("cleartext"),
sealedColumn("sealed_none"),
sealedColumn("sealed_max", PadType.MAX, 42),
sealedColumn("sealed_fixed", PadType.FIXED, 42),
fingerprintColumn("fingerprint_1"),
fingerprintColumn("fingerprint_2")
));
/**
* Encryption configuration used for data_sample.csv (matches decryption configuration for marshalled_data_sample.csv).
*
* @see #TEST_CONFIG_MARSHALLED_DATA_SAMPLE
*/
public static final EncryptSdkConfigTestUtility TEST_CONFIG_DATA_SAMPLE = EncryptSdkConfigTestUtility.builder()
.input("../samples/csv/data_sample_with_quotes.csv")
.inputColumnHeaders(CONFIG_SAMPLE.getColumns().stream().map(ColumnSchema::getSourceHeader).map(ColumnHeader::toString)
.collect(Collectors.toList()))
.outputColumnHeaders(CONFIG_SAMPLE.getColumns().stream().map(ColumnSchema::getTargetHeader).map(ColumnHeader::toString)
.collect(Collectors.toList()))
.salt("saltybytes")
.key(new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, KeyUtil.KEY_ALG))
.schema(CONFIG_SAMPLE)
.build();
/**
* Encryption configuration used for one_row_null_sample.csv with only cleartext columns.
*/
public static final EncryptSdkConfigTestUtility TEST_CONFIG_ONE_ROW_NULL_SAMPLE_CLEARTEXT = EncryptSdkConfigTestUtility.builder()
.input("../samples/csv/one_row_null_sample.csv")
.inputColumnHeaders(List.of("firstname", "lastname", "address", "city"))
.outputColumnHeaders(List.of("firstname", "lastname", "address", "city"))
.salt("saltybytes")
.key(new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, KeyUtil.KEY_ALG))
.schema(new MappedTableSchema(Stream.of("firstname", "lastname", "address", "city").map(GeneralTestUtility::cleartextColumn)
.collect(Collectors.toList())))
.build();
/**
* Decryption configuration for marshalled_data_sample.csv (matches encryption configuration for data_sample.csv).
*
* @see #TEST_CONFIG_DATA_SAMPLE
*/
public static final DecryptSdkConfigTestUtility TEST_CONFIG_MARSHALLED_DATA_SAMPLE = DecryptSdkConfigTestUtility.builder()
.input("../samples/csv/marshalled_data_sample.csv")
.columnHeaders(new String[]{"firstname", "lastname", "address", "city", "state", "phonenumber_cleartext",
"phonenumber_sealed", "phonenumber_fingerprint", "title", "level", "notes"})
.salt(GeneralTestUtility.EXAMPLE_SALT.toString())
.key(new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, KeyUtil.KEY_ALG))
.build();
/**
* Create a ColumnHeader if name isn't null.
*
* <p>
* This helper function is to support testing positional schemas. Those schemas need to have {@code null} as the value
* for the sourceHeader. However, {@code new ColumnHeader(null)} fails validation. Instead of using the ternary operator
* everywhere we assign the source value, we can call this function instead which is a bit cleaner. By having this helper,
* we don't need to make another full set of helper functions for schema creation, we can just pass {@code null} in to the
* existing helpers. {@link com.amazonaws.c3r.config.PositionalTableSchema} uses this functionality in the creation of all it's
* test variables at the top of the file if you want to see an example usage of why we need to pass null through.
*
* @param name Name of the column or {@code null} if there isn't one
* @return Input string transformed into {@link ColumnHeader} or {@code null} if {@code name} was {@code null}
*/
private static ColumnHeader nameHelper(final String name) {
if (name == null) {
return null;
}
return new ColumnHeader(name);
}
/**
* Helper function that handles cleartext column boilerplate.
*
* @param name Name to be used for input and output row
* @return An cleartext column schema
*/
public static ColumnSchema cleartextColumn(final String name) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(name))
.targetHeader(nameHelper(name))
.pad(null)
.type(ColumnType.CLEARTEXT)
.build();
}
/**
* Helper function that handles cleartext column boilerplate.
*
* @param nameIn Source column header name
* @param nameOut Target column header name
* @return An cleartext column schema
*/
public static ColumnSchema cleartextColumn(final String nameIn, final String nameOut) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(nameIn))
.targetHeader(nameHelper(nameOut))
.pad(null)
.type(ColumnType.CLEARTEXT)
.build();
}
/**
* Helper function for a sealed column with no pad.
*
* @param name Source and target column header name
* @return A sealed column schema
*/
public static ColumnSchema sealedColumn(final String name) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(name))
.targetHeader(nameHelper(name))
.pad(Pad.DEFAULT)
.type(ColumnType.SEALED)
.build();
}
/**
* Helper function for a sealed column with no pad.
*
* @param nameIn Source header name
* @param nameOut Target header name
* @return A sealed column schema
*/
public static ColumnSchema sealedColumn(final String nameIn, final String nameOut) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(nameIn))
.targetHeader(nameHelper(nameOut))
.pad(Pad.DEFAULT)
.type(ColumnType.SEALED)
.build();
}
/**
* Helper function for a sealed column with specified padding.
*
* @param name Name for source and target column headers
* @param type What pad type to use
* @param length How long the pad should be
* @return A sealed column schema
*/
public static ColumnSchema sealedColumn(final String name, final PadType type, final Integer length) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(name))
.targetHeader(nameHelper(name))
.pad(Pad.builder().type(type).length(length).build())
.type(ColumnType.SEALED)
.build();
}
/**
* Helper function for a sealed column with specified padding.
*
* @param nameIn Name for source column headers
* @param nameOut Name for target column header
* @param type What pad type to use
* @param length How long the pad should be
* @return A sealed column schema
*/
public static ColumnSchema sealedColumn(final String nameIn, final String nameOut, final PadType type, final Integer length) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(nameIn))
.targetHeader(nameHelper(nameOut))
.pad(Pad.builder().type(type).length(length).build())
.type(ColumnType.SEALED)
.build();
}
/**
* Helper function for creating a fingerprint column.
*
* @param name The name to use for both the source and target header
* @return A fingerprint column schema
*/
public static ColumnSchema fingerprintColumn(final String name) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(name))
.targetHeader(nameHelper(name))
.type(ColumnType.FINGERPRINT)
.build();
}
/**
* Helper function for creating a fingerprint column.
*
* @param nameIn The name to use for the source header
* @param nameOut The name to use for the target header
* @return A fingerprint column schema
*/
public static ColumnSchema fingerprintColumn(final String nameIn, final String nameOut) {
return ColumnSchema.builder()
.sourceHeader(nameHelper(nameIn))
.targetHeader(nameHelper(nameOut))
.type(ColumnType.FINGERPRINT)
.build();
}
/**
* Build a simple Row from strings for testing.
*
* @param rowEntries CSV row entries given in key, value, key, value, etc... order a la `Map.of(..)`
* @return A row with the given key/value pairs
*/
public static CsvRow csvRow(final String... rowEntries) {
final CsvRow row = new CsvRow();
for (int i = 0; i < rowEntries.length; i += 2) {
row.putValue(
new ColumnHeader(rowEntries[i]),
new CsvValue(rowEntries[i + 1]));
}
return row;
}
/**
* Build a simple Row from strings for testing; string values are used verbatim.
*
* @param rowEntries CSV row entries given in key, value, key, value, etc... order a la `Map.of(..)`
* @return A row with the given key/value pairs
*/
public static Map<String, String> row(final String... rowEntries) {
final var row = new HashMap<String, String>();
for (int i = 0; i < rowEntries.length; i += 2) {
row.put(rowEntries[i], rowEntries[i + 1]);
}
return row;
}
}
| 2,545 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/C3rSdkPropertiesTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class C3rSdkPropertiesTest {
@Test
public void apiNameVersionTest() {
assertEquals(C3rSdkProperties.VERSION, C3rSdkProperties.API_NAME.version());
}
@Test
public void apiNameNameTest() {
assertEquals("c3r-sdk", C3rSdkProperties.API_NAME.name());
}
@Test
public void externalAndInternalVersionsMatchTest() throws IOException {
// Ensure the version in `version.txt` (used by the build system and any other tooling outside the code base)
// and the version constant in our codebase match.
final String version = Files.readString(Path.of("../version.txt"), StandardCharsets.UTF_8).trim();
assertEquals(version, C3rSdkProperties.VERSION);
}
}
| 2,546 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/EncryptSdkConfigTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.TableSchema;
import lombok.Builder;
import lombok.Getter;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
/**
* Basic configuration settings for encryption.
*/
@Builder
@Getter
public class EncryptSdkConfigTestUtility {
/**
* Schema specification.
*/
@Builder.Default
private TableSchema schema = null;
/**
* Key to use for encryption.
*/
@Builder.Default
private SecretKeySpec key = null;
/**
* Salt to use for key generation.
*/
@Builder.Default
private String salt = null;
/**
* Security related parameters.
*/
@Builder.Default
private ClientSettings settings = ClientSettings.lowAssuranceMode();
/**
* Input file.
*/
@Builder.Default
private String input = null;
/**
* Column headers in the input file.
*/
@Builder.Default
private List<String> inputColumnHeaders = null;
/**
* Column headers to use in the output file.
*/
@Builder.Default
private List<String> outputColumnHeaders = null;
}
| 2,547 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/utils/FileTestUtility.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.utils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* A test utility for creating temporary Path resources for tests that will clean themselves up after execution.
*/
public abstract class FileTestUtility {
/**
* Creates a temporary directory with the prefix "temp" marked with deleteOnExit.
*
* @return A temporary Path
* @throws IOException If the temporary Path cannot be created
*/
public static Path createTempDir() throws IOException {
final Path tempDir = Files.createTempDirectory("temp");
tempDir.toFile().deleteOnExit();
return tempDir;
}
/**
* Creates a temporary file with the prefix "testFile" and suffix ".tmp" marked with deleteOnExit.
*
* @return A temporary Path
* @throws IOException If the temporary Path cannot be created
*/
public static Path createTempFile() throws IOException {
return createTempFile("testFile", ".tmp");
}
/**
* Creates a temporary file with the prefix and suffix provided marked with deleteOnExit.
*
* @param prefix The prefix of the Path to create
* @param suffix The suffix of the Path to create
* @return A temporary Path
* @throws IOException If the temporary Path cannot be created
*/
public static Path createTempFile(final String prefix, final String suffix) throws IOException {
final Path tempDir = createTempDir();
final Path tempFile = Files.createTempFile(tempDir, prefix, suffix);
tempFile.toFile().deleteOnExit();
return tempFile;
}
/**
* Resolves a temporary file with the file name provided marked with deleteOnExit.
*
* @param fileName The name of the Path to resolve
* @return A temporary Path
* @throws IOException If the temporary Path cannot be resolved
*/
public static Path resolve(final String fileName) throws IOException {
return resolve(fileName, createTempDir());
}
/**
* Resolves a temporary file with the prefix and suffix provided marked with deleteOnExit.
*
* @param fileName The name of the Path to resolve
* @param tempDir The Path to use to resolve the temporary file
* @return A temporary Path
*/
private static Path resolve(final String fileName, final Path tempDir) {
final Path tempFile = tempDir.resolve(fileName);
tempFile.toFile().deleteOnExit();
return tempFile;
}
}
| 2,548 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/action/RowUnmarshallerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.action;
import com.amazonaws.c3r.CleartextTransformer;
import com.amazonaws.c3r.FingerprintTransformer;
import com.amazonaws.c3r.SealedTransformer;
import com.amazonaws.c3r.Transformer;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.FileUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_MARSHALLED_DATA_SAMPLE;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RowUnmarshallerTest {
private String output;
private Map<ColumnType, Transformer> transformers;
@BeforeEach
public void setup() throws IOException {
output = FileTestUtility.resolve("output.csv").toString();
final Encryptor encryptor = Encryptor.getInstance(new SymmetricStaticProvider(TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getKey(),
TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getSalt().getBytes(StandardCharsets.UTF_8)));
transformers = new HashMap<>();
transformers.put(ColumnType.CLEARTEXT, new CleartextTransformer());
transformers.put(ColumnType.FINGERPRINT, new FingerprintTransformer(TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getKey(),
TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getSalt().getBytes(StandardCharsets.UTF_8), null, false));
transformers.put(ColumnType.SEALED, new SealedTransformer(encryptor, null));
}
@Test
public void unmarshalTransformerFailureTest() {
final SealedTransformer badCleartextTransformer = mock(SealedTransformer.class);
when(badCleartextTransformer.unmarshal(any())).thenThrow(new C3rRuntimeException("error"));
transformers.put(ColumnType.CLEARTEXT, badCleartextTransformer);
final RowUnmarshaller<CsvValue> unmarshaller = CsvRowUnmarshaller.builder()
.sourceFile(TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getInput())
.targetFile(output)
.transformers(transformers)
.build();
assertThrows(C3rRuntimeException.class, unmarshaller::unmarshal);
}
@Test
public void endToEndUnmarshalTest() {
final RowUnmarshaller<CsvValue> unmarshaller = CsvRowUnmarshaller.builder()
.sourceFile(TEST_CONFIG_MARSHALLED_DATA_SAMPLE.getInput())
.targetFile(output)
.transformers(transformers)
.build();
unmarshaller.unmarshal();
final String file = FileUtil.readBytes(Path.of(output).toAbsolutePath().toString());
assertFalse(file.isBlank());
unmarshaller.close();
}
@Test
public void unmarshallDoesNotModifyHeaders() throws IOException {
final String content =
String.join("\n",
String.join(",", List.of("Alfa", "Bravo ", " CHARLIE ", "\" D E L T A \"")),
String.join(",", List.of("a", " b ", " s e e ", "D")));
final Path csvFile = FileTestUtility.createTempFile();
Files.writeString(csvFile, content, StandardCharsets.UTF_8);
final RowUnmarshaller<CsvValue> unmarshaller = CsvRowUnmarshaller.builder()
.sourceFile(csvFile.toString())
.targetFile(output)
.transformers(transformers)
.build();
unmarshaller.unmarshal();
unmarshaller.close();
try (Stream<String> stream = Files.lines(Path.of(output), StandardCharsets.UTF_8)) {
final List<String> expected =
List.of(String.join(",", List.of("Alfa", "\"Bravo \"", "\" CHARLIE \"", "\" D E L T A \"")),
String.join(",", List.of("a", "b", "\"s e e\"", "D")));
assertEquals(expected, stream.collect(Collectors.toList()));
}
}
}
| 2,549 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/action/RowMarshalPreserveNullTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.action;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.EncryptConfig;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.CsvTestUtility;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.FileUtil;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_6COLUMN;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
// Black-box testing for how the encryption client handles NULL entries in data.
public class RowMarshalPreserveNullTest {
private String output;
private EncryptConfig.EncryptConfigBuilder configBuilder;
private ClientSettings.ClientSettingsBuilder settingsBuilder;
@BeforeEach
public void setup() throws IOException {
output = FileTestUtility.createTempFile("output", ".csv").toString();
settingsBuilder = ClientSettings.builder()
.allowCleartext(true)
.allowDuplicates(false)
.allowJoinsOnColumnsWithDifferentNames(false)
.preserveNulls(false);
configBuilder = EncryptConfig.builder()
.overwrite(true)
.salt("collaboration1234")
.secretKey(new SecretKeySpec(GeneralTestUtility.EXAMPLE_KEY_BYTES, KeyUtil.KEY_ALG))
.targetFile(output)
.tempDir(FileUtil.TEMP_DIR)
.settings(settingsBuilder.build());
}
private void validatePreserveNull(final String inputFile, final String inputNullValue, final String outputNullValue) {
final EncryptConfig config = configBuilder
.sourceFile(inputFile)
.tableSchema(TEST_CONFIG_6COLUMN)
.csvInputNullValue(inputNullValue)
.csvOutputNullValue(outputNullValue)
.settings(settingsBuilder.build())
.build();
final var rawNullString = Objects.requireNonNullElse(outputNullValue, "");
final var marshaller = CsvRowMarshaller.newInstance(config);
marshaller.marshal();
marshaller.close();
final List<String[]> encryptedRows = CsvTestUtility.readContentAsArrays(output, false);
final String[] expectedHeaders =
new String[]{"cleartext", "sealed_none", "sealed_max", "sealed_fixed", "fingerprint_1", "fingerprint_2"};
assertArrayEquals(expectedHeaders, encryptedRows.get(0));
// remove the header, make sure the rows are all still present
encryptedRows.remove(0);
assertEquals(5, encryptedRows.size());
// check that the cleartext row is null, but the others are or are not
// based on `preserveNulls`
final Set<String> nonNullValues = new HashSet<>();
for (String[] row : encryptedRows) {
for (int j = 0; j < expectedHeaders.length; j++) {
if (config.getSettings().isPreserveNulls() || j == 0) {
assertEquals(rawNullString, row[j]);
} else {
assertNotEquals(rawNullString, row[j]);
}
if (!Objects.equals(row[j], rawNullString)) {
nonNullValues.add(row[j]);
}
}
}
// ensure we got the expected number of unique, non-null values
if (config.getSettings().isPreserveNulls()) {
// preserve nulls means everything is null and thus no non-null values!
assertEquals(0, nonNullValues.size());
} else {
// if `preserveNULLs == false`
// then there are 25 non-null entries (5 encrypted columns, 5 rows)
assertEquals(25, nonNullValues.size());
}
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesTrueTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/null5by6.csv", null, null);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesFalseTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/null5by6.csv", null, null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesTrueTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/null5by6.csv", null, null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesFalseTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/null5by6.csv", null, null);
}
@Test
public void validatePreserveNullTrueAllowDuplicatesFalseTest() {
configBuilder.sourceFile("../samples/csv/null5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
// if allowDuplicates = false and preserveNULLs = true,
// NULL does not count as a value. So multiple NULL values are fine.
settingsBuilder.preserveNulls(true);
settingsBuilder.allowDuplicates(false);
final var config = configBuilder.settings(settingsBuilder.build()).build();
final var marshaller = CsvRowMarshaller.newInstance(config);
assertDoesNotThrow(marshaller::marshal);
marshaller.close();
}
@Test
public void validatePreserveNullFalseAllowDuplicatesFalseTest() {
configBuilder.sourceFile("../samples/csv/null5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowDuplicates(false);
final var marshaller = CsvRowMarshaller.newInstance(configBuilder.build());
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesTrueCustomEmptyNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/null5by6.csv", "", null);
validatePreserveNull("../samples/csv/empty5by6.csv", "\"\"", null);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesFalseCustomEmptyNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/null5by6.csv", "", null);
validatePreserveNull("../samples/csv/empty5by6.csv", "\"\"", null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesTrueCustomEmptyNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/null5by6.csv", "", null);
validatePreserveNull("../samples/csv/empty5by6.csv", "\"\"", null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesFalseCustomEmptyNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/null5by6.csv", "", null);
validatePreserveNull("../samples/csv/empty5by6.csv", "\"\"", null);
}
@Test
public void validatePreserveNullTrueAllowDuplicatesFalseCustomEmptyNullTest() {
configBuilder.sourceFile("../samples/csv/null5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("");
// if allowDuplicates = false and preserveNULLs = true,
// NULL does not count as a value. So multiple NULL values are fine.
settingsBuilder.preserveNulls(true);
settingsBuilder.allowDuplicates(false);
var config = configBuilder.settings(settingsBuilder.build()).build();
var marshaller = CsvRowMarshaller.newInstance(config);
assertDoesNotThrow(marshaller::marshal);
marshaller.close();
configBuilder.sourceFile("../samples/csv/empty5by6.csv").csvInputNullValue("\"\"");
config = configBuilder.build();
marshaller = CsvRowMarshaller.newInstance(config);
assertDoesNotThrow(marshaller::marshal);
marshaller.close();
}
@Test
public void validatePreserveNullFalseAllowDuplicatesFalseCustomEmptyNullTest() {
configBuilder.sourceFile("../samples/csv/null5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("");
settingsBuilder.preserveNulls(false);
settingsBuilder.allowDuplicates(false);
final var marshaller = CsvRowMarshaller.newInstance(configBuilder.build());
assertThrows(C3rRuntimeException.class, marshaller::marshal);
configBuilder.sourceFile("../samples/csv/empty5by6.csv");
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesTrueCustomNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", null);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesFalseCustomNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesTrueCustomNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", null);
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesFalseCustomNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", null);
}
@Test
public void validatePreserveNullTrueAllowDuplicatesFalseCustomNullTest() {
configBuilder.sourceFile("../samples/csv/customNull5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("null");
// if allowDuplicates = false and preserveNULLs = true,
// NULL does not count as a value. So multiple NULL values are fine.
settingsBuilder.preserveNulls(true);
settingsBuilder.allowDuplicates(false);
final var config = configBuilder.settings(settingsBuilder.build()).build();
final var marshaller = CsvRowMarshaller.newInstance(config);
assertDoesNotThrow(marshaller::marshal);
marshaller.close();
}
@Test
public void validatePreserveNullFalseAllowDuplicatesFalseCustomNullTest() {
configBuilder.sourceFile("../samples/csv/customNull5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("/null");
settingsBuilder.preserveNulls(false);
settingsBuilder.allowDuplicates(false);
final var marshaller = CsvRowMarshaller.newInstance(configBuilder.build());
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesTrueCustomOutputNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", "null");
}
@Test
public void validatePreserveNullTrueAllowJoinsOnColumnsWithDifferentNamesFalseCustomOutputNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(true);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", "null");
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesTrueCustomOutputNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(true);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", "null");
}
@Test
public void validatePreserveNullFalseAllowJoinsOnColumnsWithDifferentNamesFalseCustomOutputNullTest() {
settingsBuilder.allowDuplicates(true);
settingsBuilder.preserveNulls(false);
settingsBuilder.allowJoinsOnColumnsWithDifferentNames(false);
validatePreserveNull("../samples/csv/customNull5by6.csv", "null", "null");
}
@Test
public void validatePreserveNullTrueAllowDuplicatesFalseCustomOutputNullTest() {
configBuilder.sourceFile("../samples/csv/customNull5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("null");
configBuilder.csvOutputNullValue("null");
// if allowDuplicates = false and preserveNULLs = true,
// NULL does not count as a value. So multiple NULL values are fine.
settingsBuilder.preserveNulls(true);
settingsBuilder.allowDuplicates(false);
final var config = configBuilder.settings(settingsBuilder.build()).build();
final var marshaller = CsvRowMarshaller.newInstance(config);
assertDoesNotThrow(marshaller::marshal);
marshaller.close();
}
@Test
public void validatePreserveNullFalseAllowDuplicatesFalseCustomOutputNullTest() {
configBuilder.sourceFile("../samples/csv/customNull5by6.csv");
configBuilder.tableSchema(TEST_CONFIG_6COLUMN);
configBuilder.csvInputNullValue("null");
configBuilder.csvOutputNullValue("null");
settingsBuilder.preserveNulls(false);
settingsBuilder.allowDuplicates(false);
final var marshaller = CsvRowMarshaller.newInstance(configBuilder.build());
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
}
| 2,550 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/action/CsvRowUnmarshallerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.action;
import com.amazonaws.c3r.config.DecryptConfig;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.utils.FileTestUtility;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class CsvRowUnmarshallerTest {
@Test
public void validateRejectNonCsvFormatTest() throws IOException {
final String output = FileTestUtility.resolve("endToEndMarshalOut.unknown").toString();
final var configBuilder = DecryptConfig.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.fileFormat(FileFormat.CSV)
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.overwrite(true);
assertThrows(C3rIllegalArgumentException.class, () ->
CsvRowUnmarshaller.newInstance(configBuilder.fileFormat(FileFormat.PARQUET).build()));
assertDoesNotThrow(() ->
CsvRowUnmarshaller.newInstance(configBuilder.fileFormat(FileFormat.CSV).build()));
}
}
| 2,551 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/action/RowMarshallerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.action;
import com.amazonaws.c3r.CleartextTransformer;
import com.amazonaws.c3r.FingerprintTransformer;
import com.amazonaws.c3r.SealedTransformer;
import com.amazonaws.c3r.Transformer;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnInsight;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.DecryptConfig;
import com.amazonaws.c3r.config.EncryptConfig;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.data.CsvRowFactory;
import com.amazonaws.c3r.data.CsvValue;
import com.amazonaws.c3r.data.Row;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.io.CsvRowReader;
import com.amazonaws.c3r.io.CsvRowWriter;
import com.amazonaws.c3r.io.CsvTestUtility;
import com.amazonaws.c3r.io.RowReader;
import com.amazonaws.c3r.io.RowReaderTestUtility;
import com.amazonaws.c3r.io.RowWriter;
import com.amazonaws.c3r.io.SqlRowReader;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.FileUtil;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.amazonaws.c3r.utils.GeneralTestUtility.CONFIG_SAMPLE;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE;
import static com.amazonaws.c3r.utils.GeneralTestUtility.cleartextColumn;
import static com.amazonaws.c3r.utils.GeneralTestUtility.sealedColumn;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class RowMarshallerTest {
private String tempDir;
private String output;
private Map<ColumnType, Transformer> transformers;
@BeforeEach
public void setup() throws IOException {
tempDir = FileTestUtility.createTempDir().toString();
output = FileTestUtility.resolve("output.csv").toString();
final Encryptor encryptor = Encryptor.getInstance(new SymmetricStaticProvider(TEST_CONFIG_DATA_SAMPLE.getKey(),
TEST_CONFIG_DATA_SAMPLE.getSalt().getBytes(StandardCharsets.UTF_8)));
transformers = new HashMap<>();
transformers.put(ColumnType.CLEARTEXT, new CleartextTransformer());
transformers.put(ColumnType.FINGERPRINT, new FingerprintTransformer(TEST_CONFIG_DATA_SAMPLE.getKey(),
TEST_CONFIG_DATA_SAMPLE.getSalt().getBytes(StandardCharsets.UTF_8), TEST_CONFIG_DATA_SAMPLE.getSettings(), false));
transformers.put(ColumnType.SEALED, new SealedTransformer(encryptor, TEST_CONFIG_DATA_SAMPLE.getSettings()));
}
@Test
public void csvRowMarshallerNewInstanceTest() {
final var marshaller = CsvRowMarshaller.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.tempDir(tempDir)
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.schema(TEST_CONFIG_DATA_SAMPLE.getSchema())
.transforms(transformers).build();
assertNotNull(marshaller);
// compare input as sets since ordering isn't guaranteed and duplicates can exist
// via one-to-many mappings
final var expected = TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns().stream()
.map(ColumnSchema::getSourceHeader).map(ColumnHeader::toString).sorted().collect(Collectors.toList());
final var actual = marshaller.getInputReader().getHeaders().stream()
.map(ColumnHeader::toString).sorted().collect(Collectors.toList());
assertTrue(expected.removeAll(actual));
assertTrue(expected.isEmpty());
assertEquals(Set.of(TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns().stream()
.map(ColumnSchema::getTargetHeader).map(ColumnHeader::toString).sorted().toArray()),
Set.of(marshaller.getOutputWriter().getHeaders().stream().map(ColumnHeader::toString).sorted().toArray()));
assertEquals(Set.of(marshaller.getColumnInsights().stream()
.map(ColumnSchema::getTargetHeader).map(ColumnHeader::toString).sorted().toArray()),
Set.of(marshaller.getOutputWriter().getHeaders().stream().map(ColumnHeader::toString).sorted().toArray()));
}
@Test
@SuppressWarnings("unchecked")
public void respectPadTypesTest() {
final RowWriter<CsvValue> rowWriter = (RowWriter<CsvValue>) mock(RowWriter.class);
final RowMarshaller<CsvValue> marshaller = RowMarshaller.<CsvValue>builder()
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.schema(TEST_CONFIG_DATA_SAMPLE.getSchema())
.inputReader(CsvRowReader.builder().sourceName(TEST_CONFIG_DATA_SAMPLE.getInput()).build())
.rowFactory(new CsvRowFactory())
.outputWriter(rowWriter)
.transformers(transformers)
.tempDir(tempDir)
.build();
marshaller.loadInput();
final Map<ColumnHeader, ColumnInsight> targetHeaderMappedColumnInsights = marshaller.getColumnInsights().stream()
.collect(Collectors.toMap(ColumnSchema::getTargetHeader, Function.identity()));
final var notesTargetHeader = new ColumnHeader("notes");
final int longestNoteValueByteLength = 60;
if (!FileUtil.isWindows()) {
// NOTE 1: Spot check our length ONLY on *nix system CI. On Windows the length of Java string literals appearing
// in tests like this be encoded differently. This only matters for tests like this storing
// string literals - it does not matter when we read in a file from disk that is UTF8.
// NOTE 2: Importantly, the longest `Notes` string has a unicode character `é` (U+00E9) that takes two bytes
// in UTF8 (0xC3 0xA9), and so relying on non-UTF8-byte-length notions of a string value's "length"
// can lead to errors on UTF8 data containing such values.
assertEquals(
longestNoteValueByteLength,
"This is a really long noté that could really be a paragraph"
.getBytes(StandardCharsets.UTF_8).length);
}
assertEquals(
longestNoteValueByteLength,
targetHeaderMappedColumnInsights.get(notesTargetHeader).getMaxValueLength());
}
@Test
public void loadInputTest() {
final RowMarshaller<CsvValue> marshaller = CsvRowMarshaller.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.tempDir(tempDir)
.settings(ClientSettings.lowAssuranceMode())
.schema(TEST_CONFIG_DATA_SAMPLE.getSchema())
.transforms(transformers).build();
marshaller.loadInput();
final SqlRowReader<CsvValue> reader = new SqlRowReader<>(
marshaller.getColumnInsights(),
marshaller.getNonceHeader(),
new CsvRowFactory(),
marshaller.getSqlTable());
// Ensure columns were encrypted/HMACed where appropriate.
while (reader.hasNext()) {
final Row<CsvValue> row = reader.next();
for (ColumnSchema columnSchema : TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns()) {
if (columnSchema.getType() == ColumnType.CLEARTEXT) {
continue; // Cleartext columns weren't touched.
}
final CsvValue value = row.getValue(columnSchema.getTargetHeader());
if (value.getBytes() == null) {
continue; // Null values weren't touched
}
final Transformer transformer = transformers.get(columnSchema.getType());
assertTrue(Transformer.hasDescriptor(transformer, value.getBytes()));
}
}
assertNotEquals(0, marshaller.getInputReader().getReadRowCount()); // Ensure data was read
assertEquals(marshaller.getInputReader().getReadRowCount(), reader.getReadRowCount()); // Ensure table data matches data read
}
@Test
public void loadInputOmitsColumnsNotInConfigTest() {
final ColumnSchema toOmit = TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns().get(0);
final List<ColumnSchema> columnSchemas = new ArrayList<>(TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns());
columnSchemas.remove(toOmit);
final TableSchema tableSchema = new MappedTableSchema(columnSchemas);
final RowMarshaller<CsvValue> marshaller = CsvRowMarshaller.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.tempDir(tempDir)
.settings(ClientSettings.lowAssuranceMode())
.schema(tableSchema)
.transforms(transformers).build();
marshaller.loadInput();
final SqlRowReader<CsvValue> reader = new SqlRowReader<>(
marshaller.getColumnInsights(),
marshaller.getNonceHeader(),
new CsvRowFactory(),
marshaller.getSqlTable());
while (reader.hasNext()) {
assertFalse(reader.next().hasColumn(toOmit.getTargetHeader()));
}
assertNotEquals(0, marshaller.getInputReader().getReadRowCount()); // Ensure data was read
assertEquals(marshaller.getInputReader().getReadRowCount(), reader.getReadRowCount()); // Ensure table data matches data read
}
@Test
public void missingInputColumnsThrowsTest() {
final ColumnSchema missingCol = ColumnSchema.builder()
.sourceHeader(new ColumnHeader("missing_column"))
.type(ColumnType.CLEARTEXT).build();
final List<ColumnSchema> columnSchemas = new ArrayList<>(TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns());
columnSchemas.add(missingCol);
final TableSchema tableSchema = new MappedTableSchema(columnSchemas);
assertThrows(C3rRuntimeException.class, () -> CsvRowMarshaller.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.tempDir(tempDir)
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.schema(tableSchema)
.transforms(transformers).build());
}
@Test
public void marshalTransformerFailureTest() {
final SealedTransformer badSealedTransformer = mock(SealedTransformer.class);
when(badSealedTransformer.marshal(any(), any())).thenThrow(new C3rRuntimeException("error"));
transformers.put(ColumnType.SEALED, badSealedTransformer);
final RowWriter<CsvValue> rowWriter = CsvRowWriter.builder()
.targetName(output)
.headers(CONFIG_SAMPLE.getColumns().stream().map(ColumnSchema::getTargetHeader).collect(Collectors.toList()))
.build();
final RowMarshaller<CsvValue> marshaller = RowMarshaller.<CsvValue>builder()
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.schema(TEST_CONFIG_DATA_SAMPLE.getSchema())
.inputReader(CsvRowReader.builder().sourceName(TEST_CONFIG_DATA_SAMPLE.getInput()).build())
.rowFactory(new CsvRowFactory())
.outputWriter(rowWriter)
.transformers(transformers)
.tempDir(tempDir)
.build();
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
@Test
public void endToEndMarshallingTest() {
final RowWriter<CsvValue> rowWriter = CsvRowWriter.builder()
.targetName(output)
.headers(TEST_CONFIG_DATA_SAMPLE.getSchema().getColumns().stream().map(ColumnSchema::getTargetHeader)
.collect(Collectors.toList()))
.build();
final RowMarshaller<CsvValue> marshaller = RowMarshaller.<CsvValue>builder()
.settings(TEST_CONFIG_DATA_SAMPLE.getSettings())
.schema(TEST_CONFIG_DATA_SAMPLE.getSchema())
.inputReader(CsvRowReader.builder().sourceName(TEST_CONFIG_DATA_SAMPLE.getInput()).build())
.rowFactory(new CsvRowFactory())
.outputWriter(rowWriter)
.transformers(transformers)
.tempDir(tempDir)
.build();
marshaller.marshal();
final String file = FileUtil.readBytes(output);
assertFalse(file.isBlank());
marshaller.close();
}
@Test
public void roundTripCsvTest() throws IOException {
final var headers = List.of("FirstName", "LastName", "Address", "City", "State", "PhoneNumber", "Title", "Level", "Notes");
final var columnSchemas = new ArrayList<ColumnSchema>();
for (var header : headers) {
columnSchemas.add(cleartextColumn(header));
columnSchemas.add(sealedColumn(header, header + "_sealed"));
columnSchemas.add(sealedColumn(header, header + "_fixed", PadType.FIXED, 100));
columnSchemas.add(sealedColumn(header, header + "_max", PadType.MAX, 50));
}
final TableSchema schema = new MappedTableSchema(columnSchemas);
final String ciphertextFile = FileTestUtility.resolve("roundTripCsvCipherOut.csv").toString();
final String cleartextFile = FileTestUtility.resolve("roundTripCsvPlainOut.csv").toString();
final EncryptConfig encryptConfig = EncryptConfig.builder()
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(ciphertextFile)
.tempDir(tempDir)
.overwrite(true)
.csvInputNullValue(null)
.csvOutputNullValue(null)
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.settings(ClientSettings.builder()
.allowCleartext(true)
.allowDuplicates(false)
.allowJoinsOnColumnsWithDifferentNames(false)
.preserveNulls(false)
.build())
.tableSchema(schema)
.build();
final RowMarshaller<CsvValue> rowMarshaller = CsvRowMarshaller.newInstance(encryptConfig);
rowMarshaller.marshal();
rowMarshaller.close();
final var originalData = CsvTestUtility.readRows(TEST_CONFIG_DATA_SAMPLE.getInput()).stream()
.sorted(Comparator.comparing(v -> v.get("FirstName")))
.collect(Collectors.toList());
final var cipherData = CsvTestUtility.readRows(ciphertextFile).stream()
.sorted(Comparator.comparing(v -> v.get("firstname")))
.collect(Collectors.toList());
assertEquals(originalData.size(), cipherData.size());
for (int i = 0; i < originalData.size(); i++) {
final var originalLine = originalData.get(i);
final var cipherLine = cipherData.get(i);
assertEquals(originalLine.size() * 4, cipherLine.size());
for (String s : headers) {
final var original = originalLine.get(s);
final var cipherCleartext = cipherLine.get(new ColumnHeader(s).toString());
assertEquals(original, cipherCleartext);
final var cipherSealed = cipherLine.get(s + "_sealed");
assertNotEquals(original, cipherSealed);
final var cipherFixed = cipherLine.get(s + "_fixed");
assertNotEquals(original, cipherFixed);
final var cipherMax = cipherLine.get(s + "_max");
assertNotEquals(original, cipherMax);
}
}
final DecryptConfig decryptConfig = DecryptConfig.builder()
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.sourceFile(ciphertextFile)
.targetFile(cleartextFile)
.overwrite(true)
.csvInputNullValue(null)
.csvOutputNullValue(null)
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.failOnFingerprintColumns(true)
.build();
final RowUnmarshaller<CsvValue> rowUnmarshaller = CsvRowUnmarshaller.newInstance(decryptConfig);
rowUnmarshaller.unmarshal();
rowUnmarshaller.close();
final var finalData =
CsvTestUtility.readRows(cleartextFile).stream().sorted(Comparator.comparing(v -> v.get("firstname")))
.collect(Collectors.toList());
assertEquals(originalData.size(), finalData.size());
for (int i = 0; i < originalData.size(); i++) {
final var originalLine = originalData.get(i);
final var resultLine = finalData.get(i);
assertEquals(originalLine.size() * 4, resultLine.size());
for (String s : headers) {
final var resultHeader = new ColumnHeader(s).toString();
final var original = originalLine.get(s);
final var result = resultLine.get(resultHeader);
assertEquals(original, result);
final var cipherSealed = resultLine.get(resultHeader + "_sealed");
assertEquals(original, cipherSealed);
final var cipherFixed = resultLine.get(resultHeader + "_fixed");
assertEquals(original, cipherFixed);
final var cipherMax = resultLine.get(resultHeader + "_max");
assertEquals(original, cipherMax);
}
}
}
@Test
@SuppressWarnings("unchecked")
public void loadManyRowsTest() {
final RowReader<CsvValue> mockReader = RowReaderTestUtility.getMockCsvReader(
List.of(new ColumnHeader("cleartext")),
(header) -> header + " value",
RowMarshaller.LOG_ROW_UPDATE_FREQUENCY - RowMarshaller.INSERTS_PER_COMMIT, // read rows
RowMarshaller.LOG_ROW_UPDATE_FREQUENCY + 1 // total rows
);
final RowWriter<CsvValue> mockWriter = (RowWriter<CsvValue>) mock(RowWriter.class);
final TableSchema schema = new MappedTableSchema(List.of(cleartextColumn("cleartext")));
final RowMarshaller<CsvValue> marshaller = RowMarshaller.<CsvValue>builder()
.inputReader(mockReader)
.outputWriter(mockWriter)
.tempDir(FileUtil.TEMP_DIR)
.schema(schema)
.rowFactory(new CsvRowFactory())
.transformers(transformers)
.settings(ClientSettings.lowAssuranceMode())
.build();
assertDoesNotThrow(marshaller::marshal);
}
// Test if duplicate entries in a fingerprint column throws an error when expected.
@SuppressWarnings("unchecked")
private void validateDuplicateEnforcement(final Function<ColumnHeader, String> valueProducer,
final boolean allowDuplicates) {
final RowReader<CsvValue> mockReader = RowReaderTestUtility.getMockCsvReader(
List.of(new ColumnHeader("some fingerprint column")),
valueProducer,
0, // read rows
10 // total rows
);
final var clientSettings = ClientSettings.builder()
.allowDuplicates(allowDuplicates)
.preserveNulls(false)
.allowJoinsOnColumnsWithDifferentNames(true)
.allowCleartext(true)
.build();
final RowWriter<CsvValue> mockWriter = (RowWriter<CsvValue>) mock(RowWriter.class);
final TableSchema schema = new MappedTableSchema(List.of(GeneralTestUtility.fingerprintColumn("some fingerprint column")));
final RowMarshaller<CsvValue> marshaller = RowMarshaller.<CsvValue>builder()
.inputReader(mockReader)
.outputWriter(mockWriter)
.tempDir(FileUtil.TEMP_DIR)
.schema(schema)
.rowFactory(new CsvRowFactory())
.transformers(transformers)
.settings(clientSettings)
.build();
if (allowDuplicates) {
assertDoesNotThrow(marshaller::marshal);
} else {
assertThrows(C3rRuntimeException.class, marshaller::marshal);
}
}
@Test
public void validateDuplicateEnforcementTest() {
// check that multiple duplicate fingerprint values get rejected
validateDuplicateEnforcement((header) -> "duplicate value", true);
validateDuplicateEnforcement((header) -> "duplicate value", false);
// check that multiple preserved null values get rejected
validateDuplicateEnforcement((header) -> null, true);
validateDuplicateEnforcement((header) -> null, false);
}
}
| 2,552 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/action/CsvRowMarshallerTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.action;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.EncryptConfig;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import nl.altindag.log.LogCaptor;
import nl.altindag.log.model.LogEvent;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static com.amazonaws.c3r.utils.GeneralTestUtility.TEST_CONFIG_DATA_SAMPLE;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class CsvRowMarshallerTest {
@Test
public void validateRejectNonCsvFormatTest() throws IOException {
final String tempDir = FileTestUtility.createTempDir().toString();
final String output = FileTestUtility.resolve("endToEndMarshalOut.unknown").toString();
final var configBuilder = EncryptConfig.builder()
.sourceFile(TEST_CONFIG_DATA_SAMPLE.getInput())
.targetFile(output)
.secretKey(TEST_CONFIG_DATA_SAMPLE.getKey())
.salt(TEST_CONFIG_DATA_SAMPLE.getSalt())
.tempDir(tempDir)
.settings(ClientSettings.lowAssuranceMode())
.tableSchema(GeneralTestUtility.CONFIG_SAMPLE)
.overwrite(true);
assertThrows(C3rIllegalArgumentException.class, () ->
CsvRowMarshaller.newInstance(configBuilder.fileFormat(FileFormat.PARQUET).build()));
assertDoesNotThrow(() ->
CsvRowMarshaller.newInstance(configBuilder.fileFormat(FileFormat.CSV).build()));
}
@Test
public void validateWarnCustomNullsWithNoTargetCleartext() {
final List<LogEvent> logEvents;
final List<ColumnSchema> columnSchemas = new ArrayList<>();
columnSchemas.add(ColumnSchema.builder()
.sourceHeader(new ColumnHeader("source"))
.targetHeader(new ColumnHeader("target"))
.type(ColumnType.SEALED)
.pad(Pad.DEFAULT)
.build());
final TableSchema schema = new MappedTableSchema(columnSchemas);
try (LogCaptor logCaptor = LogCaptor.forName("ROOT")) {
CsvRowMarshaller.validate("custom null value", schema);
logEvents = logCaptor.getLogEvents();
}
final LogEvent warningEvent = logEvents.get(logEvents.size() - 1); // The last message is the warning
final String outputMessage = warningEvent.getFormattedMessage();
assertTrue(outputMessage.contains("Received a custom output null value `custom null value`, but no cleartext columns were found. " +
"It will be ignored."));
}
}
| 2,553 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/ValidationTypeAdapterFactoryTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ValidationTypeAdapterFactoryTest {
/*
* This class is used when we want to test the same value entered as a JSON string and entered programmatically.
* The same behavior is expected for the jsonValue and the javaValue.
*/
private static final class JavaJsonPair {
private final String jsonValue;
private final Object javaValue;
/*
* Create a schema parameter, store it as an object along with the equivalent JSON string.
* The JSON string should be insertable inside a larger JSON schema definition without modification
* (i.e., no trailing commas or scoping).
*/
private JavaJsonPair(final String jsonValue, final Object javaValue) {
this.jsonValue = jsonValue;
this.javaValue = javaValue;
}
}
// What follows are all the basic valid options for each schema parameter
// Source Column Headers
private final JavaJsonPair src = new JavaJsonPair(
"\"sourceHeader\":\"source\"", new ColumnHeader("source"));
// Target Column Headers
private final JavaJsonPair tgt = new JavaJsonPair(
"\"targetHeader\":\"target\"", new ColumnHeader("Target"));
// Pad values
private final JavaJsonPair padFixed = new JavaJsonPair(
"\"pad\":{ \"type\":\"fixed\", \"length\":32 }", Pad.builder().type(PadType.FIXED).length(32).build());
private final JavaJsonPair padMax = new JavaJsonPair(
"\"pad\":{ \"type\":\"max\", \"length\":3200 }", Pad.builder().type(PadType.MAX).length(3200).build());
private final JavaJsonPair padNone = new JavaJsonPair(
"\"pad\":{ \"type\":\"none\" }", Pad.DEFAULT);
// Column types
private final JavaJsonPair typeFingerprint = new JavaJsonPair(
"\"type\":\"fingerprint\"", ColumnType.FINGERPRINT);
private final JavaJsonPair typeSealed = new JavaJsonPair(
"\"type\":\"sealed\"", ColumnType.SEALED);
private final JavaJsonPair typeCleartext = new JavaJsonPair(
"\"type\":\"cleartext\"", ColumnType.CLEARTEXT);
// JSON field separator
private final String sep = ",\n";
private ColumnSchema decodeColumn(final String content) {
return GsonUtil.fromJson(content, ColumnSchema.class);
}
/*
* When creating a source column header via a JSON configuration file, white space should be removed from the start and end of the
* string. If the remaining string is empty, the value should be rejected.
*/
@Test
public void whiteSpaceInJsonSourceHeaderTest() {
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{ \"sourceHeader\":\"\", \"type\":\"fingerprint\" }"
));
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{ \"sourceHeader\":\" \", \"type\":\"fingerprint\" }"
));
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{ \"sourceHeader\":\"\t\t\", \"type\":\"fingerprint\" }"
));
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{ \"sourceHeader\":\"\t \", \"type\":\"fingerprint\" }"
));
final ColumnSchema c = decodeColumn(
"{ \"sourceHeader\":\" test column \t\", \"type\":\"fingerprint\" }"
);
assertEquals(new ColumnHeader("test column"), c.getSourceHeader());
}
/*
* When creating a target column header and the value is specified, the leading and trailing white space should be removed. If the
* result is empty, alert the user with an error as they may have intended to have a value. If there is a non-empty value, use that
* as the target column header name. Even if the user specifies the empty string, we will still throw en error because they actually
* wrote in a value. We only inherit from the source column header when the target column header is unspecified.
*/
@Test
public void whiteSpaceInJsonTargetHeaderTest() {
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + "\"targetHeader\":\" \"" + sep + typeFingerprint + "\n}"));
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + "\"targetHeader\":\"\"" + sep + typeFingerprint + "\n}"));
final ColumnSchema c = decodeColumn(
"{\n" + src.jsonValue + sep + "\"targetHeader\":\"test\t \"" + sep + typeFingerprint.jsonValue + "\n}");
assertEquals(new ColumnHeader("test"), c.getTargetHeader());
}
// Verify that the target header value is respected if specified.
@Test
public void checkTargetHeaderIsSpecifiedIsAcceptedTest() {
// Test specified value for target header
final ColumnSchema c1java =
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padMax.javaValue).type((ColumnType) typeSealed.javaValue).build();
assertEquals(tgt.javaValue, c1java.getTargetHeader());
assertNotEquals(src.javaValue, c1java.getTargetHeader());
final ColumnSchema c1json = decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padMax.jsonValue + sep +
typeSealed.jsonValue + "\n}");
assertEquals(c1java.getTargetHeader(), c1json.getTargetHeader());
assertNotEquals(c1json.getSourceHeader(), c1json.getTargetHeader());
}
// Confirm that Sealed accepts all pad types, does not set a default value for the padding and doesn't accept unspecified padding.
@Test
public void checkColumnPadRequiredWithSealedTypeTest() {
// Fixed Pad is accepted
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema =
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padFixed.javaValue).type((ColumnType) typeSealed.javaValue).build();
assertEquals(padFixed.javaValue, columnSchema.getPad());
});
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema = decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padFixed.jsonValue + sep +
typeSealed.jsonValue + "\n}");
assertEquals(padFixed.javaValue, columnSchema.getPad());
});
// Max Pad
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema =
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padMax.javaValue).type((ColumnType) typeSealed.javaValue).build();
assertEquals(padMax.javaValue, columnSchema.getPad());
});
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema = decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padMax.jsonValue + sep +
typeSealed.jsonValue + "\n}");
assertEquals(padMax.javaValue, columnSchema.getPad());
});
// No Pad
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema =
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padNone.javaValue).type((ColumnType) typeSealed.javaValue).build();
assertEquals(padNone.javaValue, columnSchema.getPad());
});
assertDoesNotThrow(() -> {
final ColumnSchema columnSchema = decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padNone.jsonValue + sep +
typeSealed.jsonValue + "\n}");
assertEquals(padNone.javaValue, columnSchema.getPad());
});
// Check that pad must be specified for sealed
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.type((ColumnType) typeSealed.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + typeSealed.jsonValue + "\n}"));
}
// Test that other column types do not accept a pad type, including none.
@Test
public void padLengthMustNotBeSpecifiedForNonSealedTypesTest() {
// Check that pad must be unspecified for Fingerprint type
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padFixed.javaValue).type((ColumnType) typeFingerprint.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padFixed.jsonValue + sep +
typeFingerprint.jsonValue + "\n}"));
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padNone.javaValue).type((ColumnType) typeFingerprint.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padNone.jsonValue + sep +
typeFingerprint.jsonValue + "\n}"));
assertDoesNotThrow(() -> ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue)
.targetHeader((ColumnHeader) tgt.javaValue).type((ColumnType) typeFingerprint.javaValue).build());
assertDoesNotThrow(() ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + typeFingerprint.jsonValue + "\n}"));
// Check that pad must be unspecified for Cleartext type
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padFixed.javaValue).type((ColumnType) typeCleartext.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padFixed.jsonValue + sep +
typeCleartext.jsonValue + "\n}"));
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padNone.javaValue).type((ColumnType) typeCleartext.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padNone.jsonValue + sep +
typeCleartext.jsonValue + "\n}"));
assertDoesNotThrow(() -> ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue)
.targetHeader((ColumnHeader) tgt.javaValue).type((ColumnType) typeCleartext.javaValue).build());
assertDoesNotThrow(() ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + typeCleartext.jsonValue + "\n}"));
}
// Verify that a default value for column type is not set, and it must always be specified.
@Test
public void columnTypeMustBeSpecifiedTest() {
// Test type unspecified is invalid
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padFixed.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padFixed.jsonValue + "\n}"));
assertThrows(C3rIllegalArgumentException.class, () ->
ColumnSchema.builder().sourceHeader((ColumnHeader) src.javaValue).targetHeader((ColumnHeader) tgt.javaValue)
.pad((Pad) padNone.javaValue).build());
assertThrows(C3rIllegalArgumentException.class, () ->
decodeColumn(
"{\n" + src.jsonValue + sep + tgt.jsonValue + sep + padNone.jsonValue + "\n}"));
}
}
| 2,554 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/PositionalTableSchemaTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.PositionalTableSchema;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.FileTestUtility;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
// Test class for Positional Schema specific portions of JSON parsing.
public final class PositionalTableSchemaTypeAdapterTest implements TableSchemaCommonTypeAdapterTestInterface {
// Positional cleartext column
private static final KnownPartsToCompare CS_1 = new KnownPartsToCompare("c1", ColumnType.CLEARTEXT, null);
// Pretty printed JSON string for {@code cs1}
private static final String C_1 = writePrettyPrintJson(CS_1.target.toString(), CS_1.colType.toString(), CS_1.padType, CS_1.padLen);
// Positional fingerprint column
private static final KnownPartsToCompare CS_2 = new KnownPartsToCompare("c2", ColumnType.FINGERPRINT, null);
// Pretty printed JSON string for {@code cs2}
private static final String C_2 = writePrettyPrintJson(CS_2.target.toString(), CS_2.colType.toString(), CS_2.padType, CS_2.padLen);
// Positional sealed column with no padding
private static final KnownPartsToCompare CS_3 = new KnownPartsToCompare("c3", ColumnType.SEALED, Pad.DEFAULT);
// Pretty printed JSON string for {@code cs3}
private static final String C_3 = writePrettyPrintJson(CS_3.target.toString(), CS_3.colType.toString(), CS_3.padType, CS_3.padLen);
// Positional sealed column with max padding of 100
private static final KnownPartsToCompare CS_4 = new KnownPartsToCompare("c4", ColumnType.SEALED,
Pad.builder().type(PadType.MAX).length(100).build());
// Pretty printed JSON string for {@code cs4}
private static final String C_4 = writePrettyPrintJson(CS_4.target.toString(), CS_4.colType.toString(), CS_4.padType, CS_4.padLen);
// Positional sealed column with fixed padding of 50
private static final KnownPartsToCompare CS_5 = new KnownPartsToCompare("c5", ColumnType.SEALED,
Pad.builder().type(PadType.FIXED).length(50).build());
// Pretty printed JSON string for {@code cs5}
private static final String C_5 = writePrettyPrintJson(CS_5.target.toString(), CS_5.colType.toString(), CS_5.padType, CS_5.padLen);
// Schema used for several I/O tests where a fixed value is useful
private static final List<List<ColumnSchema>> SCHEMA_FOR_WRITE_TESTS = List.of(
List.of(
ColumnSchema.builder().targetHeader(new ColumnHeader("c1")).type(ColumnType.CLEARTEXT).build(),
ColumnSchema.builder().targetHeader(new ColumnHeader("c2")).type(ColumnType.FINGERPRINT).build()
),
List.of(
ColumnSchema.builder().targetHeader(new ColumnHeader("c3")).pad(Pad.DEFAULT).type(ColumnType.SEALED).build(),
ColumnSchema.builder().targetHeader(new ColumnHeader("c4"))
.pad(Pad.builder().type(PadType.MAX).length(100).build()).type(ColumnType.SEALED).build(),
ColumnSchema.builder().targetHeader(new ColumnHeader("c5"))
.pad(Pad.builder().type(PadType.FIXED).length(50).build()).type(ColumnType.SEALED).build()
)
);
// Class to hold known values for a positional JSON string (we won't know source header until it's put in a specific column).
private static class KnownPartsToCompare {
private final ColumnHeader target;
private final ColumnType colType;
private final Pad pad;
private final String padType;
private final String padLen;
// Create an instance with the given information.
KnownPartsToCompare(final String target, final ColumnType type, final Pad pad) {
this.target = new ColumnHeader(target);
this.colType = type;
this.pad = pad;
if (pad != null) {
padType = pad.getType().toString();
if (pad.getType() != PadType.NONE) {
padLen = String.valueOf(pad.getLength());
} else {
padLen = null;
}
} else {
padType = null;
padLen = null;
}
}
}
private Path schema;
// Write out a pretty print formatted version of a positional column schema.
private static String writePrettyPrintJson(final String targetHeader, final String type, final String padding, final String length) {
final StringBuilder json = new StringBuilder();
json.append(" {\n \"type\": \"");
json.append(type);
json.append("\",\n");
if (padding != null) {
json.append(" \"pad\": {\n \"type\": \"");
json.append(padding);
json.append("\"");
if (length != null) {
json.append(",\n \"length\": ");
json.append(length);
}
json.append("\n },\n");
}
json.append(" \"targetHeader\": \"");
json.append(targetHeader);
json.append("\"\n }");
return json.toString();
}
// Construct a valid JSON string for a {@code PositionalTableSchema} including white space.
private static String makeSchema(final String[][] specs) {
final StringBuilder schema = new StringBuilder("{\n \"columns\": [\n");
for (int i = 0; i < specs.length; i++) {
final var colSet = specs[i];
if (colSet.length == 0) {
schema.append(" []");
} else {
schema.append(" [\n");
for (int j = 0; j < colSet.length; j++) {
schema.append(colSet[j]);
if (j < colSet.length - 1) {
schema.append(",\n");
} else {
schema.append("\n");
}
}
schema.append(" ]");
}
if (i < specs.length - 1) {
schema.append(",\n");
} else {
schema.append("\n");
}
}
schema.append(" ],\n \"headerRow\": false\n}");
return schema.toString();
}
// Take in a set of values and construct a column schema with the index as the source header.
private static ColumnSchema makeColumnSchema(final int idx, final KnownPartsToCompare known) {
return ColumnSchema.builder()
.sourceHeader(ColumnHeader.of(idx))
.targetHeader(known.target)
.pad(known.pad)
.type(known.colType)
.build();
}
/* * * * BEGIN TESTS * * * */
@BeforeEach
public void setup() throws IOException {
schema = FileTestUtility.createTempFile("schema", ".json");
}
// Parse a positional schema with rows that have no or multiple values and verify expected schema is read
@Test
public void complexPositionalSchemaTest() {
final String json = "{ \"headerRow\": false, \"columns\": [" +
"[{\"targetHeader\": \"column 1 cleartext\", \"type\": \"cleartext\"}, " +
"{\"targetHeader\": \"column 1 sealed\", \"type\": \"sealed\", \"pad\": { \"type\": \"none\" } }," +
"{\"targetHeader\": \"column 1 fingerprint\", \"type\": \"fingerprint\"}]," +
"[]," +
"[{\"targetHeader\": \"column 3\", \"type\": \"cleartext\"}]" +
"]}";
final TableSchema schema = GsonUtil.fromJson(json, TableSchema.class);
final List<ColumnSchema> cols = schema.getColumns();
assertEquals(4, cols.size());
final ColumnSchema col1Cleartext = cols.get(0);
final ColumnSchema col1Sealed = cols.get(1);
final ColumnSchema col1Fingerprint = cols.get(2);
assertEquals(ColumnHeader.of(0), col1Cleartext.getSourceHeader());
assertEquals("column 1 cleartext", col1Cleartext.getTargetHeader().toString());
assertEquals(ColumnType.CLEARTEXT, col1Cleartext.getType());
assertEquals(ColumnHeader.of(0), col1Sealed.getSourceHeader());
assertEquals("column 1 sealed", col1Sealed.getTargetHeader().toString());
assertEquals(ColumnType.SEALED, col1Sealed.getType());
assertEquals(Pad.DEFAULT, col1Sealed.getPad());
assertEquals(ColumnHeader.of(0), col1Fingerprint.getSourceHeader());
assertEquals("column 1 fingerprint", col1Fingerprint.getTargetHeader().toString());
assertEquals(ColumnType.FINGERPRINT, col1Fingerprint.getType());
final ColumnSchema col3 = cols.get(3);
assertEquals(ColumnHeader.of(2), col3.getSourceHeader());
assertEquals("column 3", col3.getTargetHeader().toString());
assertEquals(ColumnType.CLEARTEXT, col3.getType());
}
// Make sure null values in columns throw an error
@Test
public void verifyNullsRejectedTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class,
() -> new PositionalTableSchema(List.of(
new ArrayList<>() {{
add(ColumnSchema.builder().targetHeader(new ColumnHeader("t1")).type(ColumnType.CLEARTEXT).build());
add(null);
}}
)));
assertEquals("Invalid empty column specification found for column 1", e.getMessage());
}
@Override
@Test
public void readSchemaAsTableSchemaWithValueValidationTest() {
final String schema = makeSchema(new String[][]{{C_1, C_2}, {C_3}, {C_4, C_5}});
final TableSchema table = GsonUtil.fromJson(schema, TableSchema.class);
final List<ColumnSchema> csKnownValid = List.of(
makeColumnSchema(0, CS_1),
makeColumnSchema(0, CS_2),
makeColumnSchema(1, CS_3),
makeColumnSchema(2, CS_4),
makeColumnSchema(2, CS_5)
);
assertEquals(csKnownValid, table.getColumns());
}
@Override
@Test
public void readSchemaAsActualClassWithValueValidationTest() {
final String schema = makeSchema(new String[][]{{C_1}, {}, {C_2, C_3, C_4}, {C_5}});
final PositionalTableSchema table = GsonUtil.fromJson(schema, PositionalTableSchema.class);
final List<ColumnSchema> csKnownValid = List.of(
makeColumnSchema(0, CS_1),
makeColumnSchema(2, CS_2),
makeColumnSchema(2, CS_3),
makeColumnSchema(2, CS_4),
makeColumnSchema(3, CS_5)
);
assertEquals(csKnownValid, table.getColumns());
}
// Verify that if we try to read a {@code PositionalTableSchema} into a {@code MappedTableSchema}, creation fails.
@Override
@Test
public void readAsWrongSchemaClassTypeTest() {
final String schema = makeSchema(new String[][]{{C_1}, {}, {C_2, C_3, C_4}, {C_5}});
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, MappedTableSchema.class));
}
@Override
@Test
public void readNullJsonInputTest() {
assertNull(GsonUtil.fromJson("null", PositionalTableSchema.class));
}
@Override
@Test
public void readWithEmptyJsonClassTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("{}", PositionalTableSchema.class),
"Schema was not initialized.");
}
@Override
@Test
public void readWithWrongJsonClassTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("true", PositionalTableSchema.class));
}
@Override
@Test
public void readWithWrongHeaderValueTest() {
final String schema = "{\"headerRow\": true, columns:[[" + C_1 + ", " + C_2 + "], [" + C_3 + "]]}";
// Interesting note: When called on the PositionalTableSchema class, GSON does not use TableSchemaTypeAdapter, so it's
// validate() that catches the incorrect header type. When it's called on the TableSchema class it uses the adapter and
// gets a syntax exception (correctly) instead.
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, PositionalTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
}
@Override
@Test
public void readWithJsonNullAsColumnsTest() {
final String schema = "{headerRow: false, columns:null}";
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, PositionalTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
}
@Override
@Test
public void readWithWrongJsonTypeAsColumnsValueTest() {
assertThrowsExactly(C3rIllegalArgumentException.class,
() -> GsonUtil.fromJson("{headerRow: false, columns:{0: [" + CS_1 + ", " + CS_2 + "]}}",
PositionalTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class,
() -> GsonUtil.fromJson("{headerRow: false, columns:[{0: [" + CS_1 + ", " + CS_2 + "]}]}",
PositionalTableSchema.class));
}
@Override
@Test
public void verifyEmptyColumnsRejectedTest() {
final String noColumnsSchema = "{headerRow: false, columns: []}";
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(noColumnsSchema, PositionalTableSchema.class));
final String emptyColumnsSchema = "headerRow: false, columns:[[],[],[]]}";
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(emptyColumnsSchema, PositionalTableSchema.class));
}
@Override
@Test
public void writeSchemaAsTableSchemaTest() {
final TableSchema table = new PositionalTableSchema(SCHEMA_FOR_WRITE_TESTS);
final String schemaWithClass = GsonUtil.toJson(table, TableSchema.class);
final String schemaWithoutClass = GsonUtil.toJson(table);
final String schemaActual = makeSchema(new String[][]{{C_1, C_2}, {C_3, C_4, C_5}});
assertEquals(schemaActual, schemaWithClass);
assertEquals(schemaActual, schemaWithoutClass);
}
@Override
@Test
public void writeSchemaAsActualClassTest() {
final PositionalTableSchema table = new PositionalTableSchema(SCHEMA_FOR_WRITE_TESTS);
final String schemaWithClass = GsonUtil.toJson(table, PositionalTableSchema.class);
final String schemaWithoutClass = GsonUtil.toJson(table);
final String schemaActual = makeSchema(new String[][]{{C_1, C_2}, {C_3, C_4, C_5}});
assertEquals(schemaActual, schemaWithClass);
assertEquals(schemaActual, schemaWithoutClass);
}
/*
* Verify that writing {@code PositionalTableSchema} to JSON fails when {@code MappedTableSchema} is specified,
* regardless of whether the object is referred to as a {@code TableSchema} or {@code PositionalTableSchema}
*/
@Override
@Test
public void writeSchemaAsWrongClassTest() {
final TableSchema table = new PositionalTableSchema(SCHEMA_FOR_WRITE_TESTS);
final PositionalTableSchema positionalTable = new PositionalTableSchema(SCHEMA_FOR_WRITE_TESTS);
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.toJson(table, MappedTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.toJson(positionalTable, MappedTableSchema.class));
}
/*
* Verify that the child class writes the {@code null} value out to disk correctly when
* - called as {@code TableSchema} or
* - called as {@code MappedTableSchema}
*/
@Override
@Test
public void writeNullJsonInputTest() {
assertEquals("null", GsonUtil.toJson(null, TableSchema.class));
assertEquals("null", GsonUtil.toJson(null, PositionalTableSchema.class));
}
/*
* Starting with a JSON string, verify the same JSON string is returned when
* - Reading it in as a {@code TableSchema} and writing it out as a {@code TableSchema}
* - Reading it in as a {@code PositionalTableSchema} and writing it out as a {@code TableSchema}
* - Reading it in as a {@code TableSchema} and writing it out as a {@code PositionalTableSchema}
* - Reading it in as a {@code PositionalTableSchema} and writing it out as a {@code PositionalTableSchema}
*/
@Override
@Test
public void roundTripStringToStringSerializationTest() {
final String schemaIn = makeSchema(new String[][]{{C_1, C_2}, {}, {C_3}, {C_4}, {C_5}, {}});
final String tableSchemaInTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, TableSchema.class), TableSchema.class);
assertEquals(schemaIn, tableSchemaInTableSchemaOut);
final String positionalSchemaInTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, PositionalTableSchema.class),
TableSchema.class);
assertEquals(schemaIn, positionalSchemaInTableSchemaOut);
final String tableSchemaInPositionalSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, TableSchema.class),
PositionalTableSchema.class);
assertEquals(schemaIn, tableSchemaInPositionalSchemaOut);
final String positionalSchemaInPositionalSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, PositionalTableSchema.class),
PositionalTableSchema.class);
assertEquals(schemaIn, positionalSchemaInPositionalSchemaOut);
}
/*
* Starting with an instance of a PositionalTableSchema class, verify the same value is returned when
* - Writing it out as a {@code TableSchema} and reading it in as a {@code TableSchema}
* - Writing it out as a {@code PositionalTableSchema} and reading it in as a {@code TableSchema}
* - Writing it out as a {@code TableSchema} and reading it in as a {@code PositionalTableSchema}
* - Writing it out as a {@code PositionalTableSchema} and reading it in as a {@code PositionalTableSchema}
*/
@Override
@Test
public void roundTripClassToClassSerializationTest() {
final TableSchema tableIn = new PositionalTableSchema(SCHEMA_FOR_WRITE_TESTS);
final TableSchema tableSchemaInTableSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, TableSchema.class),
TableSchema.class);
assertEquals(tableIn, tableSchemaInTableSchemaOut);
final TableSchema positionalSchemaInTableSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, PositionalTableSchema.class),
TableSchema.class);
assertEquals(tableIn, positionalSchemaInTableSchemaOut);
final PositionalTableSchema tableSchemaInPositionalSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, TableSchema.class),
PositionalTableSchema.class);
assertEquals(tableIn, tableSchemaInPositionalSchemaOut);
final PositionalTableSchema positionalSchemaInPositionalSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn,
PositionalTableSchema.class), PositionalTableSchema.class);
assertEquals(tableIn, positionalSchemaInPositionalSchemaOut);
}
}
| 2,555 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/TableSchemaCommonTypeAdapterTestInterface.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
// Tests common to all schema types regarding schema generation to and from json.
interface TableSchemaCommonTypeAdapterTestInterface {
// Read JSON file representing child class in as {@code TableSchema} and verify values are correct.
void readSchemaAsTableSchemaWithValueValidationTest();
// Read JSON file representing child class in as child class and verify values are correct.
void readSchemaAsActualClassWithValueValidationTest();
// Read JSON representing child class in as another child class type.
void readAsWrongSchemaClassTypeTest();
// Read JSON null value into the child class and make sure {@code null} is returned.
void readNullJsonInputTest();
// Read empty JSON object {@code {}} in to child class and verify it fails validation.
void readWithEmptyJsonClassTest();
// Verify that the wrong JSON type fails to be read in to child class.
void readWithWrongJsonClassTest();
// Verify that if the headerRow value indicates the other class type, the child class fails validation as not initialized.
void readWithWrongHeaderValueTest();
// Verify that if columns are set to {@code null} for the child class, construction fails.
void readWithJsonNullAsColumnsTest();
// Verify that if the wrong JSON type is used for columns the child class fails to be created.
void readWithWrongJsonTypeAsColumnsValueTest();
// Verify that if the columns are empty in all ways they could be for the child class, construction fails.
void verifyEmptyColumnsRejectedTest();
// Verify that the child class is written out with the correct JSON fields when it is written as a {@code TableSchema}.
void writeSchemaAsTableSchemaTest();
// Verify the child class is written out with all the correct JSON fields when it is written as itself.
void writeSchemaAsActualClassTest();
/*
* Verify that writing the child class to JSON fails when the wrong type is specified,
* regardless of whether the object is referred to as a {@code TableSchema} or the child class.
*/
void writeSchemaAsWrongClassTest();
// Verify that the child class writes the {@code null} value out to disk correctly when called as {@code TableSchema} or itself.
void writeNullJsonInputTest();
/*
* Round trip verification test.
* Starting with a JSON string, verify the same JSON string is returned when:
* - Reading it in as a {@code TableSchema} and writing it out as a {@code TableSchema}
* - Reading it in as the child class and writing it out as a {@code TableSchema}
* - Reading it in as a {@code TableSchema} and writing it out as the child class
* - Reading it in as the child class and writing it out as the child class
*/
void roundTripStringToStringSerializationTest();
/*
* Round trip verification test.
* Starting with an instance of the child class, verify the same value is returned when:
* - Writing it out as a {@code TableSchema} and reading it in as a {@code TableSchema}
* - Writing it out as the child class and reading it in as a {@code TableSchema}
* - Writing it out as a {@code TableSchema} and reading it in as the child class
* - Writing it out as the child class and reading it in as the child class
*/
void roundTripClassToClassSerializationTest();
} | 2,556 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/ColumnTypeTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ColumnTypeTypeAdapterTest {
@Test
public void fromLowerCaseTest() {
final ColumnType columnType = GsonUtil.fromJson("sealed", ColumnType.class);
assertEquals(ColumnType.SEALED, columnType);
}
@Test
public void fromUpperCaseTest() {
final ColumnType columnType = GsonUtil.fromJson("SEALED", ColumnType.class);
assertEquals(ColumnType.SEALED, columnType);
}
@Test
public void fromMixedCaseTest() {
final ColumnType columnType = GsonUtil.fromJson("SeaLeD", ColumnType.class);
assertEquals(ColumnType.SEALED, columnType);
}
@Test
public void badColumnTypeTest() {
assertThrows(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("bad", ColumnType.class));
}
@Test
public void readNullTest() {
assertNull(GsonUtil.fromJson("null", ColumnType.class));
}
@Test
public void writeTest() {
final String serialized = GsonUtil.toJson(ColumnType.SEALED);
final String expected = "\"" + ColumnType.SEALED + "\"";
assertEquals(expected, serialized);
}
@Test
public void writeNullTest() {
final String serialized = GsonUtil.toJson(null);
assertEquals("null", serialized);
}
}
| 2,557 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/GsonUtilTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.FileUtil;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class GsonUtilTest {
@Test
public void duplicateJsonSourceHeadersToTargetHeadersTest() {
assertThrows(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(
"{ \"headerRow\": true, \"columns\": [ { \"sourceHeader\":\"target\", \"type\":\"fingerprint\" }," +
"{ \"sourceHeader\":\"target\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"target\", \"type\":\"fingerprint\" } ] }", TableSchema.class));
}
@Test
public void manyJsonInferredTargetHeadersTest() {
final TableSchema tableSchema = GsonUtil.fromJson(
"{ \"headerRow\": true, \"columns\": [ { \"sourceHeader\":\"target 1\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"target 2\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"target 3\", \"type\":\"fingerprint\" } ] }", TableSchema.class);
assertEquals(3, tableSchema.getColumns().size());
for (int i = 0; i < 3; i++) {
assertEquals(
new ColumnHeader(tableSchema.getColumns().get(i).getSourceHeader() + ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX),
tableSchema.getColumns().get(i).getTargetHeader());
}
}
@Test
public void jsonMixOfInferredAndNonInferredTargetHeadersTest() {
final TableSchema tableSchema = GsonUtil.fromJson(
"{ \"headerRow\": true, \"columns\": [ { \"sourceHeader\":\"inferred\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"src header\", \"targetHeader\":\"tgt header\", \"type\":\"fingerprint\" } ] }", TableSchema.class);
assertEquals(2, tableSchema.getColumns().size());
assertEquals(
new ColumnHeader(tableSchema.getColumns().get(0).getSourceHeader() + ColumnHeader.DEFAULT_FINGERPRINT_SUFFIX),
tableSchema.getColumns().get(0).getTargetHeader());
assertEquals(new ColumnHeader("src header"), tableSchema.getColumns().get(1).getSourceHeader());
assertEquals(new ColumnHeader("tgt header"), tableSchema.getColumns().get(1).getTargetHeader());
}
@Test
public void jsonColumnHeaderToManyValidTargetsTest() {
final TableSchema tableSchema = GsonUtil.fromJson(
"{ \"headerRow\": true, \"columns\": [ " +
"{ \"sourceHeader\":\"target\", \"targetHeader\":\"target 0\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"target\", \"targetHeader\":\"target 1\", \"type\":\"fingerprint\" }, " +
"{ \"sourceHeader\":\"target\", \"targetHeader\":\"target 2\", \"type\":\"fingerprint\" } ] }", TableSchema.class);
assertEquals(3, tableSchema.getColumns().size());
final List<ColumnSchema> configSpec = tableSchema.getColumns();
// Check to make sure there's only one unique source header
final Set<ColumnHeader> srcs = configSpec.stream().map(ColumnSchema::getSourceHeader).collect(Collectors.toSet());
assertEquals(1, srcs.size());
// Check to make sure there's three unique target headers
final Set<ColumnHeader> tgts = configSpec.stream().map(ColumnSchema::getTargetHeader).collect(Collectors.toSet());
assertEquals(3, tgts.size());
}
@Test
public void jsonManyColumnHeadersToSingleTargetHeaderInvalidTest() {
assertThrows(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(
"{ \"headerRow\": true, \"columns\": [ { \"sourceHeader\":\"target 0\", \"targetHeader\":\"target\", " +
"\"type\":\"fingerprint\" }, { \"sourceHeader\":\"target 1\", \"targetHeader\":\"target\", " +
"\"type\":\"fingerprint\" }, { \"sourceHeader\":\"target\", \"targetHeader\":\"target 2\", " +
"\"type\":\"fingerprint\" } ] }", TableSchema.class));
}
@Test
public void fromJsonTest() {
final TableSchema cfg = GsonUtil.fromJson(FileUtil.readBytes("../samples/schema/config_sample.json"), TableSchema.class);
assertEquals(11, cfg.getColumns().size());
}
@Test
public void toJsonBadTest() {
assertThrows(C3rIllegalArgumentException.class, () ->
GsonUtil.toJson("oops wrong object", TableSchema.class));
}
}
| 2,558 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/MappedTableSchemaTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.config.PositionalTableSchema;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
// Test class for Mapped Schema specific portions of JSON parsing
public class MappedTableSchemaTypeAdapterTest implements TableSchemaCommonTypeAdapterTestInterface {
// {@code ColumnSchema} cleartext
private static final ColumnSchema CS_1 =
ColumnSchema.builder().sourceHeader(new ColumnHeader("source1")).targetHeader(new ColumnHeader("c1"))
.type(ColumnType.CLEARTEXT).build();
// Pretty printed JSON string for {@code cs1}
private static final String C_1 = writePrettyPrintJson(CS_1.getSourceHeader().toString(), CS_1.getTargetHeader().toString(),
CS_1.getType().toString(), getPadType(CS_1), getPadLen(CS_1));
// {@code ColumnSchema} fingerprint
private static final ColumnSchema CS_2 =
ColumnSchema.builder().sourceHeader(new ColumnHeader("source2")).targetHeader(new ColumnHeader("c2"))
.type(ColumnType.FINGERPRINT).build();
// Pretty printed JSON string for {@code cs2}
private static final String C_2 = writePrettyPrintJson(CS_2.getSourceHeader().toString(), CS_2.getTargetHeader().toString(),
CS_2.getType().toString(), getPadType(CS_2), getPadLen(CS_2));
// {@code ColumnSchema} sealed with no padding
private static final ColumnSchema CS_3 =
ColumnSchema.builder().sourceHeader(new ColumnHeader("source3")).targetHeader(new ColumnHeader("c3"))
.pad(Pad.DEFAULT).type(ColumnType.SEALED).build();
// Pretty printed JSON string for {@code cs3}
private static final String C_3 = writePrettyPrintJson(CS_3.getSourceHeader().toString(), CS_3.getTargetHeader().toString(),
CS_3.getType().toString(), getPadType(CS_3), getPadLen(CS_3));
// {@code ColumnSchema} sealed with max pad of 100
private static final ColumnSchema CS_4 =
ColumnSchema.builder().sourceHeader(new ColumnHeader("source4")).targetHeader(new ColumnHeader("c4"))
.pad(Pad.builder().type(PadType.MAX).length(100).build()).type(ColumnType.SEALED).build();
// Pretty printed JSON string for {@code cs4}
private static final String C_4 = writePrettyPrintJson(CS_4.getSourceHeader().toString(), CS_4.getTargetHeader().toString(),
CS_4.getType().toString(), getPadType(CS_4), getPadLen(CS_4));
// {@code ColumnSchema} sealed with fixed pad of 50
private static final ColumnSchema CS_5 =
ColumnSchema.builder().sourceHeader(new ColumnHeader("source5")).targetHeader(new ColumnHeader("c5"))
.pad(Pad.builder().type(PadType.FIXED).length(50).build()).type(ColumnType.SEALED).build();
// Pretty printed JSON string for {@code cs5}
private static final String C_5 = writePrettyPrintJson(CS_5.getSourceHeader().toString(), CS_5.getTargetHeader().toString(),
CS_5.getType().toString(), getPadType(CS_5), getPadLen(CS_5));
// Schema used for several I/O tests where a fixed value is useful
private static final List<ColumnSchema> SCHEMA_FOR_WRITE_TESTS = List.of(CS_1, CS_2, CS_3, CS_4, CS_5);
/*
* Helper function that creates the pretty printed format (correct white space) for a positional column schema for when we do
* comparison of json outputs.
*/
private static String writePrettyPrintJson(final String sourceHeader, final String targetHeader, final String colType,
final String padType, final String padLen) {
final StringBuilder json = new StringBuilder();
json.append(" {\n \"type\": \"");
json.append(colType);
json.append("\",\n");
if (padType != null) {
json.append(" \"pad\": {\n \"type\": \"");
json.append(padType);
json.append("\"");
if (padLen != null) {
json.append(",\n \"length\": ");
json.append(padLen);
}
json.append("\n },\n");
}
json.append(" \"sourceHeader\": \"");
json.append(sourceHeader);
json.append("\",\n \"targetHeader\": \"");
json.append(targetHeader);
json.append("\"\n }");
return json.toString();
}
// Helper function for getting the pad type if any.
private static String getPadType(final ColumnSchema cs) {
final Pad p = cs.getPad();
if (p == null) {
return null;
}
return p.getType().toString();
}
// Helper function for getting the pad length if any.
private static String getPadLen(final ColumnSchema cs) {
final Pad p = cs.getPad();
if (p == null) {
return null;
}
final Integer len = p.getLength();
return (len == null) ? null : String.valueOf(len);
}
// Construct a valid JSON string for a {@code MappedTableSchema} including white space.
private static String makeSchema(final String[] specs) {
final StringBuilder schema = new StringBuilder("{\n \"columns\": [\n");
for (int i = 0; i < specs.length; i++) {
schema.append(specs[i]);
if (i < specs.length - 1) {
schema.append(",\n");
} else {
schema.append("\n");
}
}
schema.append(" ],\n \"headerRow\": true\n}");
return schema.toString();
}
/* * * * BEGIN TESTS * * * */
@Override
@Test
public void readSchemaAsTableSchemaWithValueValidationTest() {
final String schema = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
final TableSchema table = GsonUtil.fromJson(schema, TableSchema.class);
final List<ColumnSchema> csKnownValid = List.of(CS_1, CS_2, CS_3, CS_4, CS_5);
assertEquals(csKnownValid, table.getColumns());
}
@Override
@Test
public void readSchemaAsActualClassWithValueValidationTest() {
final String schema = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
final MappedTableSchema table = GsonUtil.fromJson(schema, MappedTableSchema.class);
final List<ColumnSchema> csKnownValid = List.of(CS_1, CS_2, CS_3, CS_4, CS_5);
assertEquals(csKnownValid, table.getColumns());
}
/*
* Verify that if we try to read a {@code MappedTableSchema} into a {@code PositionalTableSchema}, creation fails.
*/
@Override
@Test
public void readAsWrongSchemaClassTypeTest() {
final String schema = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, PositionalTableSchema.class));
}
@Override
@Test
public void readNullJsonInputTest() {
assertNull(GsonUtil.fromJson("null", MappedTableSchema.class));
}
@Override
@Test
public void readWithEmptyJsonClassTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("{}", MappedTableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.MappedTableSchema.", e.getMessage());
}
@Override
@Test
public void readWithWrongJsonClassTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("true", MappedTableSchema.class));
}
/*
* Verify that if {@code headerRow = false}, {@code MappedTableSchema} fails validation
*/
@Override
@Test
public void readWithWrongHeaderValueTest() {
final String schema = "{headerRow: false, columns: [" + C_1 + "," + C_2 + "," + C_3 + "]}";
// Interesting note: When called on the MappedTableSchema class, GSON does not use TableSchemaTypeAdapter, so it's
// validate() that catches the incorrect header type. When it's called on the TableSchema class it uses the adapter and
// gets a syntax exception (correctly) instead.
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, MappedTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
}
@Override
@Test
public void readWithJsonNullAsColumnsTest() {
final String schema = "{headerRow: true, columns:null}";
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, MappedTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
}
@Override
@Test
public void readWithWrongJsonTypeAsColumnsValueTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("{headerRow: true, columns:{0: " +
CS_1 + ", 1:" + CS_2 + "}}", PositionalTableSchema.class));
}
@Override
@Test
public void verifyEmptyColumnsRejectedTest() {
final String noColumnsSchema = "{headerRow: true, columns: []}";
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(noColumnsSchema, MappedTableSchema.class));
}
@Override
@Test
public void writeSchemaAsTableSchemaTest() {
final TableSchema table = new MappedTableSchema(SCHEMA_FOR_WRITE_TESTS);
final String schemaWithClass = GsonUtil.toJson(table, TableSchema.class);
final String schemaWithoutClass = GsonUtil.toJson(table);
final String schemaActual = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
assertEquals(schemaActual, schemaWithClass);
assertEquals(schemaActual, schemaWithoutClass);
}
@Override
@Test
public void writeSchemaAsActualClassTest() {
final MappedTableSchema table = new MappedTableSchema(SCHEMA_FOR_WRITE_TESTS);
final String schemaWithClass = GsonUtil.toJson(table, MappedTableSchema.class);
final String schemaWithoutClass = GsonUtil.toJson(table);
final String schemaActual = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
assertEquals(schemaActual, schemaWithClass);
assertEquals(schemaActual, schemaWithoutClass);
}
/*
* Verify that writing {@code MappedTableSchema} to JSON fails when {@code PositionalTableSchema} is specified,
* regardless of whether the object is referred to as a {@code TableSchema} or {@code MappedTableSchema}
*/
@Override
@Test
public void writeSchemaAsWrongClassTest() {
final TableSchema table = new MappedTableSchema(SCHEMA_FOR_WRITE_TESTS);
final MappedTableSchema mappedTable = new MappedTableSchema(SCHEMA_FOR_WRITE_TESTS);
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.toJson(table, PositionalTableSchema.class));
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.toJson(mappedTable, PositionalTableSchema.class));
}
@Override
@Test
public void writeNullJsonInputTest() {
assertEquals("null", GsonUtil.toJson(null, TableSchema.class));
assertEquals("null", GsonUtil.toJson(null, MappedTableSchema.class));
}
/*
* Starting with a JSON string, verify the same JSON string is returned when
* - Reading it in as a {@code TableSchema} and writing it out as a {@code TableSchema}
* - Reading it in as a {@code MappedTableSchema} and writing it out as a {@code TableSchema}
* - Reading it in as a {@code TableSchema} and writing it out as a {@code MappedTableSchema}
* - Reading it in as a {@code MappedTableSchema} and writing it out as a {@code MappedTableSchema}
*/
@Override
@Test
public void roundTripStringToStringSerializationTest() {
final String schemaIn = makeSchema(new String[]{C_1, C_2, C_3, C_4, C_5});
final String tableSchemaInTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, TableSchema.class), TableSchema.class);
assertEquals(schemaIn, tableSchemaInTableSchemaOut);
final String mappedTableSchemaInTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, MappedTableSchema.class),
TableSchema.class);
assertEquals(schemaIn, mappedTableSchemaInTableSchemaOut);
final String tableSchemaInMappedTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, TableSchema.class),
MappedTableSchema.class);
assertEquals(schemaIn, tableSchemaInMappedTableSchemaOut);
final String mappedTableSchemaInMappedTableSchemaOut = GsonUtil.toJson(GsonUtil.fromJson(schemaIn, MappedTableSchema.class),
MappedTableSchema.class);
assertEquals(schemaIn, mappedTableSchemaInMappedTableSchemaOut);
}
/*
* Starting with an instance of a MappedTableSchema class, verify the same value is returned when
* - Writing it out as a {@code TableSchema} and reading it in as a {@code TableSchema}
* - Writing it out as a {@code MappedTableSchema} and reading it in as a {@code TableSchema}
* - Writing it out as a {@code TableSchema} and reading it in as a {@code MappedTableSchema}
* - Writing it out as a {@code MappedTableSchema} and reading it in as a {@code MappedTableSchema}
*/
@Override
@Test
public void roundTripClassToClassSerializationTest() {
final TableSchema tableIn = new MappedTableSchema(SCHEMA_FOR_WRITE_TESTS);
final TableSchema tableSchemaInTableSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, TableSchema.class),
TableSchema.class);
assertEquals(tableIn, tableSchemaInTableSchemaOut);
final TableSchema mappedTableSchemaInTableSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, MappedTableSchema.class),
TableSchema.class);
assertEquals(tableIn, mappedTableSchemaInTableSchemaOut);
final MappedTableSchema tableSchemaInMappedTableSchemaOut = GsonUtil.fromJson(GsonUtil.toJson(tableIn, TableSchema.class),
MappedTableSchema.class);
assertEquals(tableIn, tableSchemaInMappedTableSchemaOut);
final MappedTableSchema mappedTableSchemaInMappedTableSchemaOut = GsonUtil.fromJson(
GsonUtil.toJson(tableIn, MappedTableSchema.class), MappedTableSchema.class);
assertEquals(tableIn, mappedTableSchemaInMappedTableSchemaOut);
}
}
| 2,559 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/PadTypeTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class PadTypeTypeAdapterTest {
@Test
public void fromLowerCaseTest() {
final PadType padType = GsonUtil.fromJson("max", PadType.class);
assertEquals(PadType.MAX, padType);
}
@Test
public void fromUpperCaseTest() {
final PadType padType = GsonUtil.fromJson("MAX", PadType.class);
assertEquals(PadType.MAX, padType);
}
@Test
public void fromMixedCaseTest() {
final PadType padType = GsonUtil.fromJson("MaX", PadType.class);
assertEquals(PadType.MAX, padType);
}
@Test
public void badPadTypeTest() {
assertThrows(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("bad", PadType.class));
}
@Test
public void readNullTest() {
assertNull(GsonUtil.fromJson("null", PadType.class));
}
@Test
public void writeTest() {
final String serialized = GsonUtil.toJson(PadType.MAX);
final String expected = "\"" + PadType.MAX.name() + "\"";
assertEquals(expected, serialized);
}
@Test
public void writeNullTest() {
final String serialized = GsonUtil.toJson(null);
assertEquals("null", serialized);
}
}
| 2,560 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/ColumnHeaderTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ColumnHeader;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class ColumnHeaderTypeAdapterTest {
@Test
public void fromLowerCaseTest() {
final ColumnHeader columnHeader = GsonUtil.fromJson("test", ColumnHeader.class);
assertEquals("test", columnHeader.toString());
}
@Test
public void fromUpperCaseTest() {
final ColumnHeader columnHeader = GsonUtil.fromJson("TEST", ColumnHeader.class);
assertEquals("test", columnHeader.toString());
}
@Test
public void fromMixedCaseTest() {
final ColumnHeader columnHeader = GsonUtil.fromJson("tEsT", ColumnHeader.class);
assertEquals("test", columnHeader.toString());
}
@Test
public void withLeadingSpacesTest() {
final ColumnHeader columnHeader = GsonUtil.fromJson(" test", ColumnHeader.class);
assertEquals("test", columnHeader.toString());
}
@Test
public void withTrailingSpacesTest() {
final ColumnHeader columnHeader = GsonUtil.fromJson("test ", ColumnHeader.class);
assertEquals("test", columnHeader.toString());
}
@Test
public void withInnerSpacesTest() {
// Note extra quotes in order for the JSON to grab the entire String. Not necessary in other tests.
final ColumnHeader columnHeader = GsonUtil.fromJson("\"test test\"", ColumnHeader.class);
assertEquals("test test", columnHeader.toString());
}
@Test
public void readNullTest() {
assertNull(GsonUtil.fromJson("null", ColumnHeader.class));
}
@Test
public void writeTest() {
final ColumnHeader columnHeader = new ColumnHeader("test");
final String serialized = GsonUtil.toJson(columnHeader);
final String expected = "\"" + columnHeader + "\"";
assertEquals(expected, serialized);
}
@Test
public void writeNullTest() {
final String serialized = GsonUtil.toJson(null);
assertEquals("null", serialized);
}
}
| 2,561 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/json/TableSchemaTypeAdapterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.json;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.MappedTableSchema;
import com.amazonaws.c3r.config.TableSchema;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.utils.FileUtil;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
// Tests top level adapter logic for schema generation to and from jsons.
public final class TableSchemaTypeAdapterTest {
// Make sure headerRow must be specified.
@Test
public void verifyHeaderRowRequiredTest() {
final String schema = "{\"columns\": []}";
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.TableSchema.", e.getMessage());
}
@Test
public void verifyObjectStatusTest() {
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("2", TableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.TableSchema.", e.getMessage());
}
// Make sure headerRow is a boolean.
@Test
public void readWithWrongJsonTypeAsHeaderValueTest() {
final String schema1 = "{headerRow: 1, columns: {}}";
final Exception e1 = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema1, TableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.TableSchema.", e1.getMessage());
final String schema2 = "{headerRow: {a: 1, b: 2}, columns: {}}";
final Exception e2 = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema2, TableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.TableSchema.", e2.getMessage());
}
// Make sure null value for headerRow is rejected.
@Test
public void readWithJsonNullAsHeaderValueTest() {
final String schema = "{headerRow: null, columns: {}}";
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
assertEquals("Unable to parse JSON class com.amazonaws.c3r.config.TableSchema.", e.getMessage());
}
// Make sure null value for headerRow is rejected.
@Test
public void readWithWrongClassValueTest() {
final String schema = "{headerRow: true, columns: {}}";
final var settings = GsonUtil.fromJson(schema, ClientSettings.class);
assertEquals(ClientSettings.highAssuranceMode(), settings);
}
// Make sure we return null when value is null
@Test
public void readWithJsonNullReturnsNullTest() {
final String schema = "null";
assertNull(GsonUtil.fromJson(schema, TableSchema.class));
assertNull(GsonUtil.fromJson(null, TableSchema.class));
}
@Test
public void readWithEmptyJsonClassTest() {
assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson("{}", TableSchema.class));
}
// Make sure we write a null value when the schema is null
@Test
public void writeWithJsonNullReturnsNullTest() {
assertEquals("null", GsonUtil.toJson(null, TableSchema.class));
}
// Make sure null value for headerRow is rejected.
@Test
public void writeWithWrongClassValueTest() {
final TableSchema schema = new MappedTableSchema(List.of(
ColumnSchema.builder().sourceHeader(new ColumnHeader("source")).type(ColumnType.CLEARTEXT).build()
));
final Exception e = assertThrowsExactly(C3rIllegalArgumentException.class, () -> GsonUtil.toJson(schema, ClientSettings.class));
assertEquals("Unable to write class com.amazonaws.c3r.config.ClientSettings as JSON.", e.getMessage());
}
// Make sure a positional schema that maps input columns to output columns produces the same relative input.
@Test
public void verifyMappedAndPositionalSchemaGenerateSameOutputColumnsTest() {
final int repeatedInputColumnIndex = 5;
final TableSchema positionalSchema = GsonUtil.fromJson(
FileUtil.readBytes("../samples/schema/config_sample_no_headers.json"), TableSchema.class);
final TableSchema mappedSchema = GsonUtil.fromJson(FileUtil.readBytes("../samples/schema/config_sample.json"),
TableSchema.class);
final var positionalColumns = positionalSchema.getColumns();
final var mappedColumns = mappedSchema.getColumns();
assertEquals(positionalColumns.size(), mappedColumns.size());
for (int i = 0; i < positionalColumns.size(); i++) {
final var positional = positionalColumns.get(i);
final var mapped = mappedColumns.get(i);
assertNotEquals(positional.getSourceHeader(), mapped.getSourceHeader());
if (i == repeatedInputColumnIndex) {
assertEquals(positional.getSourceHeader(), positionalColumns.get(i + 1).getSourceHeader());
assertEquals(positional.getSourceHeader(), positionalColumns.get(i + 2).getSourceHeader());
assertEquals(mapped.getSourceHeader(), mappedColumns.get(i + 1).getSourceHeader());
assertEquals(mapped.getSourceHeader(), mappedColumns.get(i + 2).getSourceHeader());
}
assertEquals(positional.getTargetHeader(), mapped.getTargetHeader());
assertEquals(positional.getPad(), mapped.getPad());
assertEquals(positional.getType(), mapped.getType());
}
}
// Check that duplicate target columns are rejected regardless of normalization-irrelevant differences
@Test
public void checkDuplicateTargetColumnsErrorsTst() {
final String schema = String.join("\n", "{headerRow: true,",
"columns: [",
"{",
" \"sourceHeader\": \"FirstName\",",
" \"targetHeader\": \"FirstName\",",
" \"type\": \"cleartext\"",
"},",
"{",
" \"sourceHeader\": \"FirstName\",",
" \"targetHeader\": \" firstname \",",
" \"type\": \"cleartext\"",
"}",
"]}");
assertThrows(C3rIllegalArgumentException.class, () -> GsonUtil.fromJson(schema, TableSchema.class));
assertDoesNotThrow(() -> GsonUtil.fromJson(schema.replaceAll(" firstname ", "firstname2"), TableSchema.class));
}
}
| 2,562 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/cleanrooms/CleanRoomsDaoTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.cleanrooms;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.utils.C3rSdkProperties;
import com.amazonaws.c3r.utils.FileTestUtility;
import com.amazonaws.c3r.utils.GeneralTestUtility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsCredentials;
import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider;
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import software.amazon.awssdk.auth.credentials.ProfileCredentialsProvider;
import software.amazon.awssdk.core.ApiName;
import software.amazon.awssdk.core.exception.SdkClientException;
import software.amazon.awssdk.core.exception.SdkException;
import software.amazon.awssdk.profiles.ProfileFileSystemSetting;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cleanrooms.CleanRoomsClient;
import software.amazon.awssdk.services.cleanrooms.model.AccessDeniedException;
import software.amazon.awssdk.services.cleanrooms.model.CleanRoomsException;
import software.amazon.awssdk.services.cleanrooms.model.Collaboration;
import software.amazon.awssdk.services.cleanrooms.model.DataEncryptionMetadata;
import software.amazon.awssdk.services.cleanrooms.model.GetCollaborationRequest;
import software.amazon.awssdk.services.cleanrooms.model.GetCollaborationResponse;
import software.amazon.awssdk.services.cleanrooms.model.ResourceNotFoundException;
import software.amazon.awssdk.services.cleanrooms.model.ThrottlingException;
import software.amazon.awssdk.services.cleanrooms.model.ValidationException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;
public class CleanRoomsDaoTest {
private String origAwsRegion;
private String origAwsAccessKeyId;
private String origAwsSecretAccessKey;
private final String testRegion = "not-real-test-region";
@BeforeEach
public void setup() {
origAwsRegion = System.getProperty("aws.region");
origAwsAccessKeyId = System.getProperty("aws.accessKeyId");
origAwsSecretAccessKey = System.getProperty("aws.secretAccessKey");
System.setProperty("aws.region", testRegion);
}
@AfterEach
public void teardown() {
if (origAwsRegion != null) {
System.setProperty("aws.region", origAwsRegion);
origAwsRegion = null;
} else {
System.clearProperty("aws.region");
}
if (origAwsAccessKeyId != null) {
System.setProperty("aws.accessKeyId", origAwsAccessKeyId);
origAwsAccessKeyId = null;
} else {
System.clearProperty("aws.accessKeyId");
}
if (origAwsSecretAccessKey != null) {
System.setProperty("aws.secretAccessKey", origAwsSecretAccessKey);
origAwsSecretAccessKey = null;
} else {
System.clearProperty("aws.secretAccessKey");
}
}
@Test
public void defaultApiNameTest() throws CleanRoomsException {
final CleanRoomsDao dao = CleanRoomsDao.builder().build();
assertEquals(C3rSdkProperties.API_NAME, dao.getApiName());
}
@Test
public void customApiNameTest() throws CleanRoomsException {
final ApiName testApiName = ApiName.builder()
.name("TEST_NAME")
.version("1.2.4")
.build();
final CleanRoomsDao dao = CleanRoomsDao.builder().apiName(testApiName).build();
assertEquals(testApiName, dao.getApiName());
}
@Test
public void initAwsCredentialsProviderNoProfile() throws CleanRoomsException {
final CleanRoomsDao dao = CleanRoomsDao.builder().build();
assertInstanceOf(DefaultCredentialsProvider.class, dao.initAwsCredentialsProvider());
}
@Test
public void initAwsCredentialsProviderCustomProfile() throws CleanRoomsException, IOException {
// We set up a custom temporary config file with a profile `my-profile` and then
// have the CleanRoomsDao use that, checking it got all the expected info
final String myProfileName = "my-profile";
final String myAccessKeyId = "AKIAI44QH8DHBEXAMPLE";
final String mySecretAccessKey = "je7MtGbClwBF/2Zp9Utk/h3yCo8nvbEXAMPLEKEY";
final String configFileContent = String.join("\n",
"[default]",
"aws_access_key_id=AKIAIOSFODNN7EXAMPLE",
"aws_secret_access_key=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
"",
"[profile " + myProfileName + "]",
"aws_access_key_id=" + myAccessKeyId,
"aws_secret_access_key=" + mySecretAccessKey,
""
);
final Path configFile = FileTestUtility.createTempFile();
Files.write(configFile, configFileContent.getBytes(StandardCharsets.UTF_8));
System.setProperty(ProfileFileSystemSetting.AWS_CONFIG_FILE.property(), configFile.toString());
final CleanRoomsDao dao = CleanRoomsDao.builder().profile(myProfileName).build();
final AwsCredentialsProvider credentialsProvider = dao.initAwsCredentialsProvider();
assertInstanceOf(ProfileCredentialsProvider.class, credentialsProvider);
final AwsCredentials credentials = credentialsProvider.resolveCredentials();
assertEquals(myAccessKeyId, credentials.accessKeyId());
assertEquals(mySecretAccessKey, credentials.secretAccessKey());
}
@Test
public void initRegionDefaultRegion() throws CleanRoomsException {
final CleanRoomsDao dao = CleanRoomsDao.builder().build();
assertEquals(Region.of(testRegion), dao.initRegion());
}
@Test
public void initRegionCustomRegion() throws CleanRoomsException {
final String customRegion = "us-east-1";
final CleanRoomsDao dao = CleanRoomsDao.builder().region(customRegion).build();
assertEquals(Region.of(customRegion), dao.initRegion());
}
@Test
public void initCleanRoomsClientSdkExceptionTest() throws CleanRoomsException {
final CleanRoomsDao dao = mock(CleanRoomsDao.class);
when(dao.initRegion()).thenThrow(SdkClientException.create("Region oops!"));
when(dao.initAwsCredentialsProvider()).thenThrow(SdkClientException.create("Credentials oops!"));
when(dao.getClient()).thenCallRealMethod();
assertThrows(C3rRuntimeException.class, dao::getClient);
}
@Test
public void getCollaborationDataEncryptionMetadataTest() throws CleanRoomsException {
final ClientSettings expectedClientSettings = ClientSettings.builder()
.allowCleartext(true)
.allowDuplicates(true)
.allowJoinsOnColumnsWithDifferentNames(false)
.preserveNulls(false)
.build();
final DataEncryptionMetadata metadata = DataEncryptionMetadata.builder()
.allowCleartext(expectedClientSettings.isAllowCleartext())
.allowDuplicates(expectedClientSettings.isAllowDuplicates())
.allowJoinsOnColumnsWithDifferentNames(expectedClientSettings.isAllowJoinsOnColumnsWithDifferentNames())
.preserveNulls(expectedClientSettings.isPreserveNulls())
.build();
final Collaboration collaboration = Collaboration.builder()
.dataEncryptionMetadata(metadata)
.build();
final GetCollaborationResponse response = GetCollaborationResponse.builder()
.collaboration(collaboration)
.build();
final var client = mock(CleanRoomsClient.class);
when(client.getCollaboration(any(GetCollaborationRequest.class))).thenReturn(response);
final var dao = spy(CleanRoomsDao.class);
when(dao.getClient()).thenReturn(client);
final var actualClientSettings = dao.getCollaborationDataEncryptionMetadata(GeneralTestUtility.EXAMPLE_SALT
.toString());
assertEquals(expectedClientSettings, actualClientSettings);
}
@Test
public void getCollaborationNullDataEncryptionMetadataTest() throws CleanRoomsException {
final Collaboration collaboration = Collaboration.builder()
.dataEncryptionMetadata((DataEncryptionMetadata) null)
.build();
final GetCollaborationResponse response = GetCollaborationResponse.builder()
.collaboration(collaboration)
.build();
final var client = mock(CleanRoomsClient.class);
when(client.getCollaboration(any(GetCollaborationRequest.class))).thenReturn(response);
final var dao = spy(CleanRoomsDao.class);
when(dao.getClient()).thenReturn(client);
assertThrows(C3rRuntimeException.class, () ->
dao.getCollaborationDataEncryptionMetadata(GeneralTestUtility.EXAMPLE_SALT.toString()));
assertThrows(C3rRuntimeException.class, () ->
dao.getCollaborationDataEncryptionMetadata(GeneralTestUtility.EXAMPLE_SALT.toString()));
}
@Test
public void getCollaborationDataEncryptionMetadataFailureTest() throws CleanRoomsException {
final List<Throwable> exceptions = List.of(
ResourceNotFoundException.builder().message("ResourceNotFoundException").build(),
AccessDeniedException.builder().message("AccessDeniedException").build(),
ThrottlingException.builder().message("ThrottlingException").build(),
ValidationException.builder().message("ValidationException").build(),
CleanRoomsException.builder().message("CleanRoomsException").build(),
SdkException.builder().message("SdkException").build());
for (var exception : exceptions) {
final var client = mock(CleanRoomsClient.class);
when(client.getCollaboration(any(GetCollaborationRequest.class))).thenThrow(exception);
final var dao = spy(CleanRoomsDao.class);
when(dao.getClient()).thenReturn(client);
assertThrows(C3rRuntimeException.class, () ->
dao.getCollaborationDataEncryptionMetadata(GeneralTestUtility.EXAMPLE_SALT.toString()));
try {
dao.getCollaborationDataEncryptionMetadata(GeneralTestUtility.EXAMPLE_SALT.toString());
fail();
} catch (Exception e) {
assertEquals(exception, e.getCause());
}
}
}
}
| 2,563 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/ClientDataInfoTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import static com.amazonaws.c3r.data.ClientDataInfo.FLAG_COUNT;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClientDataInfoTest {
@Test
public void validateWithinBitWidthLimit() {
// Ensure we stay within 8 bits.
assertTrue(FLAG_COUNT + ClientDataType.BITS <= ClientDataInfo.BYTE_LENGTH * 8);
}
@ParameterizedTest
@EnumSource(ClientDataType.class)
public void encodeDecodeStringNonNull(final ClientDataType type) {
final var nullUnknown = ClientDataInfo.builder().type(ClientDataType.UNKNOWN).isNull(true).build();
final var nonNullUnknown = ClientDataInfo.builder().type(ClientDataType.UNKNOWN).isNull(false).build();
if (type != ClientDataType.UNKNOWN) {
final var nullType = ClientDataInfo.builder().type(type).isNull(true).build();
final var nonNullType = ClientDataInfo.builder().type(type).isNull(false).build();
// Test round trip encode/decode remains the same
assertEquals(nullType, ClientDataInfo.decode(nullType.encode()));
assertEquals(nonNullType, ClientDataInfo.decode(nonNullType.encode()));
// Make sure decoded type is unique from other type
assertNotEquals(ClientDataInfo.decode(nullType.encode()), nullUnknown);
assertNotEquals(ClientDataInfo.decode(nonNullType.encode()), nonNullUnknown);
// Make sure null status is kept through encode/decode
assertNotEquals(ClientDataInfo.decode(nullType.encode()), ClientDataInfo.decode(nonNullType.encode()));
// Make sure decoded opposite null with different type doesn't match
assertNotEquals(ClientDataInfo.decode(nullType.encode()), nonNullUnknown);
assertNotEquals(ClientDataInfo.decode(nonNullType.encode()), nullUnknown);
} else {
// Special case for ClientDataType.UNKNOWN since it needs to be compared against a different value.
final var nullString = ClientDataInfo.builder().type(ClientDataType.STRING).isNull(true).build();
final var nonNullString = ClientDataInfo.builder().type(ClientDataType.STRING).isNull(false).build();
// Test round trip encode/decode remains the same
assertEquals(nullUnknown, ClientDataInfo.decode(nullUnknown.encode()));
assertEquals(nonNullUnknown, ClientDataInfo.decode(nonNullUnknown.encode()));
// Make sure decoded type is unique from other type
assertNotEquals(ClientDataInfo.decode(nullUnknown.encode()), nullString);
assertNotEquals(ClientDataInfo.decode(nonNullUnknown.encode()), nonNullString);
// Make sure null status is kept through encode/decode
assertNotEquals(ClientDataInfo.decode(nullUnknown.encode()), ClientDataInfo.decode(nonNullUnknown.encode()));
// Make sure decoded opposite null with different type doesn't match
assertNotEquals(ClientDataInfo.decode(nullUnknown.encode()), nonNullString);
assertNotEquals(ClientDataInfo.decode(nonNullUnknown.encode()), nullString);
}
}
}
| 2,564 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/ValueTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ValueTest {
@Test
public void getBytesReturnsNullWhenInputIsNull() {
assertNull(Value.getBytes(null));
}
@Test
public void getBytesReturnsNullWhenDataIsNull() {
final Value value = mock(Value.class);
when(value.getBytes()).thenReturn(null);
assertNull(value.getBytes());
}
@Test public void getBytesReturnsArray() {
final byte[] bytes = {1, 2, 3, 4};
final Value value = mock(Value.class);
when(value.getBytes()).thenReturn(bytes);
// Check addresses are the same
assertEquals(bytes, value.getBytes());
// Check the values are the same
assertArrayEquals(bytes, value.getBytes());
}
}
| 2,565 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/FingerprintEquivalenceClassTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.FingerprintTransformer;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class FingerprintEquivalenceClassTest {
private final byte[] secret = "SomeFakeSecretKey".getBytes(StandardCharsets.UTF_8);
private final byte[] salt = "saltybytes".getBytes(StandardCharsets.UTF_8);
private final SecretKey secretKey = new SecretKeySpec(secret, 0, secret.length, "AES");
private FingerprintTransformer fingerprintTransformer;
private EncryptionContext context(final ClientDataType type) {
return EncryptionContext.builder()
.columnLabel("label")
.clientDataType(type)
.build();
}
@BeforeEach
public void setup() {
fingerprintTransformer = new FingerprintTransformer(secretKey, salt, ClientSettings.highAssuranceMode(), false);
}
@Test
public void bigintIsAccepted() {
final byte[] lVal = ValueConverter.BigInt.toBytes(Long.MAX_VALUE);
final var results = fingerprintTransformer.marshal(lVal, context(ClientDataType.BIGINT));
assertArrayEquals("02:hmac:tJkxHwIHIj0kN9fOGfMmqRlHm7JSJukZ0+KLiUCPaWM=".getBytes(StandardCharsets.UTF_8), results);
}
@Test
public void booleanIsAccepted() {
final byte[] bVal = ValueConverter.Boolean.toBytes(true);
final var results = fingerprintTransformer.marshal(bVal, context(ClientDataType.BOOLEAN));
assertArrayEquals("02:hmac:Tzupi3wWfO1KjWtrbHQ1QS/uYZMPcqcBOJQ7oW7XPzg=".getBytes(StandardCharsets.UTF_8), results);
}
@Test
public void charIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.CHAR)));
}
@Test
public void dateIsAccepted() {
final byte[] bytes = ValueConverter.Int.toBytes(100);
final var results = fingerprintTransformer.marshal(bytes, context(ClientDataType.DATE));
assertArrayEquals("02:hmac:8sqW9guEZZM5Yp4ZrPHg5os8s0j+m2odoieHGVto2eg=".getBytes(StandardCharsets.UTF_8), results);
}
@Test
public void decimalIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.DECIMAL)));
}
@Test
public void doubleIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.DOUBLE)));
}
@Test
public void floatIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.FLOAT)));
}
@Test
public void intIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.INT)));
}
@Test
public void smallintIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.SMALLINT)));
}
@Test
public void stringIsAccepted() {
final byte[] sVal = ValueConverter.String.toBytes("12345");
final var results = fingerprintTransformer.marshal(sVal, context(ClientDataType.STRING));
assertArrayEquals("02:hmac:31wVfl2/f1AUWduklYARibTmLE0P4/99MtNJ14W7qO8=".getBytes(StandardCharsets.UTF_8), results);
}
@Test
public void timestampIsRejected() {
assertThrows(C3rIllegalArgumentException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.TIMESTAMP)));
}
@Test
public void varcharIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.VARCHAR)));
}
@Test
public void unknownIsRejected() {
assertThrows(C3rRuntimeException.class, () -> fingerprintTransformer.marshal(null, context(ClientDataType.UNKNOWN)));
}
@Test
public void differentEquivalenceClassesDoNotMatchTest() {
final byte[] bytes = ValueConverter.BigInt.toBytes(100);
final var resultsAsBigInt = new String(fingerprintTransformer.marshal(bytes, context(ClientDataType.BIGINT)),
StandardCharsets.UTF_8);
assertEquals("02:hmac:XxBlrpT1ndd+Jk12ya7Finb9I9rOCzBO3ivb/inZ0eo=", resultsAsBigInt);
final var resultsAsString = new String(fingerprintTransformer.marshal(bytes, context(ClientDataType.STRING)),
StandardCharsets.UTF_8);
assertEquals("02:hmac:1Mv2rjn0cWRjXl5nWA3dNP0hT6PXDbcDbZhayZMgNMU=", resultsAsString);
assertNotEquals(resultsAsBigInt, resultsAsString);
}
}
| 2,566 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/ClientDataTypeTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import java.util.Arrays;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClientDataTypeTest {
@Test
public void validateValueCountTest() {
// Make sure the number of supported types fits in our allocated 6 bits for encoding
assertTrue(ClientDataType.values().length <= ClientDataType.MAX_DATATYPE_COUNT);
}
@Test
public void validateDataTypeIndicesTest() {
// Make sure there aren't any duplicate values
final var uniqueIndexCount = Arrays.stream(ClientDataType.values()).map(ClientDataType::getIndex)
.collect(Collectors.toSet())
.size();
assertEquals(uniqueIndexCount, ClientDataType.values().length);
// Ensure each individual value fits within the reserved number of bits
for (ClientDataType t : ClientDataType.values()) {
assertTrue(t.getIndex() <= ClientDataType.MAX_DATATYPE_COUNT);
}
}
@ParameterizedTest
@EnumSource(ClientDataType.class)
public void fromIndexTest(final ClientDataType type) {
assertEquals(type, ClientDataType.fromIndex(type.getIndex()));
}
@Test
public void invalidIndexTest() {
assertThrows(C3rIllegalArgumentException.class, () ->
ClientDataType.fromIndex((byte) -1));
assertThrows(C3rIllegalArgumentException.class, () ->
ClientDataType.fromIndex((byte) ClientDataType.values().length));
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class,
names = {"BIGINT", "INT", "SMALLINT", "STRING", "CHAR", "VARCHAR", "BOOLEAN", "DATE"},
mode = EnumSource.Mode.EXCLUDE)
public void invalidTypesTest(final ClientDataType type) {
assertThrows(C3rRuntimeException.class, () -> type.getRepresentativeType());
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class, names = {"BIGINT", "INT", "SMALLINT"})
public void validIntegralTypesTest(final ClientDataType type) {
assertEquals(ClientDataType.BIGINT, type.getRepresentativeType());
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class, names = {"STRING", "CHAR", "VARCHAR"})
public void validStringTypesTest(final ClientDataType type) {
assertEquals(ClientDataType.STRING, type.getRepresentativeType());
}
@Test
public void validBooleanTypesTest() {
assertEquals(ClientDataType.BOOLEAN, ClientDataType.BOOLEAN.getRepresentativeType());
}
@Test
public void validDateTypesTest() {
assertEquals(ClientDataType.DATE, ClientDataType.DATE.getRepresentativeType());
}
@Test
public void indicesAreUnchangedTest() {
// Make sure enumeration hasn't changed order so we don't break backward compatibility unknowingly
assertEquals(ClientDataType.UNKNOWN, ClientDataType.fromIndex((byte) 0));
assertEquals(ClientDataType.STRING, ClientDataType.fromIndex((byte) 1));
assertEquals(ClientDataType.BIGINT, ClientDataType.fromIndex((byte) 2));
assertEquals(ClientDataType.BOOLEAN, ClientDataType.fromIndex((byte) 3));
assertEquals(ClientDataType.CHAR, ClientDataType.fromIndex((byte) 4));
assertEquals(ClientDataType.DATE, ClientDataType.fromIndex((byte) 5));
assertEquals(ClientDataType.DECIMAL, ClientDataType.fromIndex((byte) 6));
assertEquals(ClientDataType.DOUBLE, ClientDataType.fromIndex((byte) 7));
assertEquals(ClientDataType.FLOAT, ClientDataType.fromIndex((byte) 8));
assertEquals(ClientDataType.INT, ClientDataType.fromIndex((byte) 9));
assertEquals(ClientDataType.SMALLINT, ClientDataType.fromIndex((byte) 10));
assertEquals(ClientDataType.TIMESTAMP, ClientDataType.fromIndex((byte) 11));
assertEquals(ClientDataType.VARCHAR, ClientDataType.fromIndex((byte) 12));
}
}
| 2,567 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/CsvValueTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
public class CsvValueTest {
@Test
public void stringConstructorNullTest() {
assertNull(new CsvValue((String) null).getBytes());
assertNull(new CsvValue((byte[]) null).getBytes());
assertEquals(0, new CsvValue((byte[]) null).byteLength());
}
@Test
public void emptyStringConstructorNullTest() {
assertArrayEquals(new byte[0], new CsvValue("").getBytes());
assertArrayEquals(new byte[0], new CsvValue("".getBytes(StandardCharsets.UTF_8)).getBytes());
}
@Test
public void nonEmptyStringConstructorNullTest() {
assertArrayEquals("42".getBytes(StandardCharsets.UTF_8), new CsvValue("42").getBytes());
assertArrayEquals("42".getBytes(StandardCharsets.UTF_8), new CsvValue("42".getBytes(StandardCharsets.UTF_8)).getBytes());
}
}
| 2,568 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/data/ValueConverterTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.data;
import com.amazonaws.c3r.config.ColumnHeader;
import com.amazonaws.c3r.config.ColumnInsight;
import com.amazonaws.c3r.config.ColumnSchema;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.Pad;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.mockito.ArgumentMatchers;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import static com.amazonaws.c3r.data.ClientDataType.BIGINT_BYTE_SIZE;
import static com.amazonaws.c3r.data.ClientDataType.INT_BYTE_SIZE;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
public class ValueConverterTest {
private static final ColumnInsight SEALED_COLUMN_INSIGHT = new ColumnInsight(ColumnSchema.builder().type(ColumnType.SEALED)
.sourceHeader(ColumnHeader.ofRaw("source")).pad(Pad.DEFAULT).build());
private static final ColumnInsight CLEARTEXT_COLUMN_INSIGHT = new ColumnInsight(ColumnSchema.builder().type(ColumnType.CLEARTEXT)
.sourceHeader(ColumnHeader.ofRaw("source")).build());
private static final ColumnInsight FINGERPRINT_COLUMN_INSIGHT = new ColumnInsight(ColumnSchema.builder().type(ColumnType.FINGERPRINT)
.sourceHeader(ColumnHeader.ofRaw("source")).build());
@ParameterizedTest
@EnumSource(value = ClientDataType.class)
public void cleartextMapsToSameValueTest(final ClientDataType type) {
final byte[] testVal = new byte[]{1, 2, 3};
final Value value = org.mockito.Mockito.mock(Value.class);
when(value.getClientDataType()).thenReturn(type);
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.BIGINT)))
.thenReturn(ByteBuffer.allocate(BIGINT_BYTE_SIZE).putLong(2L).array());
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.STRING))).thenReturn("hello".getBytes(StandardCharsets.UTF_8));
when(value.getBytes()).thenReturn(testVal);
assertEquals(value.getBytes(), ValueConverter.getBytesForColumn(value, CLEARTEXT_COLUMN_INSIGHT.getType()));
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class)
public void sealedMapsToSameValueTest(final ClientDataType type) {
final byte[] testVal = new byte[]{1, 2, 3};
final Value value = org.mockito.Mockito.mock(Value.class);
when(value.getClientDataType()).thenReturn(type);
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.BIGINT)))
.thenReturn(ByteBuffer.allocate(BIGINT_BYTE_SIZE).putLong(2L).array());
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.STRING))).thenReturn("hello".getBytes(StandardCharsets.UTF_8));
when(value.getBytes()).thenReturn(testVal);
assertEquals(value.getBytes(), ValueConverter.getBytesForColumn(value, SEALED_COLUMN_INSIGHT.getType()));
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class, names = {"STRING", "CHAR", "VARCHAR"})
public void fingerprintStringEquivalenceClassTest(final ClientDataType type) {
final String string = "hello";
final Value value = org.mockito.Mockito.mock(Value.class);
when(value.getClientDataType()).thenReturn(type);
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.STRING))).thenReturn(string.getBytes(StandardCharsets.UTF_8));
when(value.getBytes()).thenReturn(string.getBytes(StandardCharsets.UTF_8));
assertArrayEquals(value.getBytes(), ValueConverter.getBytesForColumn(value, FINGERPRINT_COLUMN_INSIGHT.getType()));
}
@ParameterizedTest
@EnumSource(value = ClientDataType.class, names = {"BIGINT", "INT", "SMALLINT"})
public void fingerprintIntegerEquivalenceClassTest(final ClientDataType type) {
final Value value = org.mockito.Mockito.mock(Value.class);
when(value.getClientDataType()).thenReturn(type);
when(value.getBytesAs(ArgumentMatchers.eq(ClientDataType.BIGINT)))
.thenReturn(ByteBuffer.allocate(BIGINT_BYTE_SIZE).putLong(2L).array());
when(value.getBytes()).thenReturn(
type == ClientDataType.BIGINT ?
ByteBuffer.allocate(BIGINT_BYTE_SIZE).putLong(2L).array() : ByteBuffer.allocate(INT_BYTE_SIZE).putInt(2).array()
);
if (type == ClientDataType.BIGINT) {
assertArrayEquals(value.getBytes(), ValueConverter.getBytesForColumn(value, FINGERPRINT_COLUMN_INSIGHT.getType()));
} else {
assertFalse(Arrays.equals(value.getBytes(), ValueConverter.getBytesForColumn(value, FINGERPRINT_COLUMN_INSIGHT.getType())));
}
}
@Test
public void bigIntBytesTest() {
assertEquals(
42,
ValueConverter.BigInt.fromBytes(ValueConverter.BigInt.toBytes(42L)));
assertNull(ValueConverter.BigInt.fromBytes(null));
assertNull(ValueConverter.BigInt.toBytes((Integer) null));
assertNull(ValueConverter.BigInt.toBytes((Long) null));
// BigInt values can only be at most BIGINT_BYTE_LEN in length
final byte[] tooFewBytes = new byte[BIGINT_BYTE_SIZE - 1];
final byte[] exactBytes = new byte[BIGINT_BYTE_SIZE];
final byte[] tooManyBytes = new byte[BIGINT_BYTE_SIZE + 1];
assertDoesNotThrow(() -> ValueConverter.BigInt.fromBytes(tooFewBytes));
assertDoesNotThrow(() -> ValueConverter.BigInt.fromBytes(exactBytes));
assertThrows(C3rRuntimeException.class, () -> ValueConverter.BigInt.fromBytes(tooManyBytes));
}
@Test
public void booleanBytesTest() {
assertEquals(
true,
ValueConverter.Boolean.fromBytes(ValueConverter.Boolean.toBytes(true)));
assertEquals(
false,
ValueConverter.Boolean.fromBytes(ValueConverter.Boolean.toBytes(false)));
assertNull(ValueConverter.Boolean.fromBytes(null));
assertNull(ValueConverter.Boolean.fromBytes(null));
}
@Test
public void dateBytesTest() {
assertEquals(1000, ValueConverter.Date.fromBytes(ValueConverter.Date.toBytes(1000)));
assertNull(ValueConverter.Date.fromBytes(null));
assertNull(ValueConverter.Date.toBytes(null));
// Date values can be only INT_BYTE_LEN long
final byte[] tooFewBytes = new byte[INT_BYTE_SIZE - 1];
final byte[] exactBytes = new byte[INT_BYTE_SIZE];
final byte[] tooManyBytes = new byte[INT_BYTE_SIZE + 1];
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Date.fromBytes(tooFewBytes));
assertDoesNotThrow(() -> ValueConverter.Date.fromBytes(exactBytes));
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Date.fromBytes(tooManyBytes));
}
@Test
public void floatBytesTest() {
assertEquals(
(float) 42.0,
ValueConverter.Float.fromBytes(ValueConverter.Float.toBytes((float) 42.0)));
assertNull(ValueConverter.Float.fromBytes(null));
assertNull(ValueConverter.Float.toBytes(null));
// Floats must be exactly Float.BYTES long
final byte[] tooFewBytes = new byte[Float.BYTES - 1];
final byte[] exactBytes = new byte[Float.BYTES];
final byte[] tooManyBytes = new byte[Float.BYTES + 1];
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Float.fromBytes(tooFewBytes));
assertDoesNotThrow(() -> ValueConverter.Float.fromBytes(exactBytes));
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Float.fromBytes(tooManyBytes));
}
@Test
public void doubleBytesTest() {
assertEquals(
42.0,
ValueConverter.Double.fromBytes(ValueConverter.Double.toBytes(42.0)));
assertNull(ValueConverter.Double.fromBytes(null));
assertNull(ValueConverter.Double.toBytes(null));
// Doubles must be exactly Double.BYTES long
final byte[] tooFewBytes = new byte[Double.BYTES - 1];
final byte[] exactBytes = new byte[Double.BYTES];
final byte[] tooManyBytes = new byte[Double.BYTES + 1];
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Double.fromBytes(tooFewBytes));
assertDoesNotThrow(() -> ValueConverter.Double.fromBytes(exactBytes));
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Double.fromBytes(tooManyBytes));
}
@Test
public void intBytesTest() {
assertEquals(
42,
ValueConverter.Int.fromBytes(ValueConverter.Int.toBytes(42)));
assertNull(ValueConverter.Int.fromBytes(null));
assertNull(ValueConverter.Int.toBytes(null));
// Integer values can be at most INT_BYTES_LONG long
final byte[] lessBytes = new byte[INT_BYTE_SIZE - 1];
final byte[] exactBytes = new byte[INT_BYTE_SIZE];
final byte[] tooManyBytes = new byte[INT_BYTE_SIZE + 1];
assertDoesNotThrow(() -> ValueConverter.Int.fromBytes(lessBytes));
assertDoesNotThrow(() -> ValueConverter.Int.fromBytes(exactBytes));
assertThrows(C3rRuntimeException.class, () -> ValueConverter.Int.fromBytes(tooManyBytes));
}
@Test
public void stringBytesTest() {
assertEquals("hello", ValueConverter.String.fromBytes(ValueConverter.String.toBytes("hello")));
assertNull(ValueConverter.String.fromBytes(null));
assertNull(ValueConverter.String.toBytes(null));
}
}
| 2,569 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/exception/C3rRuntimeExceptionTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.exception;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class C3rRuntimeExceptionTest {
private final Exception sensitiveException = new RuntimeException("sensitive message");
@Test
public void getMessageTest() {
// Ensure just the given message is returned and never an underlying message
assertEquals("Doh!", new C3rRuntimeException("Doh!").getMessage());
assertEquals("Doh!",
new C3rRuntimeException("Doh!", sensitiveException).getMessage());
}
@Test
public void getCauseTest() {
// verify the underlying cause exception is being stored and returned as expected
assertEquals(sensitiveException, new C3rRuntimeException("doh!", sensitiveException).getCause());
}
}
| 2,570 |
0 | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/test/java/com/amazonaws/c3r/exception/C3rIllegalArgumentExceptionTest.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.exception;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class C3rIllegalArgumentExceptionTest {
private final Exception sensitiveException = new RuntimeException("sensitive message");
@Test
public void getMessageTest() {
// Ensure just the given message is returned and never an underlying message
assertEquals("Doh!", new C3rIllegalArgumentException("Doh!").getMessage());
assertEquals("Doh!",
new C3rIllegalArgumentException("Doh!", sensitiveException).getMessage());
}
@Test
public void getCauseTest() {
// verify the underlying cause exception is being stored and returned as expected
assertEquals(sensitiveException, new C3rIllegalArgumentException("doh!", sensitiveException).getCause());
}
}
| 2,571 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/CleartextTransformer.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import java.nio.charset.StandardCharsets;
/**
* Performs the marshalling/unmarshalling of data that may be used for cleartext columns between party members in a clean room.
*
* <p>
* This Transformer performs a no-op transform. Marshalling or unmarshalling data will return the data AS IS.
*/
public class CleartextTransformer extends Transformer {
/**
* The version of the {@code CleartextTransformer} for compatability support.
*/
private static final byte[] FORMAT_VERSION = "01:".getBytes(StandardCharsets.UTF_8);
/**
* Empty constructor since no context is needed.
*/
public CleartextTransformer() {
}
/**
* Validates the cleartext and returns it unchanged.
*
* @param cleartext Data to be passed through as cleartext, or null
* @param context Encryption context of cryptographic settings, not applied in this case
* @return {@code cleartext} unmodified
*/
@Override
public byte[] marshal(final byte[] cleartext, final EncryptionContext context) {
validateMarshalledByteLength(cleartext);
return cleartext;
}
/**
* Processes the cleartext data during decryption.
*
* @param ciphertext Cleartext being unmarshalled
* @return {@code ciphertext} unmodified
*/
@Override
public byte[] unmarshal(final byte[] ciphertext) {
return ciphertext;
}
/**
* Gets the current format version.
*
* @return {@link #FORMAT_VERSION}
*/
@Override
public byte[] getVersion() {
return FORMAT_VERSION.clone();
}
/**
* There is no encryption descriptor for this type since no encryption is performed. If this function is called, an error is thrown.
*
* @return Nothing, only throws an exception
* @throws C3rRuntimeException Operation is not supported for CleartextTransformer, exception always thrown
*/
@Override
byte[] getEncryptionDescriptor() {
// No descriptor is used for cleartext data.
throw new C3rRuntimeException("This operation is not supported for the CleartextTransformer.");
}
}
| 2,572 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/Transformer.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.config.ColumnType;
import com.amazonaws.c3r.config.DecryptConfig;
import com.amazonaws.c3r.config.EncryptConfig;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.encryption.providers.SymmetricStaticProvider;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Performs the marshalling/unmarshalling of ciphertext that may be used in a clean room.
*/
public abstract class Transformer {
/**
* Max size of any String post padding. This limit is imposed by Glue.
*/
public static final int MAX_GLUE_STRING_BYTES = 16383;
/**
* Determines whether a given byte[] of marshalled data the appropriate descriptor in the prefix section for the passed
* Transformer.
*
* @param transformer The Transformer providing a descriptor.
* @param value A byte[] of marshalled data.
* @return True if the descriptor for the passed Transformer was found, else false.
*/
public static boolean hasDescriptor(final Transformer transformer, final byte[] value) {
final byte[] descriptor = transformer.getEncryptionDescriptor();
final byte[] version = transformer.getVersion();
// If value is blank or less than the length of the descriptor plus the translator version, short circuit and return false
if (value == null || value.length < version.length + descriptor.length) {
return false;
}
// First characters are the version. Next characters are the descriptor followed by encoded data
final byte[] foundDescriptor = Arrays.copyOfRange(value, version.length, version.length + descriptor.length);
return Arrays.equals(descriptor, foundDescriptor);
}
/**
* Encrypts given cleartext based on settings.
*
* @param cleartext Data to be encrypted, or null.
* @param context Encryption context.
* @return Ciphertext encrypted version of {@code cleartext}, or null depending on {@code context}.
*/
public abstract byte[] marshal(byte[] cleartext, EncryptionContext context);
/**
* Decrypts given plain text based on settings.
*
* @param ciphertext Data to be decrypted, or null.
* @return Cleartext encrypted version of {@code ciphertext}, or null if given null.
*/
public abstract byte[] unmarshal(byte[] ciphertext);
/**
* Each Transformer stores a corresponding version stored as a 2 byte hex representation with a `:` at the end.
* These versions may be used to determine if a marshalled value was produced by a given Transformer version.
*
* @return the version of the Transformer.
*/
public abstract byte[] getVersion();
/**
* Each Transformer stores a corresponding descriptor with a `:` at the end. These descriptors may be used to determine
* if a marshalled value was produced by the corresponding type of Transformer.
*
* @return the descriptor used by the Transformer.
*/
abstract byte[] getEncryptionDescriptor();
/**
* Confirms the ciphertext is not null and is not too long for the database.
*
* @param marshalledBytes Ciphertext
* @throws C3rRuntimeException If the ciphertext was null or longer than the allowed length
*/
void validateMarshalledByteLength(final byte[] marshalledBytes) {
if (marshalledBytes != null && marshalledBytes.length > MAX_GLUE_STRING_BYTES) {
throw new C3rRuntimeException("Marshalled bytes too long for Glue. Glue supports a maximum length of "
+ MAX_GLUE_STRING_BYTES + " bytes but marshalled value was " + marshalledBytes.length + " bytes.");
}
}
/**
* Create cryptographic transforms available for use.
*
* @param secretKey Clean room key used to generate sub-keys for HMAC and encryption
* @param salt Salt that can be publicly known but adds to randomness of cryptographic operations
* @param settings Clean room cryptographic settings
* @param failOnFingerprintColumns Whether to throw an error if a Fingerprint column is seen in the data
* @return Mapping of {@link ColumnType} to the appropriate {@link Transformer}
*/
public static Map<ColumnType, Transformer> initTransformers(final SecretKey secretKey, final String salt, final ClientSettings settings,
final boolean failOnFingerprintColumns) {
final Encryptor encryptor = Encryptor.getInstance(new SymmetricStaticProvider(secretKey,
salt.getBytes(StandardCharsets.UTF_8)));
final Map<ColumnType, Transformer> transformers = new LinkedHashMap<>();
transformers.put(ColumnType.CLEARTEXT, new CleartextTransformer());
transformers.put(ColumnType.FINGERPRINT, new FingerprintTransformer(
secretKey,
salt.getBytes(StandardCharsets.UTF_8),
settings,
failOnFingerprintColumns));
transformers.put(ColumnType.SEALED, new SealedTransformer(encryptor, settings));
return transformers;
}
/**
* Create cryptographic transforms available for use.
*
* @param config The cryptographic settings to use to initialize the transformers
* @return Mapping of {@link ColumnType} to the appropriate {@link Transformer}
*/
public static Map<ColumnType, Transformer> initTransformers(final EncryptConfig config) {
return initTransformers(config.getSecretKey(),
config.getSalt(),
config.getSettings(),
false); // FailOnFingerprintColumns not relevant to encryption
}
/**
* Create cryptographic transforms available for use.
*
* @param config The cryptographic settings to use to initialize the transformers
* @return Mapping of {@link ColumnType} to the appropriate {@link Transformer}
*/
public static Map<ColumnType, Transformer> initTransformers(final DecryptConfig config) {
return initTransformers(config.getSecretKey(),
config.getSalt(),
null, // Settings not relevant to decryption
config.isFailOnFingerprintColumns());
}
}
| 2,573 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/SealedTransformer.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.data.ClientDataInfo;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.Encryptor;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.AdditionalAuthenticatedData;
import com.amazonaws.c3r.internal.InitializationVector;
import com.amazonaws.c3r.internal.Nonce;
import com.amazonaws.c3r.internal.PadUtil;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
/**
* Performs the marshalling/unmarshalling of data that may be used for column transfers between party members in a clean room.
* Ciphertext will be encrypted based on the Provider contained in the Encryptor.
*
* <p>
* Ciphertext produced by this class is meant for transferring and thus can be decrypted by a consumer.
*/
public class SealedTransformer extends Transformer {
/**
* The version of the {@code SealedTransformer} for compatability support.
*/
static final byte[] FORMAT_VERSION = "01:".getBytes(StandardCharsets.UTF_8);
/**
* Indicating what type of cryptographic transformation was applied to the data and how it should be handled during decryption.
*/
static final byte[] ENCRYPTION_DESCRIPTOR = "enc:".getBytes(StandardCharsets.UTF_8);
/**
* Combined format version and encryption description that will be attached as a prefix to the ciphertext so the correct processing is
* done on decryption as a String.
*/
public static final String DESCRIPTOR_PREFIX_STRING =
new String(FORMAT_VERSION, StandardCharsets.UTF_8) + new String(ENCRYPTION_DESCRIPTOR, StandardCharsets.UTF_8);
/**
* Combined format version and encryption description that will be attached as a prefix to the ciphertext so the correct processing is
* done on decryption as bytes.
*/
static final byte[] DESCRIPTOR_PREFIX = DESCRIPTOR_PREFIX_STRING.getBytes(StandardCharsets.UTF_8);
/**
* Used to confirm origin and authenticity of data.
*/
private static final AdditionalAuthenticatedData AAD = new AdditionalAuthenticatedData(DESCRIPTOR_PREFIX);
/**
* How many bytes of the output will be used to store information about the encrypted data since type information and null status is
* lost during encryption.
*/
private static final int DATA_INFO_TAG_BYTE_LENGTH = 1;
/**
* Handles encrypting and decrypting data given the cryptographic settings such as {@code AAD} and key.
*/
private final Encryptor encryptor;
/**
* Cryptographic settings that will be used in this clean room.
*/
private final ClientSettings clientSettings;
/**
* Create an instance of a {@code SealedTransformer}.
*
* @param encryptor A specific HMAC implementation that will handle encryption/decryption
* @param clientSettings Cryptographic settings for the clean room
*/
public SealedTransformer(final Encryptor encryptor, final ClientSettings clientSettings) {
this.encryptor = encryptor;
this.clientSettings = clientSettings;
}
/**
* Marshals cleartext data into Base64 encoded ciphertext using AES-GCM. Marshalled data is in the format:
* <ul>
* <li>FORMAT_VERSION + ENCRYPTION_DESCRIPTOR + NONCE + IV + CIPHERTEXT + AUTH_TAG</li>
* </ul>
* Where:
* <ul>
* <li>FORMAT_VERSION = 2 bytes in hexadecimal followed by a ":", representing the version of the SealedTransformer used for
* marshalling.</li>
* <li>ENCRYPTION_DESCRIPTOR = 4 bytes of "enc:" for marking the column as encrypted.</li>
* <li>NONCE = Provided via the EncryptionContext.</li>
* <li>IV = Generated with the Nonce and the column label stored in the EncryptionContext.</li>
* <li>CIPHERTEXT = Generated with the cleartext + padding (if any) + 2 byte pad size.</li>
* <li>AUTH_TAG = 16 byte AES-GCM tag.</li>
* </ul>
*
* @param cleartext The data to be encrypted, or null
* @param encryptionContext The EncryptionContext for the data to be encrypted
* @return Base64 encoded ciphertext with prefixed encryption data,
* or null if {@code cleartext == null} and {@code ClientSettings.preserveNull() == true}.
* @throws C3rIllegalArgumentException If {@code EncryptionContext} is missing or data type is not supported
*/
@Override
public byte[] marshal(final byte[] cleartext, final EncryptionContext encryptionContext) {
if (encryptionContext == null) {
throw new C3rIllegalArgumentException("An EncryptionContext must be provided when encrypting.");
}
if (encryptionContext.getClientDataType() == null) {
throw new C3rIllegalArgumentException("EncryptionContext missing ClientDataType when encrypting data for column `"
+ encryptionContext.getColumnLabel() + "`.");
}
if (encryptionContext.getClientDataType() != ClientDataType.STRING) {
throw new C3rIllegalArgumentException("Only string columns can be encrypted, but encountered non-string column `"
+ encryptionContext.getColumnLabel() + "`.");
}
if (cleartext == null && clientSettings.isPreserveNulls()) {
return null;
}
final var valueInfo = ClientDataInfo.builder()
.type(encryptionContext.getClientDataType())
.isNull(cleartext == null)
.build();
final byte[] paddedMessage = PadUtil.padMessage(cleartext, encryptionContext);
final InitializationVector iv = InitializationVector.deriveIv(encryptionContext.getColumnLabel(), encryptionContext.getNonce());
final byte[] fullPayload = ByteBuffer.allocate(DATA_INFO_TAG_BYTE_LENGTH + paddedMessage.length)
.put(valueInfo.encode())
.put(paddedMessage).array();
final byte[] ciphertext = encryptor.encrypt(fullPayload, iv, AAD, encryptionContext);
final byte[] base64EncodedCiphertext = buildBase64EncodedMessage(ciphertext, encryptionContext.getNonce(), iv);
final ByteBuffer marshalledMessage = ByteBuffer.allocate(DESCRIPTOR_PREFIX.length + base64EncodedCiphertext.length)
.put(DESCRIPTOR_PREFIX)
.put(base64EncodedCiphertext);
final byte[] marshalledBytes = marshalledMessage.array();
validateMarshalledByteLength(marshalledBytes);
return marshalledBytes;
}
/**
* Unmarshalls Base64 encoded ciphertext data into cleartext.
*
* @param content The Base64 encoded ciphertext with corresponding prefixed encryption data to be decrypted
* @return The decoded cleartext
* @throws C3rIllegalArgumentException If data type is not a string
* @throws C3rRuntimeException If the ciphertext couldn't be decoded from Base64
*/
@Override
public byte[] unmarshal(final byte[] content) {
// Nulls must have been permitted when encrypting.
if (content == null) {
return null;
}
ByteBuffer marshalledCiphertext = ByteBuffer.wrap(content);
// Verify format version
verifyFormatVersion(marshalledCiphertext);
// Verify descriptor
verifyEncryptionDescriptor(marshalledCiphertext);
// Decode Base64 Ciphertext String appearing after the descriptor prefix
final byte[] base64EncodedCiphertext = new byte[marshalledCiphertext.remaining()];
marshalledCiphertext.get(base64EncodedCiphertext);
// Decode Base64 Ciphertext String
try {
marshalledCiphertext = ByteBuffer.wrap(Base64.getDecoder().decode(base64EncodedCiphertext));
} catch (Exception e) {
throw new C3rRuntimeException("Ciphertext could not be decoded from Base64.", e);
}
// Extract nonce.
final Nonce nonce = extractNonce(marshalledCiphertext);
// Extract IV
final InitializationVector iv = extractIv(marshalledCiphertext);
// Extract padded ciphertext data
final byte[] ciphertext = extractCiphertext(marshalledCiphertext);
final EncryptionContext encryptionContext = EncryptionContext.builder()
.nonce(nonce)
.columnLabel("UNMARSHAL") // unused during decryption.
.build();
// Decipher ciphertext
final byte[] payload = encryptor.decrypt(ciphertext, iv, AAD, encryptionContext);
final ClientDataInfo clientDataInfo = ClientDataInfo.decode(payload[0]);
if (clientDataInfo.getType() != ClientDataType.STRING) {
throw new C3rIllegalArgumentException("Expected encrypted data to be of type string, but found unsupported data type: "
+ clientDataInfo.getType());
}
if (clientDataInfo.isNull()) {
return null;
}
final byte[] paddedCleartext = Arrays.copyOfRange(payload, DATA_INFO_TAG_BYTE_LENGTH, payload.length);
// Remove padding
return PadUtil.removePadding(paddedCleartext);
}
@Override
public byte[] getVersion() {
return FORMAT_VERSION.clone();
}
@Override
byte[] getEncryptionDescriptor() {
return ENCRYPTION_DESCRIPTOR.clone();
}
/**
* Concatenates the nonce, IV, and ciphertext and then returns them as the Base64 encoded representation.
*
* @param ciphertext The ciphertext to add to the message
* @param nonce The nonce to add to the message
* @param iv The IV to add to the message
* @return The base64 encoded message
*/
byte[] buildBase64EncodedMessage(final byte[] ciphertext, final Nonce nonce, final InitializationVector iv) {
final byte[] nonceBytes = nonce.getBytes();
final byte[] ivBytes = iv.getBytes();
final byte[] prefixedCiphertext = ByteBuffer.allocate(nonceBytes.length + ivBytes.length + ciphertext.length)
.put(nonceBytes)
.put(ivBytes)
.put(ciphertext)
.array();
return Base64.getEncoder().encode(prefixedCiphertext);
}
/**
* Ensure that the version information in the message matches the current version.
* If there's a version mismatch, decryption may produce unexpected results.
*
* @param ciphertext The original marshalled ciphertext with all content
* @throws C3rRuntimeException If the ciphertext is too short to extract version info from or value was invalid
*/
void verifyFormatVersion(final ByteBuffer ciphertext) {
if (ciphertext.remaining() < FORMAT_VERSION.length) {
throw new C3rRuntimeException("Ciphertext missing version header, unable to decrypt.");
}
// Verify format version
final byte[] versionNumber = new byte[FORMAT_VERSION.length];
ciphertext.get(versionNumber);
if (!Arrays.equals(FORMAT_VERSION, versionNumber)) {
throw new C3rRuntimeException("Ciphertext version mismatch. Expected `" + Arrays.toString(FORMAT_VERSION)
+ "` but was `" + Arrays.toString(versionNumber) + "`.");
}
}
/**
* Verifies that the encryption descriptor is part of the marshalled ciphertext. If not, this may not actually be ciphertext and
* decryption may produce unexpected results.
*
* @param ciphertext The marshalled ciphertext with the FORMAT_VERSION removed from the front
* @throws C3rRuntimeException If the ciphertext is too short to have the descriptor or the descriptor does not match sealed
*/
void verifyEncryptionDescriptor(final ByteBuffer ciphertext) {
if (ciphertext.remaining() < SealedTransformer.ENCRYPTION_DESCRIPTOR.length) {
throw new C3rRuntimeException("Ciphertext missing description header, unable to decrypt.");
}
final byte[] encryptionDescriptor = new byte[ENCRYPTION_DESCRIPTOR.length];
ciphertext.get(encryptionDescriptor);
if (!Arrays.equals(ENCRYPTION_DESCRIPTOR, encryptionDescriptor)) {
throw new C3rRuntimeException("Ciphertext descriptor mismatch. Expected `"
+ new String(ENCRYPTION_DESCRIPTOR, StandardCharsets.UTF_8)
+ "` but was `" + new String(encryptionDescriptor, StandardCharsets.UTF_8) + "`.");
}
}
/**
* Extracts the nonce from the marshalled base64 decoded ciphertext body.
*
* @param ciphertextBody The body of the ciphertext, post base64 decoding
* @return The nonce from the head of the ciphertext body
* @throws C3rRuntimeException If the ciphertext doesn't contain enough bytes for the nonce
*/
Nonce extractNonce(final ByteBuffer ciphertextBody) {
if (ciphertextBody.remaining() < Nonce.NONCE_BYTE_LENGTH) {
throw new C3rRuntimeException("Ciphertext missing nonce, unable to decrypt.");
}
final byte[] nonceBytes = new byte[Nonce.NONCE_BYTE_LENGTH];
ciphertextBody.get(nonceBytes);
return new Nonce(nonceBytes);
}
/**
* Extracts the IV from the marshalled base64 decoded ciphertext body.
*
* @param ciphertextBody The body of the ciphertext, post base64 decoding with
* the nonce already removed from the head
* @return The IV that was used for creating the ciphertext
* @throws C3rRuntimeException If the ciphertext is too short to have an initialization vector
*/
InitializationVector extractIv(final ByteBuffer ciphertextBody) {
if (ciphertextBody.remaining() < InitializationVector.IV_BYTE_LENGTH) {
throw new C3rRuntimeException("Ciphertext missing IV, unable to decrypt.");
}
final byte[] ivBytes = new byte[InitializationVector.IV_BYTE_LENGTH];
ciphertextBody.get(ivBytes);
return new InitializationVector(ivBytes);
}
/**
* Extracts the ciphertext from the marshalled ciphertext.
*
* @param ciphertext The marshalled ciphertext
* @return The ciphertext
*/
byte[] extractCiphertext(final ByteBuffer ciphertext) {
final byte[] paddedCiphertext = new byte[ciphertext.remaining()];
ciphertext.get(paddedCiphertext);
return paddedCiphertext;
}
}
| 2,574 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/FingerprintTransformer.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r;
import com.amazonaws.c3r.config.ClientSettings;
import com.amazonaws.c3r.data.ClientDataInfo;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.keys.KeyUtil;
import com.amazonaws.c3r.encryption.keys.SaltedHkdf;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import lombok.extern.slf4j.Slf4j;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
/**
* Performs the marshalling/unmarshalling of data that may be used for column matching between party members in a clean room.
*
* <p>
* By default, ciphertext will be produced with HmacSHA256. A developer may also choose to encrypt on a per-column or per-row basis.
*
* <p>
* Ciphertext produced by this class is meant for matching and is NOT intended to be returned. It can not be unmarshalled.
* Attempting to unmarshall match data in tests or otherwise will return the data AS IS.
*/
@Slf4j
public class FingerprintTransformer extends Transformer {
/**
* Application context stored inside the created mac key.
*
* @see KeyUtil#HKDF_INFO
*/
static final byte[] HKDF_INFO_BYTES = KeyUtil.HKDF_INFO.getBytes(StandardCharsets.UTF_8);
/**
* Indicating what type of cryptographic transformation was applied to the data and how it should be handled during decryption.
*/
private static final byte[] ENCRYPTION_DESCRIPTOR = "hmac:".getBytes(StandardCharsets.UTF_8);
/**
* The version of the {@code FingerprintTransformer} for compatability support.
*/
private static final byte[] FORMAT_VERSION = "02:".getBytes(StandardCharsets.UTF_8);
/**
* Combined format version and encryption description that will be attached as a prefix to the ciphertext so the correct processing is
* done on decryption as a String.
*/
public static final String DESCRIPTOR_PREFIX_STRING =
new String(FORMAT_VERSION, StandardCharsets.UTF_8) + new String(ENCRYPTION_DESCRIPTOR, StandardCharsets.UTF_8);
/**
* Combined format version and encryption description that will be attached as a prefix to the ciphertext so the correct processing is
* done on decryption as bytes.
*/
static final byte[] DESCRIPTOR_PREFIX = DESCRIPTOR_PREFIX_STRING.getBytes(StandardCharsets.UTF_8);
/**
* Used to create random bytes when {@link ClientSettings#isPreserveNulls} is false.
*/
private static final SecureRandom RANDOM = new SecureRandom();
/**
* Number of bytes of random data when not preserving NULLs.
*/
private static final int NULL_RANDOM_SIZE_BYTES = 32;
/**
* Number of bytes in the HMAC key.
*/
private static final int HMAC_KEY_SIZE = 32;
/**
* HKDF created with mac and salt for this clean room.
*/
private final SaltedHkdf hkdf;
/**
* Cryptographic settings for the clean room.
*/
private final ClientSettings clientSettings;
/**
* Whether fingerprint columns should be permitted in decrypted data or not since they can't be reversed and provide no information.
*/
private final boolean failOnUnmarshal;
/**
* Generates MACs based on {@link KeyUtil#HMAC_ALG} specified algorithm and key.
*/
private final Mac mac;
/**
* Whether to warn user if a fingerprint column was included in decrypted output.
*/
private boolean unmarshalWarningRaised = false;
/**
* Constructs a FingerprintTransformer that will use the HMAC algorithm "HmacSHA256".
*
* @param secretKey The secretKey used to instantiate the HKDF
* @param salt The salt used to instantiate the HKDF
* @param clientSettings ClientSettings to use when determining things like whether to use the same secret key for every column or
* use per column secrets
* @param failOnUnmarshal Whether to throw an error if calling unmarshall on a Fingerprint column
* @throws C3rRuntimeException If the FingerprintTransformer can't be initialized with given cryptographic specifications
*/
public FingerprintTransformer(final SecretKey secretKey, final byte[] salt, final ClientSettings clientSettings,
final boolean failOnUnmarshal) {
this.clientSettings = clientSettings;
this.failOnUnmarshal = failOnUnmarshal;
try {
hkdf = new SaltedHkdf(secretKey, salt);
mac = Mac.getInstance(KeyUtil.HMAC_ALG);
} catch (NoSuchAlgorithmException e) {
throw new C3rRuntimeException("Could not initialize FingerprintTransformer.", e);
}
}
/**
* Marshals cleartext data into Base64 encoded ciphertext using HmacSHA256. Marshalled data is in the format:
* <ul>
* <li>FORMAT_VERSION + ENCRYPTION_DESCRIPTOR + CIPHERTEXT</li>
* </ul>
* Where:
* <ul>
* <li>FORMAT_VERSION = 2 bytes in hexadecimal followed by a ":", representing the version of the FingerprintTransformer used for
* marshalling.</li>
* <li>ENCRYPTION_DESCRIPTOR = 5 bytes of "hmac:" for marking the column as HMACed.</li>
* <li>CIPHERTEXT = Generated with the cleartext and the column label from the EncryptionContext if
* allowJoinsOnColumnsWithDifferentNames is false</li>
* </ul>
*
* @param cleartext The data to be HMACed
* @param encryptionContext The EncryptionContext for the data to be HMACed
* @return base64 encoded HMAC of the cleartext with prefix, or null if given null
* @throws C3rIllegalArgumentException If encryption context is missing or data type is not a string
* @throws C3rRuntimeException If the HMAC algorithm couldn't be configured
*/
@Override
public byte[] marshal(final byte[] cleartext, final EncryptionContext encryptionContext) {
if (encryptionContext == null) {
throw new C3rIllegalArgumentException("An EncryptionContext must be provided when marshaling.");
}
if (encryptionContext.getClientDataType() == null) {
throw new C3rIllegalArgumentException("EncryptionContext missing ClientDataType when encrypting data for column `"
+ encryptionContext.getColumnLabel() + "`.");
}
if (!encryptionContext.getClientDataType().supportsFingerprintColumns()) {
throw new C3rIllegalArgumentException(encryptionContext.getClientDataType() + " is not a type supported by " +
"fingerprint columns.");
}
if (!encryptionContext.getClientDataType().isEquivalenceClassRepresentativeType()) {
throw new C3rIllegalArgumentException(encryptionContext.getClientDataType() + " is not the parent type of its equivalence " +
"class. Expected parent type is " + encryptionContext.getClientDataType().getRepresentativeType() + ".");
}
// Check if a plain null value should be used
if (cleartext == null) {
if (clientSettings.isPreserveNulls()) {
return null;
}
}
// Create final value to be HMAC'd
final byte[] normalizedCleartext = buildFinalizedValue(cleartext, encryptionContext.getClientDataType());
final byte[] key;
if (clientSettings.isAllowJoinsOnColumnsWithDifferentNames()) {
key = hkdf.deriveKey(HKDF_INFO_BYTES, HMAC_KEY_SIZE);
} else {
final byte[] hkdfKeyInfo = (KeyUtil.HKDF_COLUMN_BASED_INFO + encryptionContext.getColumnLabel())
.getBytes(StandardCharsets.UTF_8);
key = hkdf.deriveKey(hkdfKeyInfo, HMAC_KEY_SIZE);
}
final SecretKeySpec secretKeySpec = new SecretKeySpec(key, mac.getAlgorithm());
Arrays.fill(key, (byte) 0); // Safe to zero here. SecretKeySpec takes a clone on instantiation.
try {
mac.init(secretKeySpec);
} catch (InvalidKeyException e) {
throw new C3rRuntimeException("Initialization of hmac failed for target column `"
+ encryptionContext.getColumnLabel() + "`.", e);
}
final byte[] hmacBase64 = Base64.getEncoder().encode(mac.doFinal(normalizedCleartext));
final byte[] marshalledBytes = ByteBuffer.allocate(DESCRIPTOR_PREFIX.length + hmacBase64.length)
.put(DESCRIPTOR_PREFIX)
.put(hmacBase64)
.array();
validateMarshalledByteLength(marshalledBytes);
return marshalledBytes;
}
/**
* Logs a warning when unmarshalling HMACed data since it's a one-way transform unless {@link #failOnUnmarshal} is true then an error
* is thrown.
*
* @param ciphertext The ciphertext of HMAC data or null.
* @return {@code ciphertext} value
* @throws C3rRuntimeException If {@link #failOnUnmarshal} set to true and fingerprint column encountered
*/
@Override
public byte[] unmarshal(final byte[] ciphertext) {
if (failOnUnmarshal) {
throw new C3rRuntimeException("Data encrypted for a fingerprint column was found but is forbidden with current settings.");
}
if (!unmarshalWarningRaised) {
unmarshalWarningRaised = true;
log.warn("Data encrypted for a fingerprint column was found. Encrypted fingerprint column data cannot be decrypted and " +
"will appear as-is in the output.");
}
return ciphertext;
}
/**
* Gets the current format version.
*
* @return {@link #FORMAT_VERSION}
*/
@Override
public byte[] getVersion() {
return FORMAT_VERSION.clone();
}
/**
* Gets the descriptor for the FingerprintTransformer.
*
* @return {@link #ENCRYPTION_DESCRIPTOR}
*/
@Override
byte[] getEncryptionDescriptor() {
return ENCRYPTION_DESCRIPTOR.clone();
}
/**
* Build the bytes to be HMAC'd. This includes replacing {@code null} values with a random string and adding the
* equivalence class information to the value.
*
* @param cleartext The data to be HMAC'd
* @param type The equivalence class for the data
* @return The value with the equivalence class information and {@code null}s replaced with random data
*/
private byte[] buildFinalizedValue(final byte[] cleartext, final ClientDataType type) {
final byte[] typedCleartext;
if (cleartext == null) {
typedCleartext = new byte[NULL_RANDOM_SIZE_BYTES + 1];
RANDOM.nextBytes(typedCleartext);
typedCleartext[NULL_RANDOM_SIZE_BYTES] = ClientDataInfo.builder().type(type).isNull(true).build().encode();
} else {
typedCleartext = ByteBuffer.allocate(cleartext.length + 1)
.put(cleartext)
.put(ClientDataInfo.builder().type(type).isNull(false).build().encode())
.array();
}
return typedCleartext;
}
} | 2,575 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Handles the transformation of cleartext data into encrypted data.
*
* <p>
* This package takes in the settings for a clean room, a data file and then preforms the necessary transformations to create the
* encrypted output. The row marshallers and unmarshallers (see {@link com.amazonaws.c3r.action}) are the main entry point into the SDK.
* To encrypt data, create a new instance of a {@link com.amazonaws.c3r.action.RowMarshaller} for the particular data format you are using,
* then calling {@link com.amazonaws.c3r.action.RowMarshaller#marshal()} and {@link com.amazonaws.c3r.action.RowMarshaller#close()} will
* transform the cleartext data according to the schema into a file containing the encrypted data. To decrypt data, an instance of a
* {@link com.amazonaws.c3r.action.RowUnmarshaller} for the particular data type is created, then
* {@link com.amazonaws.c3r.action.RowUnmarshaller#unmarshal()} and {@link com.amazonaws.c3r.action.RowUnmarshaller#close()} are called.
*
* <p>
* The settings are stored in an instance of {@link com.amazonaws.c3r.config.EncryptConfig} or
* {@link com.amazonaws.c3r.config.DecryptConfig} for the respective mode of operation. The schema information is kept in an instance of
* the {@link com.amazonaws.c3r.config.TableSchema} which is backed by several implementations. Between the configuration and schema
* classes, the row marshallers and unmarshallers will have the information they need to do cryptographic transforms.
*
* <p>
* The rest of the packages and classes inside this package are in support of these top level classes. Classes in the package
* {@code com.amazonaws.config} will be used in the course of creating the cryptographic configurations but the remaining classes are not
* meant to be used directly for development as they may change at will.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r;
| 2,576 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/Encryptor.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption;
import com.amazonaws.c3r.encryption.keys.DerivedEncryptionKey;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
import com.amazonaws.c3r.encryption.materials.DecryptionMaterials;
import com.amazonaws.c3r.encryption.materials.EncryptionMaterials;
import com.amazonaws.c3r.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.AdditionalAuthenticatedData;
import com.amazonaws.c3r.internal.InitializationVector;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.GCMParameterSpec;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* This class handles the encryption and decryption of data using the CryptographicMaterialsProvider provided at instantiation.
*/
public final class Encryptor {
/**
* Configuration for encryption settings.
*/
private static final String SYMMETRIC_ENCRYPTION_MODE = "AES/GCM/NoPadding";
/**
* MAC length.
*/
private static final int AUTHENTICATION_TAG_LENGTH = 128;
/**
* Handles cryptographic operations.
*/
private final EncryptionMaterialsProvider encryptionMaterialsProvider;
/**
* Create wrapper for cryptographic operations.
*
* @param provider Underlying cryptographic implementation
*/
private Encryptor(final EncryptionMaterialsProvider provider) {
this.encryptionMaterialsProvider = provider;
}
/**
* Get an instance for cryptographic operations using the specified implementation.
*
* @param provider Underlying cryptographic implementation
* @return Wrapper for cryptographic operations
*/
public static Encryptor getInstance(final EncryptionMaterialsProvider provider) {
return new Encryptor(provider);
}
/**
* Encrypts the cleartext data into ciphertext.
*
* @param cleartext The cleartext data to be encrypted.
* @param iv The IV to use for encryption.
* @param aad The AAD to use for encryption.
* @param encryptionContext The EncryptionContext to use for encryption.
* @return The encrypted cleartext data
*/
public byte[] encrypt(final byte[] cleartext, final InitializationVector iv, final AdditionalAuthenticatedData aad,
final EncryptionContext encryptionContext) {
final EncryptionMaterials encryptionMaterials = encryptionMaterialsProvider.getEncryptionMaterials(encryptionContext);
final DerivedRootEncryptionKey key = encryptionMaterials.getRootEncryptionKey();
return transform(cleartext, iv, aad, encryptionContext, key, Cipher.ENCRYPT_MODE);
}
/**
* Decrypts the ciphertext data into cleartext.
*
* @param ciphertext The ciphertext data to be decrypted
* @param iv The IV to use for decryption
* @param aad The AAD to use for decryption
* @param encryptionContext The EncryptionContext to use for decryption
* @return The decrypted cleartext data
*/
public byte[] decrypt(final byte[] ciphertext, final InitializationVector iv, final AdditionalAuthenticatedData aad,
final EncryptionContext encryptionContext) {
final DecryptionMaterials encryptionMaterials = encryptionMaterialsProvider.getDecryptionMaterials(encryptionContext);
final DerivedRootEncryptionKey key = encryptionMaterials.getRootDecryptionKey();
return transform(ciphertext, iv, aad, encryptionContext, key, Cipher.DECRYPT_MODE);
}
/**
* Decrypt or encrypt data.
*
* @param message Data to operate on
* @param iv Initialization vector
* @param aad Additional authenticated data
* @param encryptionContext Cryptographic implementation to use
* @param derivedRootEncryptionKey Key to use
* @param mode Which cryptographic operation to perform
* @return Results from cryptographic computation
* @throws C3rIllegalArgumentException If the message, encryption information, block size or padding is incorrect.
* @throws C3rRuntimeException If the key could not initialize with specified settings
*/
private byte[] transform(final byte[] message, final InitializationVector iv, final AdditionalAuthenticatedData aad,
final EncryptionContext encryptionContext, final DerivedRootEncryptionKey derivedRootEncryptionKey,
final int mode) {
if (message == null) {
throw new C3rIllegalArgumentException("Expected a message to transform but was given null.");
}
if (encryptionContext == null) {
throw new C3rIllegalArgumentException("An EncryptionContext must always be provided when encrypting/decrypting, but was null.");
}
final DerivedEncryptionKey derivedEncryptionKey = new DerivedEncryptionKey(derivedRootEncryptionKey, encryptionContext.getNonce());
final GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(AUTHENTICATION_TAG_LENGTH, iv.getBytes());
final Cipher cipher;
try {
cipher = Cipher.getInstance(SYMMETRIC_ENCRYPTION_MODE);
cipher.init(mode, derivedEncryptionKey, gcmParameterSpec);
} catch (InvalidAlgorithmParameterException | InvalidKeyException e) {
throw new C3rRuntimeException("Initialization for cipher `" + SYMMETRIC_ENCRYPTION_MODE + "` failed.", e);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new C3rRuntimeException("Requested cipher `" + SYMMETRIC_ENCRYPTION_MODE + "` is not available.", e);
}
if (aad != null) {
cipher.updateAAD(aad.getBytes());
}
try {
return cipher.doFinal(message);
} catch (IllegalBlockSizeException | BadPaddingException e) {
final String error;
if (mode == Cipher.ENCRYPT_MODE) {
error = "Failed to encrypt data for target column `" + encryptionContext.getColumnLabel() + "`.";
} else {
error = "Failed to decrypt.";
}
throw new C3rRuntimeException(error, e);
}
}
}
| 2,577 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/EncryptionContext.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption;
import com.amazonaws.c3r.config.ColumnInsight;
import com.amazonaws.c3r.config.PadType;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.encryption.materials.DecryptionMaterials;
import com.amazonaws.c3r.encryption.materials.EncryptionMaterials;
import com.amazonaws.c3r.encryption.providers.EncryptionMaterialsProvider;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Nonce;
import com.amazonaws.c3r.internal.Validatable;
import lombok.Builder;
import lombok.Getter;
/**
* This class serves to provide additional useful data to {@link EncryptionMaterialsProvider}s so
* they can more intelligently sealed the proper {@link EncryptionMaterials} or {@link
* DecryptionMaterials} for use.
*/
@Getter
public final class EncryptionContext implements Validatable {
/**
* Name of the column.
*/
private final String columnLabel;
/**
* Data type of field before encryption.
*/
private final ClientDataType clientDataType;
/**
* Pseudorandom number.
*/
private final Nonce nonce;
/**
* Type of padding used on the cleartext value, or {@code null} if padding is not applicable in this context.
*/
private final PadType padType;
/**
* Length of padding to use in bytes if applicable, else {@code null}.
*/
private final Integer padLength;
/**
* Maximum length in bytes of a value for this column.
*/
private final int maxValueLength;
/**
* Create the configuration for encrypting this particular column.
*
* @param columnLabel Name of column
* @param nonce Pseudorandom number
* @param padType Type of padding used on the column, or {@code null} if not applicable
* @param padLength Length of padding in bytes, or {@code null} if not applicable
* @param maxValueLength Maximum length in bytes of the values for this context
* @param clientDataType Data type before encryption
*/
@Builder
private EncryptionContext(final String columnLabel, final Nonce nonce, final PadType padType, final Integer padLength,
final int maxValueLength, final ClientDataType clientDataType) {
this.columnLabel = columnLabel;
this.nonce = nonce;
this.padType = padType;
this.padLength = padLength;
this.maxValueLength = maxValueLength;
this.clientDataType = clientDataType;
validate();
}
/**
* Create the configuration for encrypting this particular column.
*
* @param columnInsight Information about the column
* @param nonce Pseudorandom number
* @param clientDataType Data type before encryption
*/
public EncryptionContext(final ColumnInsight columnInsight,
final Nonce nonce,
final ClientDataType clientDataType) {
columnLabel = columnInsight.getTargetHeader().toString();
this.clientDataType = clientDataType;
this.nonce = nonce;
padType = (columnInsight.getPad() != null) ? columnInsight.getPad().getType() : null;
padLength = (columnInsight.getPad() != null) ? columnInsight.getPad().getLength() : null;
maxValueLength = columnInsight.getMaxValueLength();
validate();
}
/**
* Gets the target padded length of values in the column.
*
* @return the target padded length for values in the column
*/
public Integer getTargetPaddedLength() {
if (padType == PadType.MAX) {
return padLength + maxValueLength;
}
return padLength;
}
/**
* Make sure column label is specified.
*/
@Override
public void validate() {
if (columnLabel == null || columnLabel.isBlank()) {
throw new C3rIllegalArgumentException("A column label must be provided in the EncryptionContext.");
}
}
} | 2,578 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Cryptographic functions for C3R.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r.encryption; | 2,579 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/AbstractRawMaterials.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
/**
* Combines {@link DecryptionMaterials} and {@link EncryptionMaterials} into one class for managing all cryptographic operations.
*/
public abstract class AbstractRawMaterials implements DecryptionMaterials, EncryptionMaterials {
}
| 2,580 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/EncryptionMaterials.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
/**
* Interface that specifies functions for encryption key usage.
*/
public interface EncryptionMaterials extends CryptographicMaterials {
/**
* Get the root encryption key in use.
*
* @return Encryption key
*/
DerivedRootEncryptionKey getRootEncryptionKey();
} | 2,581 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/SymmetricRawMaterials.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
/**
* Stores a symmetric root key, managing the encryption and decryption keys derived from it.
*/
public class SymmetricRawMaterials extends AbstractRawMaterials {
/**
* Symmetric key used for cryptographic operations.
*/
private final DerivedRootEncryptionKey cryptoKey;
/**
* Stores root symmetric encryption key for managing encryption/decryption operations.
*
* @param encryptionKey Symmetric key
*/
public SymmetricRawMaterials(final DerivedRootEncryptionKey encryptionKey) {
this.cryptoKey = encryptionKey;
}
/**
* {@inheritDoc}
*/
@Override
public DerivedRootEncryptionKey getRootEncryptionKey() {
return cryptoKey;
}
/**
* {@inheritDoc}
*/
@Override
public DerivedRootEncryptionKey getRootDecryptionKey() {
return cryptoKey;
}
} | 2,582 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/DecryptionMaterials.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
/**
* Interface that specifies functions for decryption key usage.
*/
public interface DecryptionMaterials extends CryptographicMaterials {
/**
* Get the root decryption key in use.
*
* @return Decryption key
*/
DerivedRootEncryptionKey getRootDecryptionKey();
} | 2,583 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/CryptographicMaterials.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.materials;
/**
* Top level interface for all the materials. Anything meant to be global to all the materials should be added here.
*/
public interface CryptographicMaterials {
} | 2,584 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/materials/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Classes for managing cryptographic keys.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r.encryption.materials; | 2,585 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/providers/SymmetricStaticProvider.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.providers;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.keys.DerivedRootEncryptionKey;
import com.amazonaws.c3r.encryption.materials.DecryptionMaterials;
import com.amazonaws.c3r.encryption.materials.EncryptionMaterials;
import com.amazonaws.c3r.encryption.materials.SymmetricRawMaterials;
import javax.crypto.SecretKey;
/**
* This EncryptionMaterialsProvider may be used when a SecretKey/salt has been shared out of band or is otherwise provided
* programmatically. Data encrypted with this EncryptionMaterialsProvider may be decrypted with the same symmetric key and salt provided at
* construction.
*/
public class SymmetricStaticProvider implements EncryptionMaterialsProvider {
/**
* Implements a symmetric key cryptographic algorithm.
*/
private final SymmetricRawMaterials materials;
/**
* Creates a handler for symmetric keys, using {@code encryptionKey} and {@code salt} to generate sub-keys as needed.
*
* @param encryptionKey the key materials for the root key
* @param salt the salt for the root key
*/
public SymmetricStaticProvider(final SecretKey encryptionKey, final byte[] salt) {
materials = new SymmetricRawMaterials(new DerivedRootEncryptionKey(encryptionKey, salt));
}
/**
* Returns the {@code encryptionKey} provided to the constructor.
*/
@Override
public DecryptionMaterials getDecryptionMaterials(final EncryptionContext context) {
return new SymmetricRawMaterials(materials.getRootEncryptionKey());
}
/**
* Returns the {@code encryptionKey} provided to the constructor.
*/
@Override
public EncryptionMaterials getEncryptionMaterials(final EncryptionContext context) {
return new SymmetricRawMaterials(materials.getRootEncryptionKey());
}
/**
* Does nothing.
*/
@Override
public void refresh() {
// Do nothing
}
} | 2,586 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/providers/EncryptionMaterialsProvider.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.providers;
import com.amazonaws.c3r.encryption.EncryptionContext;
import com.amazonaws.c3r.encryption.materials.DecryptionMaterials;
import com.amazonaws.c3r.encryption.materials.EncryptionMaterials;
/**
* Interface for providing encryption materials. Implementations are free to use any strategy for
* providing encryption materials, such as simply providing static material that doesn't change, or
* more complicated implementations, such as integrating with existing key management systems.
*/
public interface EncryptionMaterialsProvider {
/**
* Retrieves encryption materials matching the specified description from some source.
*
* @param context Information to assist in selecting the proper return value. The implementation
* is free to determine the minimum necessary for successful processing
* @return The encryption materials that match the description, or null if no matching encryption
* materials found
*/
DecryptionMaterials getDecryptionMaterials(EncryptionContext context);
/**
* Returns EncryptionMaterials which the caller can use for encryption. Each implementation of
* EncryptionMaterialsProvider can choose its own strategy for loading encryption material. For
* example, an implementation might load encryption material from an existing key management
* system, or load new encryption material when keys are rotated.
*
* @param context Information to assist in selecting the proper return value. The implementation
* is free to determine the minimum necessary for successful processing
* @return EncryptionMaterials which the caller can use to encrypt or decrypt data
*/
EncryptionMaterials getEncryptionMaterials(EncryptionContext context);
/**
* Forces this encryption materials provider to refresh its encryption material. For many
* implementations of encryption materials provider, this may simply be a no-op, such as any
* encryption materials provider implementation that vends static/non-changing encryption
* material. For other implementations that vend different encryption material throughout their
* lifetime, this method should force the encryption materials provider to refresh its encryption
* material.
*/
void refresh();
}
| 2,587 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/providers/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Cryptographic implementations for key generation algorithms.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r.encryption.providers; | 2,588 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/DerivedRootEncryptionKey.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
/**
* This class is a wrapper on SecretKeys. It adds type safety for ensuring that a DerivedRootEncryptionKey is <b>never</b> used for
* encrypting individual data and that only a DerivedRootEncryptionKey may be used for generating {@link DerivedEncryptionKey} objects.
*/
public class DerivedRootEncryptionKey extends Key {
/**
* Creates the key to be used for all future key delegations. Note that this key and salt pair must be shared between all parties.
*
* @param secretKey The key to be used to initialize the root key
* @param salt The salt to be used to initialize the root key
*/
public DerivedRootEncryptionKey(final SecretKey secretKey, final byte[] salt) {
super(deriveRootEncryptionKey(secretKey, salt));
}
/**
* Creates the key to be used for all future key delegations. Note that this key and salt pair must be shared across all members of
* the collaboration.
*
* @param secretKey The key to be used to initialize the root key
* @param salt The salt to be used to initialize the root key
* @return A key derived from the HMAC of the key provided
*/
private static SecretKey deriveRootEncryptionKey(final SecretKey secretKey, final byte[] salt) {
final SaltedHkdf hkdf = new SaltedHkdf(secretKey, salt);
return new SecretKeySpec(hkdf.deriveKey(KeyUtil.HKDF_INFO.getBytes(StandardCharsets.UTF_8),
KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH), KeyUtil.KEY_ALG);
}
}
| 2,589 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/DerivedEncryptionKey.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import com.amazonaws.c3r.internal.Nonce;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* This class is a wrapper on SecretKeys. It adds type safety for ensuring that only a DerivedEncryptionKey is used for encrypting
* individual data.
*/
public class DerivedEncryptionKey extends Key {
/**
* Sets up the key with a shared secret along with a nonce to add randomness.
*
* @param derivedRootEncryptionKey Shared secret used to generate symmetric key
* @param nonce Adds extra randomness
*/
public DerivedEncryptionKey(final DerivedRootEncryptionKey derivedRootEncryptionKey, final Nonce nonce) {
super(deriveEncryptionKey(derivedRootEncryptionKey, nonce));
}
/**
* Derives new encryption key from the root encryption key and nonce.
*
* @param derivedRootEncryptionKey The secret key to derive a new key from
* @param nonce a random byte sequence
* @return a newly derived encryption key
* @throws C3rIllegalArgumentException If the key material doesn't meet requirements
* @throws C3rRuntimeException If the algorithm requested is not available
*/
private static SecretKey deriveEncryptionKey(final DerivedRootEncryptionKey derivedRootEncryptionKey, final Nonce nonce) {
if (derivedRootEncryptionKey == null) {
throw new C3rIllegalArgumentException("A root key must be provided when deriving an encryption key, but was null.");
} else if (nonce == null) {
throw new C3rIllegalArgumentException("A nonce must be provided when deriving an encryption key, but was null.");
}
final byte[] key = derivedRootEncryptionKey.getEncoded();
if (key.length != KeyUtil.SHARED_SECRET_KEY_BYTE_LENGTH) {
throw new C3rIllegalArgumentException("A root key must be 32 bytes, but was " + key.length + " bytes.");
}
final byte[] nonceBytes = nonce.getBytes();
final ByteBuffer buffer = ByteBuffer.allocate(key.length + nonceBytes.length);
buffer.put(key);
buffer.put(nonceBytes);
final MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance(KeyUtil.HASH_ALG);
} catch (NoSuchAlgorithmException e) {
throw new C3rRuntimeException("Requested algorithm `" + KeyUtil.HASH_ALG + "` is not available!", e);
}
return new SecretKeySpec(messageDigest.digest(buffer.array()), KeyUtil.KEY_ALG);
}
}
| 2,590 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/KeyUtil.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
* Utility class for key management and general key information.
*/
public abstract class KeyUtil {
/**
* Key generation algorithm.
*/
public static final String KEY_ALG = "AES";
/**
* Environment variable shared secret should be stored in for CLI users.
*/
public static final String KEY_ENV_VAR = "C3R_SHARED_SECRET";
/**
* Algorithm to use for HMAC.
*/
public static final String HMAC_ALG = "HmacSHA256";
/**
* Application specific context to add randomness to key generation.
*/
public static final String HKDF_INFO = "c3r-encryption-primary-aes-gcm-256";
/**
* Application specific context to add randomness to key generation.
*/
public static final String HKDF_COLUMN_BASED_INFO = "c3r-hmac-sha256-col-";
/**
* Algorithm to use for hashing.
*/
public static final String HASH_ALG = "SHA-256";
/**
* How long in bytes the shared secret should be.
*/
public static final int SHARED_SECRET_KEY_BYTE_LENGTH = 32;
/**
* Help message for how the CLI users should pass in the shared secret.
*/
private static final String CLI_ENV_VAR_MESSAGE =
"(CLI users should inspect the value passed via the `" + KEY_ENV_VAR + "` environment variable.)";
/**
* Construct a {@code SecretKey} from the Base64 encoded contents of the string.,
* checking its size is greater than or equal to {@value #SHARED_SECRET_KEY_BYTE_LENGTH} bytes.
*
* @param base64EncodedKeyMaterial Base64-encoded shared secret key
* @return A SecretKey containing the bytes read from the environment variable
* @throws C3rIllegalArgumentException If the key material is invalid
*/
public static SecretKey sharedSecretKeyFromString(final String base64EncodedKeyMaterial) {
if (base64EncodedKeyMaterial == null) {
throw new C3rIllegalArgumentException("Shared secret key was null. " + CLI_ENV_VAR_MESSAGE);
}
final byte[] keyMaterial;
try {
keyMaterial = Base64.getDecoder().decode(base64EncodedKeyMaterial);
} catch (IllegalArgumentException e) {
throw new C3rIllegalArgumentException(
"Shared secret key could not be decoded from Base64. Please verify that the key material is encoded as Base64. "
+ CLI_ENV_VAR_MESSAGE, e);
}
if (keyLengthIsValid(keyMaterial.length)) {
return new SecretKeySpec(keyMaterial, KEY_ALG);
} else {
throw new C3rIllegalArgumentException("Shared secret key was expected to have at least "
+ SHARED_SECRET_KEY_BYTE_LENGTH + " bytes, but was found to contain " +
keyMaterial.length + " bytes. "
+ CLI_ENV_VAR_MESSAGE);
}
}
/**
* Ensure key is at least {@value #SHARED_SECRET_KEY_BYTE_LENGTH} bytes long.
*
* @param byteLength Actual key length
* @return {@code true} if key is at least as long as required bytes
*/
private static boolean keyLengthIsValid(final long byteLength) {
return byteLength >= SHARED_SECRET_KEY_BYTE_LENGTH;
}
}
| 2,591 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/HmacKeyDerivationFunction.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.util.Arrays;
/**
* HMAC-based Key Derivation Function. Adapted from Hkdf.java in aws-dynamodb-encryption-java
*
* @see <a href="http://tools.ietf.org/html/rfc5869">RFC 5869</a>
*/
final class HmacKeyDerivationFunction {
/**
* Limit on key length relative to HMAC length.
*/
private static final int DERIVED_KEY_LIMITER = 255;
/**
* Empty byte array.
*/
private static final byte[] EMPTY_ARRAY = new byte[0];
/**
* Encryption algorithm to use.
*/
private final String algorithm;
/**
* Cryptographic family algorithm is from.
*/
private final Provider provider;
/**
* Symmetric key.
*/
private SecretKey prk = null;
/**
* Returns an {@code HmacKeyDerivationFunction} object using the specified algorithm.
*
* @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the
* <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" >
* Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information
* about standard algorithm names
* @param provider Desired Java Security API provider
* @throws C3rIllegalArgumentException If the HMAC algorithm is not being used
*/
private HmacKeyDerivationFunction(final String algorithm, final Provider provider) {
if (!algorithm.startsWith("Hmac")) {
throw new C3rIllegalArgumentException("Invalid algorithm `" + algorithm + "`. Hkdf may only be used with Hmac algorithms.");
}
this.algorithm = algorithm;
this.provider = provider;
}
/**
* Returns an {@code HmacKeyDerivationFunction} object using the specified algorithm.
*
* @param algorithm the standard name of the requested MAC algorithm. See the Mac section in the
* <a href=
* "http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac" >
* Java Cryptography Architecture Standard Algorithm Name Documentation</a> for information
* about standard algorithm names
* @return the new {@code Hkdf} object
* @throws C3rRuntimeException If no Provider supports a MacSpi implementation for the
* specified algorithm
*/
public static HmacKeyDerivationFunction getInstance(final String algorithm) {
try {
// Constructed specifically to sanity-test arguments.
final Mac mac = Mac.getInstance(algorithm);
return new HmacKeyDerivationFunction(algorithm, mac.getProvider());
} catch (NoSuchAlgorithmException e) {
throw new C3rRuntimeException("Requested MAC algorithm isn't available on this system.", e);
}
}
/**
* Initializes this Hkdf with input keying material. A default salt of HashLen zeros will be used
* (where HashLen is the length of the return value of the supplied algorithm).
*
* @param ikm the Input Keying Material
*/
public void init(final byte[] ikm) {
init(ikm, null);
}
/**
* Initializes this Hkdf with input keying material and a salt. If {@code salt}
* is {@code null} or of length 0, then a default salt of HashLen zeros will be
* used (where HashLen is the length of the return value of the supplied algorithm).
*
* @param salt the salt used for key extraction (optional)
* @param ikm the Input Keying Material
* @throws C3rRuntimeException If the symmetric key could not be initialized
*/
public void init(final byte[] ikm, final byte[] salt) {
byte[] realSalt = (salt == null) ? EMPTY_ARRAY : salt.clone();
byte[] rawKeyMaterial = EMPTY_ARRAY;
try {
final Mac extractionMac = Mac.getInstance(algorithm, provider);
if (realSalt.length == 0) {
realSalt = new byte[extractionMac.getMacLength()];
Arrays.fill(realSalt, (byte) 0);
}
extractionMac.init(new SecretKeySpec(realSalt, algorithm));
rawKeyMaterial = extractionMac.doFinal(ikm);
this.prk = new SecretKeySpec(rawKeyMaterial, algorithm);
} catch (GeneralSecurityException e) {
// We've already checked all the parameters so no exceptions
// should be possible here.
throw new C3rRuntimeException("Unexpected exception", e);
} finally {
Arrays.fill(rawKeyMaterial, (byte) 0); // Zeroize temporary array
}
}
/**
* Returns a pseudorandom key of {@code length} bytes.
*
* @param info optional context and application specific information (can be a zero-length array)
* @param length number of bytes the key should have
* @return a pseudorandom key of {@code length} bytes
* @throws C3rIllegalArgumentException If this object has not been initialized
*/
public byte[] deriveKey(final byte[] info, final int length) {
if (length < 0) {
throw new C3rIllegalArgumentException("Length must be a non-negative value.");
}
assertInitialized();
final byte[] result = new byte[length];
final Mac mac = createMac();
if (length > DERIVED_KEY_LIMITER * mac.getMacLength()) {
throw new C3rIllegalArgumentException("Requested keys may not be longer than 255 times the underlying HMAC length.");
}
byte[] t = EMPTY_ARRAY;
try {
int loc = 0;
byte i = 1;
while (loc < length) {
mac.update(t);
mac.update(info);
mac.update(i);
t = mac.doFinal();
for (int x = 0; x < t.length && loc < length; x++, loc++) {
result[loc] = t[x];
}
i++;
}
} finally {
Arrays.fill(t, (byte) 0); // Zeroize temporary array
}
return result;
}
/**
* Create a message authentication code using the symmetric key generated by the input keying material and salt
* {@link #init(byte[], byte[])}.
*
* @return MAC generated by requested algorithm and symmetric key
* @throws C3rRuntimeException If the MAC couldn't be generated
*/
private Mac createMac() {
try {
final Mac mac = Mac.getInstance(algorithm, provider);
mac.init(prk);
return mac;
} catch (NoSuchAlgorithmException | InvalidKeyException ex) {
// We've already validated that this algorithm/key is correct.
throw new C3rRuntimeException("Internal error: failed to create MAC for " + algorithm + ".", ex);
}
}
/**
* Throws an {@code C3rRuntimeException} if this object has not been initialized.
*
* @throws C3rRuntimeException If this object has not been initialized
*/
private void assertInitialized() {
if (prk == null) {
throw new C3rRuntimeException("Hkdf has not been initialized");
}
}
} | 2,592 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/Key.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import javax.crypto.SecretKey;
/**
* This class is a wrapper on SecretKeys, providing bare minimum validation on a SecretKey. The class is package private and may not be
* instantiated. See child classes {@link DerivedRootEncryptionKey} and {@link DerivedEncryptionKey} for more info.
*/
abstract class Key implements SecretKey {
/**
* Symmetric key.
*/
protected final SecretKey secretKey;
/**
* Initialize symmetric key and validate the value.
*
* @param secretKey Symmetric key
*/
Key(final SecretKey secretKey) {
this.secretKey = secretKey;
validate();
}
/**
* Make sure key is not {@code null}.
*
* @throws C3rIllegalArgumentException If key is {@code null}
*/
public void validate() {
if (secretKey == null) {
throw new C3rIllegalArgumentException("The SecretKey must not be null.");
}
}
/**
* {@inheritDoc}
*/
@Override
public String getAlgorithm() {
return secretKey.getAlgorithm();
}
/**
* {@inheritDoc}
*/
@Override
public String getFormat() {
return secretKey.getFormat();
}
/**
* {@inheritDoc}
*/
@Override
public byte[] getEncoded() {
return secretKey.getEncoded();
}
}
| 2,593 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/SaltedHkdf.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.encryption.keys;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import javax.crypto.SecretKey;
/**
* The SaltedHkdf is a wrapper on the HmacKeyDerivationFunction class, exposing only the deriveKey function call.
* HmacKeyDerivationFunction is pulled from the AWS Encryption SDK and is otherwise unmodified, but provides more functionality than
* desirable.
*/
public class SaltedHkdf {
/**
* The algorithm to use to derive keys.
*/
private final HmacKeyDerivationFunction hkdf;
/**
* Creates the HKDF to be used for root key derivation or HMACed columns. Note that this key and salt pair must be shared across all
* members of the collaboration.
*
* @param secretKey The key to be used to initialize the HKDF
* @param salt The salt to be used to initialize the HKDF
* @throws C3rIllegalArgumentException If the key and salt aren't valid
* @throws C3rRuntimeException If the root key couldn't be created
*/
public SaltedHkdf(final SecretKey secretKey, final byte[] salt) {
if (secretKey == null) {
throw new C3rIllegalArgumentException("A SecretKey must be provided when deriving the root encryption key, but was null.");
}
if (salt == null || salt.length == 0) {
throw new C3rIllegalArgumentException("A salt must be provided when deriving the root encryption key, but was null or empty.");
}
hkdf = HmacKeyDerivationFunction.getInstance(KeyUtil.HMAC_ALG);
hkdf.init(secretKey.getEncoded(), salt);
}
/**
* Derive key from using extra randomness added by {@code info}.
*
* @param info Extra randomness the application can optionally add during key generation
* @param length Length of generated key
* @return Pseudorandom key of {@code length} bytes
*/
public byte[] deriveKey(final byte[] info, final int length) {
return hkdf.deriveKey(info, length);
}
}
| 2,594 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/encryption/keys/package-info.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
/**
* Classes that generate the various keys used for different cryptographic operations.
*
* <p>
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.amazonaws.c3r.encryption.keys; | 2,595 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/config/ColumnSchema.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.internal.Validatable;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import javax.annotation.Nullable;
import java.io.Serializable;
import java.util.UUID;
/**
* Column configuration data specified by a user.
*/
@EqualsAndHashCode
@Getter
public class ColumnSchema implements Validatable, Serializable {
/**
* What cryptographic transform to apply to data.
*/
private final ColumnType type;
/**
* What types of padding should be used if column type is {@link ColumnType#SEALED}.
*
* @see Pad
* @see PadType
*/
private final Pad pad;
/**
* Column name/index that should be transformed into output data.
*/
private final ColumnHeader sourceHeader;
/**
* Name of column to use in output data file.
*/
private final ColumnHeader targetHeader;
/**
* Name of column to use internally. Generated as a UUID.
*/
@EqualsAndHashCode.Exclude
private final transient ColumnHeader internalHeader;
/**
* Creates a specification for transforming data during encryption.
*
* @param sourceHeader Name or index of column in the input file
* @param targetHeader Name of the column in the output file
* @param internalHeader Name of the column in the temporary SQL table
* @param pad What kind of padding to use if the type is {@link ColumnType#SEALED}, {@code null} otherwise
* @param type What cryptographic primitive should be used
*/
@Builder
private ColumnSchema(final ColumnHeader sourceHeader,
final ColumnHeader targetHeader,
@Nullable final ColumnHeader internalHeader,
final Pad pad,
final ColumnType type) {
this.sourceHeader = sourceHeader;
this.targetHeader = ColumnHeader.deriveTargetColumnHeader(sourceHeader, targetHeader, type);
this.internalHeader = internalHeader != null ? internalHeader : new ColumnHeader(UUID.randomUUID().toString());
this.pad = pad;
this.type = type;
validate();
}
/**
* Copies one schema in to another.
*
* @param columnSchema Existing schema to copy
*/
public ColumnSchema(final ColumnSchema columnSchema) {
this(columnSchema.sourceHeader, columnSchema.targetHeader, columnSchema.getInternalHeader(), columnSchema.pad, columnSchema.type);
}
/**
* Check that rules for a ColumnSchema are followed.
* - A type must always be set
* - If the column type is {@code SEALED} then there must be a pad specified
* - Pad must not be set for other column types
*
* @throws C3rIllegalArgumentException If any rules are violated
*/
public void validate() {
// A type is always required
if (type == null) {
throw new C3rIllegalArgumentException("Columns must be provided a type, but column " + sourceHeader + " has none.");
}
// Padding must be specified on encrypted columns
if (pad == null && type == ColumnType.SEALED) {
throw new C3rIllegalArgumentException("Padding must be provided for sealed columns, but column " + sourceHeader + " has none.");
}
// Padding may only be used on encrypted columns
if (pad != null && type != ColumnType.SEALED) {
throw new C3rIllegalArgumentException("Padding is only available for sealed columns, but pad type " + pad.getType().name()
+ " was sealed for column " + sourceHeader + " of type " + type + ".");
}
}
/**
* Determines if there's a need to run through the source file in order to ensure configuration constraints.
*
* <p>
* A column with a {@link PadType} other than NONE would require knowing the largest data in the given column to ensure
* padding can be done successfully and to the correct size.
*
* <p>
* A column that is <b>not</b> of {@link ColumnType#CLEARTEXT} will require preprocessing in order to randomize
* the order of output rows.
*
* @return {@code true} if there are any settings that require preprocessing
*/
public boolean requiresPreprocessing() {
boolean requiresPreprocessing = pad != null && pad.requiresPreprocessing();
requiresPreprocessing |= type != ColumnType.CLEARTEXT;
return requiresPreprocessing;
}
}
| 2,596 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/config/ColumnInsight.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.data.ClientDataType;
import com.amazonaws.c3r.data.Value;
import com.amazonaws.c3r.data.ValueConverter;
import com.amazonaws.c3r.exception.C3rRuntimeException;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
/**
* A ColumnSchema with additional state to accumulate insights about a
* column's origin and content properties during pre-processing.
*/
@EqualsAndHashCode(callSuper = true)
public class ColumnInsight extends ColumnSchema {
/**
* Accumulator for maximum value length seen <i>if</i> {@code padType == PadType.MAX},
* otherwise the field is set to {@code 0} and ignored.
*/
@Getter
@Setter
private int maxValueLength;
/**
* Index of the column in the input source. A negative number indicates the column was not found.
*/
@Getter
@Setter
private int sourceColumnPosition = -1;
/**
* Tracks whether a {@code null} value has been seen in the data processed so far.
*/
private boolean seenNull = false;
/**
* Tracks the type seen in the column so far to make sure a column doesn't contain multiple types.
*/
@Getter
private ClientDataType clientDataType = null;
/**
* Create metadata wrapper around a {@link ColumnSchema}.
*
* @param columnSchema Column to wrap with metadata
*/
public ColumnInsight(final ColumnSchema columnSchema) {
super(columnSchema);
}
/**
* Updates the insight info for this column with the observed value (e.g.,
* maximum value length thus far for this column <i>if</i>
* {@code padType == PadType.MAX}, etc).
*
* @param value Seen value
* @throws C3rRuntimeException if more than two client data types are found in a single column
*/
public void observe(@NonNull final Value value) {
if (value.isNull()) {
seenNull = true;
return;
}
final var length = value.byteLength();
if (getPad() != null && getPad().getType() == PadType.MAX && maxValueLength < length) {
maxValueLength = length;
}
if (clientDataType == null) {
clientDataType = ValueConverter.getClientDataTypeForColumn(value, getType());
} else if (clientDataType != value.getClientDataType()) {
throw new C3rRuntimeException("Multiple client data types found in a single column: " + clientDataType + " and " +
value.getClientDataType() + ".");
}
}
/**
* If this column observed a value for which `isNull() == true`.
*
* @return False if a null value has not been encountered yet, else true
*/
public boolean hasSeenNull() {
return seenNull;
}
}
| 2,597 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/config/ClientSettings.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import lombok.Builder;
import lombok.Value;
import java.io.Serializable;
/**
* Contains clean room wide settings.
*/
@Value
@Builder
public class ClientSettings implements Serializable {
/**
* Whether cleartext columns are allowed.
*/
private boolean allowCleartext;
/**
* Whether duplicate values are allowed in a fingerprint column.
*
* @see ColumnType#FINGERPRINT
*/
private boolean allowDuplicates;
/**
* Whether fingerprint column names need to match on queries.
*
* @see ColumnType#FINGERPRINT
*/
private boolean allowJoinsOnColumnsWithDifferentNames;
/**
* Whether {@code null} values should be encrypted or left as {@code null}.
*/
private boolean preserveNulls;
/**
* Most permissive settings.
*
* @return ClientSettings with all flags set to `true`
*/
public static ClientSettings lowAssuranceMode() {
return ClientSettings.builder()
.allowCleartext(true)
.allowDuplicates(true)
.allowJoinsOnColumnsWithDifferentNames(true)
.preserveNulls(true)
.build();
}
/**
* Least permissive settings.
*
* @return ClientSettings with all flags set to `false`
*/
public static ClientSettings highAssuranceMode() {
return ClientSettings.builder()
.allowCleartext(false)
.allowDuplicates(false)
.allowJoinsOnColumnsWithDifferentNames(false)
.preserveNulls(false)
.build();
}
} | 2,598 |
0 | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r | Create_ds/c3r/c3r-sdk-core/src/main/java/com/amazonaws/c3r/config/SimpleFileConfig.java | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
package com.amazonaws.c3r.config;
import com.amazonaws.c3r.exception.C3rIllegalArgumentException;
import com.amazonaws.c3r.io.FileFormat;
import com.amazonaws.c3r.utils.FileUtil;
import lombok.NonNull;
import javax.crypto.SecretKey;
/**
* Basic information needed whether encrypting or decrypting data for basic file types.
*/
public abstract class SimpleFileConfig extends Config {
/**
* Basic configuration information needed for encrypting or decrypting data.
*
* @param secretKey Clean room key used to generate sub-keys for HMAC and encryption
* @param sourceFile Location of input data
* @param fileFormat Format of input data
* @param targetFile Where output should be saved
* @param overwrite Whether to overwrite the target file if it exists already
* @param csvInputNullValue What value should be interpreted as {@code null} for CSV files
* @param csvOutputNullValue What value should be saved in output to represent {@code null} values for CSV
* @param salt Salt that can be publicly known but adds to randomness of cryptographic operations
*/
protected SimpleFileConfig(@NonNull final SecretKey secretKey, @NonNull final String sourceFile, final FileFormat fileFormat,
final String targetFile, final boolean overwrite, final String csvInputNullValue,
final String csvOutputNullValue, @NonNull final String salt) {
super(secretKey, sourceFile, fileFormat, targetFile, overwrite, csvInputNullValue, csvOutputNullValue, salt);
validate();
}
/**
* Verifies that settings are consistent.
* - Make sure the program can read from the source file
* - Make sure the program can write to the target file
* - Make sure the data format is known
*
* @throws C3rIllegalArgumentException If any of the rules are violated
*/
private void validate() {
FileUtil.verifyReadableFile(getSourceFile());
FileUtil.verifyWritableFile(getTargetFile(), isOverwrite());
if (getFileFormat() == null) {
throw new C3rIllegalArgumentException("Unknown file extension: please specify the file format for file "
+ getSourceFile() + ".");
}
if (getFileFormat() != FileFormat.CSV) {
if (getCsvInputNullValue() != null || getCsvOutputNullValue() != null) {
throw new C3rIllegalArgumentException("CSV options specified for " + getFileFormat() + " file.");
}
}
}
}
| 2,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.