|
| 1 | +/* |
| 2 | + * Copyright (c) 2021 Airbyte, Inc., all rights reserved. |
| 3 | + */ |
| 4 | + |
| 5 | +package io.airbyte.oauth.flows; |
| 6 | + |
| 7 | +import static org.junit.jupiter.api.Assertions.assertTrue; |
| 8 | +import static org.mockito.Mockito.mock; |
| 9 | +import static org.mockito.Mockito.when; |
| 10 | + |
| 11 | +import com.fasterxml.jackson.databind.JsonNode; |
| 12 | +import com.google.common.collect.ImmutableMap; |
| 13 | +import com.sun.net.httpserver.HttpExchange; |
| 14 | +import com.sun.net.httpserver.HttpHandler; |
| 15 | +import com.sun.net.httpserver.HttpServer; |
| 16 | +import io.airbyte.commons.json.Jsons; |
| 17 | +import io.airbyte.config.SourceOAuthParameter; |
| 18 | +import io.airbyte.config.persistence.ConfigNotFoundException; |
| 19 | +import io.airbyte.config.persistence.ConfigRepository; |
| 20 | +import io.airbyte.validation.json.JsonValidationException; |
| 21 | +import java.io.IOException; |
| 22 | +import java.io.OutputStream; |
| 23 | +import java.net.InetSocketAddress; |
| 24 | +import java.nio.file.Files; |
| 25 | +import java.nio.file.Path; |
| 26 | +import java.util.HashMap; |
| 27 | +import java.util.List; |
| 28 | +import java.util.Map; |
| 29 | +import java.util.UUID; |
| 30 | +import org.junit.jupiter.api.AfterEach; |
| 31 | +import org.junit.jupiter.api.BeforeEach; |
| 32 | +import org.junit.jupiter.api.Test; |
| 33 | +import org.slf4j.Logger; |
| 34 | +import org.slf4j.LoggerFactory; |
| 35 | + |
| 36 | +public class SalesforceOAuthFlowIntegrationTest { |
| 37 | + |
| 38 | + private static final Logger LOGGER = LoggerFactory.getLogger(SalesforceOAuthFlowIntegrationTest.class); |
| 39 | + private static final String REDIRECT_URL = "http://localhost:8000/code"; |
| 40 | + private static final Path CREDENTIALS_PATH = Path.of("secrets/salesforce.json"); |
| 41 | + |
| 42 | + private ConfigRepository configRepository; |
| 43 | + private SalesforceOAuthFlow salesforceOAuthFlow; |
| 44 | + private HttpServer server; |
| 45 | + private ServerHandler serverHandler; |
| 46 | + |
| 47 | + @BeforeEach |
| 48 | + public void setup() throws IOException { |
| 49 | + if (!Files.exists(CREDENTIALS_PATH)) { |
| 50 | + throw new IllegalStateException( |
| 51 | + "Must provide path to a oauth credentials file."); |
| 52 | + } |
| 53 | + configRepository = mock(ConfigRepository.class); |
| 54 | + salesforceOAuthFlow = new SalesforceOAuthFlow(configRepository); |
| 55 | + |
| 56 | + server = HttpServer.create(new InetSocketAddress(8000), 0); |
| 57 | + server.setExecutor(null); // creates a default executor |
| 58 | + server.start(); |
| 59 | + serverHandler = new ServerHandler("code"); |
| 60 | + server.createContext("/code", serverHandler); |
| 61 | + } |
| 62 | + |
| 63 | + @AfterEach |
| 64 | + void tearDown() { |
| 65 | + server.stop(1); |
| 66 | + } |
| 67 | + |
| 68 | + @Test |
| 69 | + public void testFullSalesforceOAuthFlow() throws InterruptedException, ConfigNotFoundException, IOException, JsonValidationException { |
| 70 | + int limit = 20; |
| 71 | + final UUID workspaceId = UUID.randomUUID(); |
| 72 | + final UUID definitionId = UUID.randomUUID(); |
| 73 | + final String fullConfigAsString = new String(Files.readAllBytes(CREDENTIALS_PATH)); |
| 74 | + final JsonNode credentialsJson = Jsons.deserialize(fullConfigAsString); |
| 75 | + final String clientId = credentialsJson.get("client_id").asText(); |
| 76 | + when(configRepository.listSourceOAuthParam()).thenReturn(List.of(new SourceOAuthParameter() |
| 77 | + .withOauthParameterId(UUID.randomUUID()) |
| 78 | + .withSourceDefinitionId(definitionId) |
| 79 | + .withWorkspaceId(workspaceId) |
| 80 | + .withConfiguration(Jsons.jsonNode(ImmutableMap.builder() |
| 81 | + .put("client_id", clientId) |
| 82 | + .put("client_secret", credentialsJson.get("client_secret").asText()) |
| 83 | + .build())))); |
| 84 | + final String url = salesforceOAuthFlow.getSourceConsentUrl(workspaceId, definitionId, REDIRECT_URL); |
| 85 | + LOGGER.info("Waiting for user consent at: {}", url); |
| 86 | + // TODO: To automate, start a selenium job to navigate to the Consent URL and click on allowing |
| 87 | + // access... |
| 88 | + while (!serverHandler.isSucceeded() && limit > 0) { |
| 89 | + Thread.sleep(1000); |
| 90 | + limit -= 1; |
| 91 | + } |
| 92 | + assertTrue(serverHandler.isSucceeded(), "Failed to get User consent on time"); |
| 93 | + final Map<String, Object> params = salesforceOAuthFlow.completeSourceOAuth(workspaceId, definitionId, |
| 94 | + Map.of("code", serverHandler.getParamValue()), REDIRECT_URL); |
| 95 | + LOGGER.info("Response from completing OAuth Flow is: {}", params.toString()); |
| 96 | + assertTrue(params.containsKey("refresh_token")); |
| 97 | + assertTrue(params.get("refresh_token").toString().length() > 0); |
| 98 | + } |
| 99 | + |
| 100 | + static class ServerHandler implements HttpHandler { |
| 101 | + |
| 102 | + final private String expectedParam; |
| 103 | + private Map responseQuery; |
| 104 | + private String paramValue; |
| 105 | + private boolean succeeded; |
| 106 | + |
| 107 | + public ServerHandler(String expectedParam) { |
| 108 | + this.expectedParam = expectedParam; |
| 109 | + this.paramValue = ""; |
| 110 | + this.succeeded = false; |
| 111 | + } |
| 112 | + |
| 113 | + public boolean isSucceeded() { |
| 114 | + return succeeded; |
| 115 | + } |
| 116 | + |
| 117 | + public String getParamValue() { |
| 118 | + return paramValue; |
| 119 | + } |
| 120 | + |
| 121 | + public Map getResponseQuery() { |
| 122 | + return responseQuery; |
| 123 | + } |
| 124 | + |
| 125 | + @Override |
| 126 | + public void handle(HttpExchange t) { |
| 127 | + final String query = t.getRequestURI().getQuery(); |
| 128 | + LOGGER.info("Received query: '{}'", query); |
| 129 | + final Map<String, String> data; |
| 130 | + try { |
| 131 | + data = deserialize(query); |
| 132 | + final String response; |
| 133 | + if (data != null && data.containsKey(expectedParam)) { |
| 134 | + paramValue = data.get(expectedParam); |
| 135 | + response = String.format("Successfully extracted %s:\n'%s'\nTest should be continuing the OAuth Flow to retrieve the refresh_token...", |
| 136 | + expectedParam, paramValue); |
| 137 | + responseQuery = data; |
| 138 | + LOGGER.info(response); |
| 139 | + t.sendResponseHeaders(200, response.length()); |
| 140 | + succeeded = true; |
| 141 | + } else { |
| 142 | + response = String.format("Unable to parse query params from redirected url: %s", query); |
| 143 | + t.sendResponseHeaders(500, response.length()); |
| 144 | + } |
| 145 | + final OutputStream os = t.getResponseBody(); |
| 146 | + os.write(response.getBytes()); |
| 147 | + os.close(); |
| 148 | + } catch (RuntimeException | IOException e) { |
| 149 | + LOGGER.error("Failed to parse from body {}", query, e); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + private static Map<String, String> deserialize(String query) { |
| 154 | + if (query == null) { |
| 155 | + return null; |
| 156 | + } |
| 157 | + final Map<String, String> result = new HashMap<>(); |
| 158 | + for (String param : query.split("&")) { |
| 159 | + String[] entry = param.split("=", 2); |
| 160 | + if (entry.length > 1) { |
| 161 | + result.put(entry[0], entry[1]); |
| 162 | + } else { |
| 163 | + result.put(entry[0], ""); |
| 164 | + } |
| 165 | + } |
| 166 | + return result; |
| 167 | + } |
| 168 | + |
| 169 | + } |
| 170 | + |
| 171 | +} |
0 commit comments