|
| 1 | +/* |
| 2 | + * Copyright The OpenTelemetry Authors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package io.opentelemetry.contrib.gcp.auth; |
| 7 | + |
| 8 | +import static io.opentelemetry.contrib.gcp.auth.GcpAuthAutoConfigurationCustomizerProvider.GCP_USER_PROJECT_ID_KEY; |
| 9 | +import static io.opentelemetry.contrib.gcp.auth.GcpAuthAutoConfigurationCustomizerProvider.QUOTA_USER_PROJECT_HEADER; |
| 10 | +import static org.awaitility.Awaitility.await; |
| 11 | +import static org.junit.jupiter.api.Assertions.assertFalse; |
| 12 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 13 | +import static org.mockserver.model.HttpRequest.request; |
| 14 | +import static org.mockserver.model.HttpResponse.response; |
| 15 | +import static org.mockserver.stop.Stop.stopQuietly; |
| 16 | + |
| 17 | +import com.google.protobuf.InvalidProtocolBufferException; |
| 18 | +import io.opentelemetry.contrib.gcp.auth.springapp.Application; |
| 19 | +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; |
| 20 | +import io.opentelemetry.proto.common.v1.AnyValue; |
| 21 | +import io.opentelemetry.proto.common.v1.KeyValue; |
| 22 | +import io.opentelemetry.proto.trace.v1.ResourceSpans; |
| 23 | +import java.net.URI; |
| 24 | +import java.security.KeyManagementException; |
| 25 | +import java.security.NoSuchAlgorithmException; |
| 26 | +import java.security.cert.X509Certificate; |
| 27 | +import java.time.Duration; |
| 28 | +import java.util.Arrays; |
| 29 | +import java.util.List; |
| 30 | +import java.util.Optional; |
| 31 | +import java.util.stream.Collectors; |
| 32 | +import javax.net.ssl.HttpsURLConnection; |
| 33 | +import javax.net.ssl.SSLContext; |
| 34 | +import javax.net.ssl.TrustManager; |
| 35 | +import javax.net.ssl.X509TrustManager; |
| 36 | +import org.junit.jupiter.api.AfterAll; |
| 37 | +import org.junit.jupiter.api.BeforeAll; |
| 38 | +import org.junit.jupiter.api.Test; |
| 39 | +import org.mockserver.client.MockServerClient; |
| 40 | +import org.mockserver.integration.ClientAndServer; |
| 41 | +import org.mockserver.model.Body; |
| 42 | +import org.mockserver.model.Headers; |
| 43 | +import org.mockserver.model.HttpRequest; |
| 44 | +import org.mockserver.model.JsonBody; |
| 45 | +import org.springframework.beans.factory.annotation.Autowired; |
| 46 | +import org.springframework.boot.test.context.SpringBootTest; |
| 47 | +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; |
| 48 | +import org.springframework.boot.test.web.client.TestRestTemplate; |
| 49 | +import org.springframework.boot.test.web.server.LocalServerPort; |
| 50 | + |
| 51 | +@SpringBootTest( |
| 52 | + classes = {Application.class}, |
| 53 | + webEnvironment = WebEnvironment.RANDOM_PORT) |
| 54 | +public class GcpAuthExtensionEndToEndTest { |
| 55 | + |
| 56 | + @LocalServerPort private int testApplicationPort; // port at which the spring app is running |
| 57 | + |
| 58 | + @Autowired private TestRestTemplate template; |
| 59 | + |
| 60 | + // The port at which the backend server will receive telemetry |
| 61 | + private static final int EXPORTER_ENDPOINT_PORT = 4318; |
| 62 | + // The port at which the mock GCP OAuth 2.0 server will run |
| 63 | + private static final int MOCK_GCP_OAUTH2_PORT = 8090; |
| 64 | + |
| 65 | + // Backend server to which the application under test will export traces |
| 66 | + // the export config is specified in the build.gradle file. |
| 67 | + private static ClientAndServer backendServer; |
| 68 | + |
| 69 | + // Mock server to intercept calls to the GCP OAuth 2.0 server and provide fake credentials |
| 70 | + private static ClientAndServer mockGcpOAuth2Server; |
| 71 | + |
| 72 | + private static final String DUMMY_GCP_QUOTA_PROJECT = System.getenv("GOOGLE_CLOUD_QUOTA_PROJECT"); |
| 73 | + private static final String DUMMY_GCP_PROJECT = System.getProperty("google.cloud.project"); |
| 74 | + |
| 75 | + @BeforeAll |
| 76 | + public static void setup() throws NoSuchAlgorithmException, KeyManagementException { |
| 77 | + // Setup proxy host(s) |
| 78 | + System.setProperty("http.proxyHost", "localhost"); |
| 79 | + System.setProperty("http.proxyPort", MOCK_GCP_OAUTH2_PORT + ""); |
| 80 | + System.setProperty("https.proxyHost", "localhost"); |
| 81 | + System.setProperty("https.proxyPort", MOCK_GCP_OAUTH2_PORT + ""); |
| 82 | + System.setProperty("http.nonProxyHost", "localhost"); |
| 83 | + System.setProperty("https.nonProxyHost", "localhost"); |
| 84 | + |
| 85 | + // Disable SSL validation for integration test |
| 86 | + // The OAuth2 token validation requires SSL validation |
| 87 | + disableSSLValidation(); |
| 88 | + |
| 89 | + // Set up mock OTLP backend server to which traces will be exported |
| 90 | + backendServer = ClientAndServer.startClientAndServer(EXPORTER_ENDPOINT_PORT); |
| 91 | + backendServer.when(request()).respond(response().withStatusCode(200)); |
| 92 | + |
| 93 | + // Set up the mock gcp metadata server to provide fake credentials |
| 94 | + String accessTokenResponse = |
| 95 | + "{\"access_token\": \"fake.access_token\",\"expires_in\": 3600, \"token_type\": \"Bearer\"}"; |
| 96 | + mockGcpOAuth2Server = ClientAndServer.startClientAndServer(MOCK_GCP_OAUTH2_PORT); |
| 97 | + |
| 98 | + MockServerClient mockServerClient = |
| 99 | + new MockServerClient("localhost", MOCK_GCP_OAUTH2_PORT).withSecure(true); |
| 100 | + |
| 101 | + // mock the token refresh - always respond with 200 |
| 102 | + mockServerClient |
| 103 | + .when(request().withMethod("POST").withPath("/token")) |
| 104 | + .respond( |
| 105 | + response() |
| 106 | + .withStatusCode(200) |
| 107 | + .withHeader("Content-Type", "application/json") |
| 108 | + .withBody(new JsonBody(accessTokenResponse))); |
| 109 | + } |
| 110 | + |
| 111 | + @AfterAll |
| 112 | + public static void teardown() { |
| 113 | + // Stop the backend server |
| 114 | + stopQuietly(backendServer); |
| 115 | + stopQuietly(mockGcpOAuth2Server); |
| 116 | + } |
| 117 | + |
| 118 | + @Test |
| 119 | + public void authExtensionSmokeTest() { |
| 120 | + template.getForEntity( |
| 121 | + URI.create("http://localhost:" + testApplicationPort + "/ping"), String.class); |
| 122 | + |
| 123 | + await() |
| 124 | + .atMost(Duration.ofSeconds(10)) |
| 125 | + .untilAsserted( |
| 126 | + () -> { |
| 127 | + HttpRequest[] requests = backendServer.retrieveRecordedRequests(request()); |
| 128 | + List<Headers> extractedHeaders = extractHeadersFromRequests(requests); |
| 129 | + verifyRequestHeaders(extractedHeaders); |
| 130 | + |
| 131 | + List<ResourceSpans> extractedResourceSpans = |
| 132 | + extractResourceSpansFromRequests(requests); |
| 133 | + verifyResourceAttributes(extractedResourceSpans); |
| 134 | + }); |
| 135 | + } |
| 136 | + |
| 137 | + // Helper methods |
| 138 | + |
| 139 | + private static void disableSSLValidation() |
| 140 | + throws NoSuchAlgorithmException, KeyManagementException { |
| 141 | + TrustManager[] trustAllCerts = |
| 142 | + new TrustManager[] { |
| 143 | + new X509TrustManager() { |
| 144 | + @Override |
| 145 | + public void checkClientTrusted(X509Certificate[] chain, String authType) {} |
| 146 | + |
| 147 | + @Override |
| 148 | + public void checkServerTrusted(X509Certificate[] chain, String authType) {} |
| 149 | + |
| 150 | + @Override |
| 151 | + public X509Certificate[] getAcceptedIssuers() { |
| 152 | + return null; |
| 153 | + } |
| 154 | + } |
| 155 | + }; |
| 156 | + SSLContext sc = SSLContext.getInstance("SSL"); |
| 157 | + sc.init(null, trustAllCerts, new java.security.SecureRandom()); |
| 158 | + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); |
| 159 | + } |
| 160 | + |
| 161 | + private static void verifyResourceAttributes(List<ResourceSpans> extractedResourceSpans) { |
| 162 | + extractedResourceSpans.forEach( |
| 163 | + resourceSpan -> |
| 164 | + assertTrue( |
| 165 | + resourceSpan |
| 166 | + .getResource() |
| 167 | + .getAttributesList() |
| 168 | + .contains( |
| 169 | + KeyValue.newBuilder() |
| 170 | + .setKey(GCP_USER_PROJECT_ID_KEY) |
| 171 | + .setValue(AnyValue.newBuilder().setStringValue(DUMMY_GCP_PROJECT)) |
| 172 | + .build()))); |
| 173 | + } |
| 174 | + |
| 175 | + private static void verifyRequestHeaders(List<Headers> extractedHeaders) { |
| 176 | + assertFalse(extractedHeaders.isEmpty()); |
| 177 | + // verify if extension added the required headers |
| 178 | + extractedHeaders.forEach( |
| 179 | + headers -> { |
| 180 | + assertTrue(headers.containsEntry(QUOTA_USER_PROJECT_HEADER, DUMMY_GCP_QUOTA_PROJECT)); |
| 181 | + assertTrue(headers.containsEntry("Authorization", "Bearer fake.access_token")); |
| 182 | + }); |
| 183 | + } |
| 184 | + |
| 185 | + private static List<Headers> extractHeadersFromRequests(HttpRequest[] requests) { |
| 186 | + return Arrays.stream(requests).map(HttpRequest::getHeaders).collect(Collectors.toList()); |
| 187 | + } |
| 188 | + |
| 189 | + /** |
| 190 | + * Extract resource spans from http requests received by a telemetry collector. |
| 191 | + * |
| 192 | + * @param requests Request received by a http server trace collector |
| 193 | + * @return spans extracted from the request body |
| 194 | + */ |
| 195 | + private static List<ResourceSpans> extractResourceSpansFromRequests(HttpRequest[] requests) { |
| 196 | + return Arrays.stream(requests) |
| 197 | + .map(HttpRequest::getBody) |
| 198 | + .map(GcpAuthExtensionEndToEndTest::getExportTraceServiceRequest) |
| 199 | + .filter(Optional::isPresent) |
| 200 | + .map(Optional::get) |
| 201 | + .flatMap( |
| 202 | + exportTraceServiceRequest -> exportTraceServiceRequest.getResourceSpansList().stream()) |
| 203 | + .collect(Collectors.toList()); |
| 204 | + } |
| 205 | + |
| 206 | + private static Optional<ExportTraceServiceRequest> getExportTraceServiceRequest(Body<?> body) { |
| 207 | + try { |
| 208 | + return Optional.ofNullable(ExportTraceServiceRequest.parseFrom(body.getRawBytes())); |
| 209 | + } catch (InvalidProtocolBufferException e) { |
| 210 | + return Optional.empty(); |
| 211 | + } |
| 212 | + } |
| 213 | +} |
0 commit comments