Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
package io.opentelemetry.exporter.internal;

import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.joining;

import java.io.ByteArrayInputStream;
import java.io.IOException;
Expand Down Expand Up @@ -48,6 +49,21 @@ public final class TlsUtil {

private static final String PEM_KEY_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PEM_KEY_FOOTER = "-----END PRIVATE KEY-----";
private static final List<KeyFactory> SUPPORTED_KEY_FACTORIES;

static {
SUPPORTED_KEY_FACTORIES = new ArrayList<>();
try {
SUPPORTED_KEY_FACTORIES.add(KeyFactory.getInstance("RSA"));
} catch (NoSuchAlgorithmException e) {
// Ignore and continue
}
try {
SUPPORTED_KEY_FACTORIES.add(KeyFactory.getInstance("EC"));
} catch (NoSuchAlgorithmException e) {
// Ignore and continue
}
}

private TlsUtil() {}

Expand Down Expand Up @@ -83,9 +99,8 @@ public static X509KeyManager keyManager(byte[] privateKeyPem, byte[] certificate
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null);
KeyFactory factory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodePem(privateKeyPem));
PrivateKey key = factory.generatePrivate(keySpec);
PrivateKey key = generatePrivateKey(keySpec, SUPPORTED_KEY_FACTORIES);
Comment thread
jack-berg marked this conversation as resolved.

CertificateFactory cf = CertificateFactory.getInstance("X.509");

Expand All @@ -106,12 +121,27 @@ public static X509KeyManager keyManager(byte[] privateKeyPem, byte[] certificate
| KeyStoreException
| IOException
| NoSuchAlgorithmException
| UnrecoverableKeyException
| InvalidKeySpecException e) {
| UnrecoverableKeyException e) {
throw new SSLException("Could not build KeyManagerFactory from clientKeysPem.", e);
}
}

// Visible for testing
static PrivateKey generatePrivateKey(PKCS8EncodedKeySpec keySpec, List<KeyFactory> keyFactories)
throws SSLException {
// Try to generate key using supported key factories
for (KeyFactory factory : keyFactories) {
try {
return factory.generatePrivate(keySpec);
} catch (InvalidKeySpecException e) {
// Ignore
}
}
throw new SSLException(
"Unable to generate key from supported algorithms: "
+ keyFactories.stream().map(KeyFactory::getAlgorithm).collect(joining(",", "[", "]")));
}

/** Returns a {@link TrustManager} for the given trusted certificates. */
public static X509TrustManager trustManager(byte[] trustedCertificatesPem) throws SSLException {
requireNonNull(trustedCertificatesPem, "trustedCertificatesPem");
Expand Down Expand Up @@ -140,7 +170,8 @@ public static X509TrustManager trustManager(byte[] trustedCertificatesPem) throw
// We catch linkage error to provide a better exception message on Android.
// https://github.com/open-telemetry/opentelemetry-java/issues/4533
@IgnoreJRERequirement
private static byte[] decodePem(byte[] pem) {
// Visible for testing
static byte[] decodePem(byte[] pem) {
String pemStr = new String(pem, StandardCharsets.UTF_8).trim();
if (!pemStr.startsWith(PEM_KEY_HEADER) || !pemStr.endsWith(PEM_KEY_FOOTER)) {
// pem may already be a decoded binary key, try to use it.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.exporter.internal;

import static org.assertj.core.api.Assertions.assertThatCode;

import com.linecorp.armeria.internal.common.util.SelfSignedCertificate;
import java.security.KeyFactory;
import java.security.cert.CertificateException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.time.Instant;
import java.util.Collections;
import java.util.Date;
import javax.net.ssl.SSLException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class TlsUtilTest {

private SelfSignedCertificate rsaCertificate;
private SelfSignedCertificate ecCertificate;

@BeforeEach
void setup() throws CertificateException {
rsaCertificate =
new SelfSignedCertificate(Date.from(Instant.now()), Date.from(Instant.now()), "RSA", 2048);
ecCertificate =
new SelfSignedCertificate(Date.from(Instant.now()), Date.from(Instant.now()), "EC", 256);
}

@Test
void keyManager_Rsa() {
assertThatCode(
() ->
TlsUtil.keyManager(
rsaCertificate.key().getEncoded(), rsaCertificate.cert().getEncoded()))
.doesNotThrowAnyException();
}

@Test
void keyManager_Ec() {
assertThatCode(
() ->
TlsUtil.keyManager(
ecCertificate.key().getEncoded(), ecCertificate.cert().getEncoded()))
.doesNotThrowAnyException();
}

@Test
void generatePrivateKey_Invalid() {
PKCS8EncodedKeySpec keySpec =
new PKCS8EncodedKeySpec(TlsUtil.decodePem(rsaCertificate.key().getEncoded()));
assertThatCode(
() ->
TlsUtil.generatePrivateKey(
keySpec, Collections.singletonList(KeyFactory.getInstance("EC"))))
.isInstanceOf(SSLException.class)
.hasMessage("Unable to generate key from supported algorithms: [EC]");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@
import static org.testcontainers.Testcontainers.exposeHostPorts;

import com.google.protobuf.InvalidProtocolBufferException;
import com.linecorp.armeria.internal.common.util.SelfSignedCertificate;
import com.linecorp.armeria.server.ServerBuilder;
import com.linecorp.armeria.server.ServiceRequestContext;
import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService;
import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension;
import com.linecorp.armeria.testing.junit5.server.ServerExtension;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.Attributes;
Expand Down Expand Up @@ -68,18 +68,19 @@
import io.opentelemetry.sdk.trace.export.SpanExporter;
import io.opentelemetry.semconv.resource.attributes.ResourceAttributes;
import java.io.UncheckedIOException;
import java.security.cert.CertificateException;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletionStage;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.slf4j.LoggerFactory;
Expand Down Expand Up @@ -113,17 +114,22 @@ abstract class OtlpExporterIntegrationTest {
.put(ResourceAttributes.SERVICE_NAME, "integration test")
.build();

@RegisterExtension
static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension();

@RegisterExtension
static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension();
static SelfSignedCertificate serverTls;
static SelfSignedCertificate clientTls;

private static OtlpGrpcServer grpcServer;
private static GenericContainer<?> collector;

@BeforeAll
static void beforeAll() {
static void beforeAll() throws CertificateException {
serverTls = new SelfSignedCertificate();
clientTls =
new SelfSignedCertificate(
Date.from(Instant.now().minusSeconds(365 * 24 * 3600)),
Date.from(Instant.ofEpochMilli(253402300799000L)),
"EC",
256);
Comment thread
jack-berg marked this conversation as resolved.
Outdated

grpcServer = new OtlpGrpcServer();
grpcServer.start();

Expand All @@ -136,13 +142,11 @@ static void beforeAll() {
.withImagePullPolicy(PullPolicy.alwaysPull())
.withEnv("LOGGING_EXPORTER_LOG_LEVEL", "INFO")
.withCopyFileToContainer(
MountableFile.forHostPath(serverTls.certificateFile().toPath(), 0555),
"/server.cert")
MountableFile.forHostPath(serverTls.certificate().toPath(), 0555), "/server.cert")
.withCopyFileToContainer(
MountableFile.forHostPath(serverTls.privateKeyFile().toPath(), 0555), "/server.key")
MountableFile.forHostPath(serverTls.privateKey().toPath(), 0555), "/server.key")
.withCopyFileToContainer(
MountableFile.forHostPath(clientTls.certificateFile().toPath(), 0555),
"/client.cert")
MountableFile.forHostPath(clientTls.certificate().toPath(), 0555), "/client.cert")
.withEnv(
"OTLP_EXPORTER_ENDPOINT", "host.testcontainers.internal:" + grpcServer.httpPort())
.withEnv("MTLS_CLIENT_CERTIFICATE", "/client.cert")
Expand Down Expand Up @@ -202,8 +206,8 @@ void testOtlpGrpcTraceExport_mtls() throws Exception {
+ collector.getHost()
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_GRPC_MTLS_PORT))
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testTraceExport(exporter);
Expand Down Expand Up @@ -236,8 +240,8 @@ void testOtlpHttpTraceExport_mtls() throws Exception {
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_HTTP_MTLS_PORT)
+ "/v1/traces")
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testTraceExport(exporter);
Expand Down Expand Up @@ -335,8 +339,8 @@ void testOtlpGrpcMetricExport_mtls() throws Exception {
+ collector.getHost()
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_GRPC_MTLS_PORT))
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testMetricExport(exporter);
Expand Down Expand Up @@ -369,8 +373,8 @@ void testOtlpHttpMetricExport_mtls() throws Exception {
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_HTTP_MTLS_PORT)
+ "/v1/metrics")
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testMetricExport(exporter);
Expand Down Expand Up @@ -460,8 +464,8 @@ void testOtlpGrpcLogExport_mtls() throws Exception {
+ collector.getHost()
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_GRPC_MTLS_PORT))
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testLogRecordExporter(exporter);
Expand Down Expand Up @@ -494,8 +498,8 @@ void testOtlpHttpLogExport_mtls() throws Exception {
+ ":"
+ collector.getMappedPort(COLLECTOR_OTLP_HTTP_MTLS_PORT)
+ "/v1/logs")
.setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded())
.setTrustedCertificates(serverTls.certificate().getEncoded())
.setClientTls(clientTls.key().getEncoded(), clientTls.cert().getEncoded())
.setTrustedCertificates(serverTls.cert().getEncoded())
.build();

testLogRecordExporter(exporter);
Expand Down