Search in sources :

Example 31 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project jade-data-repo by DataBiosphere.

the class TestRunner method executeTestConfiguration.

void executeTestConfiguration() throws Exception {
    // specify any value overrides in the Helm chart, then deploy
    if (!config.server.skipDeployment) {
    // modifyHelmValuesAndDeploy();
    }
    // update any Kubernetes properties specified by the test configuration
    if (!config.server.skipKubernetes) {
        KubernetesClientUtils.buildKubernetesClientObject(config.server);
        modifyKubernetesPostDeployment();
    }
    // get an instance of the API client per test user
    for (TestUserSpecification testUser : config.testUsers) {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath(config.server.uri);
        GoogleCredentials userCredential = AuthenticationUtils.getDelegatedUserCredential(testUser);
        AccessToken userAccessToken = AuthenticationUtils.getAccessToken(userCredential);
        apiClient.setAccessToken(userAccessToken.getTokenValue());
        apiClientsForUsers.put(testUser.name, apiClient);
    }
    // get an instance of each test script class
    for (TestScriptSpecification testScriptSpecification : config.testScripts) {
        try {
            TestScript testScriptInstance = testScriptSpecification.scriptClass.newInstance();
            // set the billing account for the test script to use
            testScriptInstance.setBillingAccount(config.billingAccount);
            // set any parameters specified by the configuration
            testScriptInstance.setParameters(testScriptSpecification.parameters);
            scripts.add(testScriptInstance);
        } catch (IllegalAccessException | InstantiationException niEx) {
            throw new IllegalArgumentException("Error calling constructor of TestScript class: " + testScriptSpecification.scriptClass.getName(), niEx);
        }
    }
    // call the setup method of each test script
    Exception setupExceptionThrown = callTestScriptSetups();
    if (setupExceptionThrown != null) {
        // ignore any exceptions thrown by cleanup methods
        callTestScriptCleanups();
        throw new RuntimeException("Error calling test script setup methods.", setupExceptionThrown);
    }
    // for each test script
    List<ApiClient> apiClientList = new ArrayList<>(apiClientsForUsers.values());
    for (int tsCtr = 0; tsCtr < scripts.size(); tsCtr++) {
        TestScript testScript = scripts.get(tsCtr);
        TestScriptSpecification testScriptSpecification = config.testScripts.get(tsCtr);
        // add a description to the user journey threads/results that includes any parameters
        String userJourneyDescription = testScriptSpecification.name;
        if (testScriptSpecification.parameters != null) {
            userJourneyDescription += ": " + String.join(",", testScriptSpecification.parameters);
        }
        // create a thread pool for running its user journeys
        ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(testScriptSpecification.numberToRunInParallel);
        threadPools.add(threadPool);
        // kick off the user journey(s), one per thread
        List<UserJourneyThread> userJourneyThreads = new ArrayList<>();
        for (int ujCtr = 0; ujCtr < testScriptSpecification.totalNumberToRun; ujCtr++) {
            ApiClient apiClient = apiClientList.get(ujCtr % apiClientList.size());
            userJourneyThreads.add(new UserJourneyThread(testScript, userJourneyDescription, apiClient));
        }
        // TODO: support different patterns of kicking off user journeys. here they're all queued at
        // once
        List<Future<UserJourneyResult>> userJourneyFutures = threadPool.invokeAll(userJourneyThreads);
        userJourneyFutureLists.add(userJourneyFutures);
    }
    // wait until all threads either finish or time out
    for (int ctr = 0; ctr < scripts.size(); ctr++) {
        TestScriptSpecification testScriptSpecification = config.testScripts.get(ctr);
        ThreadPoolExecutor threadPool = threadPools.get(ctr);
        threadPool.shutdown();
        long totalTerminationTime = testScriptSpecification.expectedTimeForEach * testScriptSpecification.totalNumberToRun;
        boolean terminatedByItself = threadPool.awaitTermination(totalTerminationTime, testScriptSpecification.expectedTimeForEachUnitObj);
        // if the threads didn't finish in the expected time, then send them interrupts
        if (!terminatedByItself) {
            threadPool.shutdownNow();
        }
        if (!threadPool.awaitTermination(secondsToWaitForPoolShutdown, TimeUnit.SECONDS)) {
            System.out.println("Thread pool for test script " + ctr + " (" + testScriptSpecification.name + ") failed to terminate.");
        }
    }
    // compile the results from all thread pools
    for (int ctr = 0; ctr < scripts.size(); ctr++) {
        List<Future<UserJourneyResult>> userJourneyFutureList = userJourneyFutureLists.get(ctr);
        TestScriptSpecification testScriptSpecification = config.testScripts.get(ctr);
        for (Future<UserJourneyResult> userJourneyFuture : userJourneyFutureList) {
            UserJourneyResult result = null;
            if (userJourneyFuture.isDone())
                try {
                    // user journey thread completed and populated its own return object, which may include
                    // an exception
                    result = userJourneyFuture.get();
                    result.completed = true;
                } catch (ExecutionException execEx) {
                    // user journey thread threw an exception and didn't populate its own return object
                    result = new UserJourneyResult(testScriptSpecification.name, "");
                    result.completed = false;
                    result.exceptionThrown = execEx;
                }
            else {
                // user journey either was never started or got cancelled before it finished
                result = new UserJourneyResult(testScriptSpecification.name, "");
                result.completed = false;
            }
            userJourneyResults.add(result);
        }
    }
    // call the cleanup method of each test script
    Exception cleanupExceptionThrown = callTestScriptCleanups();
    if (cleanupExceptionThrown != null) {
        throw new RuntimeException("Error calling test script cleanup methods.", cleanupExceptionThrown);
    }
    // delete the deployment and restore any Kubernetes settings
    if (!config.server.skipDeployment) {
        deleteDeployment();
    }
    if (!config.server.skipKubernetes) {
        restoreKubernetesSettings();
    }
    // cleanup data project
    cleanupLeftoverTestData();
}
Also used : ArrayList(java.util.ArrayList) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) TestScriptSpecification(runner.config.TestScriptSpecification) TestUserSpecification(runner.config.TestUserSpecification) ExecutionException(java.util.concurrent.ExecutionException) ApiClient(bio.terra.datarepo.client.ApiClient) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) Future(java.util.concurrent.Future) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor)

Example 32 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project apiman by apiman.

the class KeycloakOAuth2 method authenticate.

@Override
public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) {
    OAuth2FlowType flowType = getFlowType(config.get("flowType"));
    JsonObject params = new JsonObject();
    if (config.get("username") != null) {
        params.put("username", config.get("username"));
    }
    if (config.get("password") != null) {
        params.put("password", config.get("password"));
    }
    OAuth2Auth oauth2 = KeycloakAuth.create(vertx, flowType, mapToJson(config));
    oauth2.getToken(params, tokenResult -> {
        if (tokenResult.succeeded()) {
            log.debug("OAuth2 Keycloak exchange succeeded.");
            AccessToken token = tokenResult.result();
            headerMap.set("Authorization", "Bearer " + token.principal().getString("access_token"));
            resultHandler.handle(Future.succeededFuture());
        } else {
            log.error("Access Token Error: {0}.", tokenResult.cause().getMessage());
            resultHandler.handle(Future.failedFuture(tokenResult.cause()));
        }
    });
    return this;
}
Also used : AccessToken(io.vertx.ext.auth.oauth2.AccessToken) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType)

Example 33 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project apiman by apiman.

the class KeycloakOAuthFactory method directGrant.

private static AuthHandler directGrant(Vertx vertx, VertxEngineConfig apimanConfig, JsonObject authConfig, OAuth2FlowType flowType, String role) {
    return new AuthHandler() {

        @Override
        public void handle(RoutingContext context) {
            try {
                String[] auth = Basic.decodeWithScheme(context.request().getHeader("Authorization"));
                doBasic2Oauth(context, role, auth[0], auth[1]);
            } catch (RuntimeException e) {
                handle400(context, e.getMessage());
            }
        }

        private void doBasic2Oauth(RoutingContext context, String role, String username, String password) {
            JsonObject params = new JsonObject().put("username", username).put("password", password);
            HttpClientOptions sslOptions = getHttpClientOptionsForKeycloak(authConfig);
            OAuth2Auth oauth2 = KeycloakAuth.create(vertx, flowType, authConfig, sslOptions);
            oauth2.authenticate(params, tokenResult -> {
                if (tokenResult.succeeded()) {
                    log.debug("OAuth2 Keycloak exchange succeeded.");
                    AccessToken token = (AccessToken) tokenResult.result();
                    token.isAuthorised(role, res -> {
                        if (res.result()) {
                            context.next();
                        } else {
                            String message = MessageFormat.format("User {0} does not have required role: {1}.", username, role);
                            log.error(message);
                            handle403(context, "insufficient_scope", message);
                        }
                    });
                } else {
                    String message = tokenResult.cause().getMessage();
                    log.error("Access Token Error: {0}.", message);
                    handle401(context, "invalid_token", message);
                }
            });
        }

        private void handle400(RoutingContext context, String message) {
            if (message != null)
                context.response().setStatusMessage(message);
            context.fail(400);
        }

        private void handle401(RoutingContext context, String error, String message) {
            String value = MessageFormat.format("Basic realm=\"{0}\" error=\"{1}\" error_message=\"{2}\"", "apiman-gw", error, message);
            context.response().putHeader("WWW-Authenticate", value);
            context.fail(401);
        }

        private void handle403(RoutingContext context, String error, String message) {
            String value = MessageFormat.format("Basic realm=\"{0}\" error=\"{1}\" error_message=\"{2}\"", "apiman-gw", error, message);
            context.response().putHeader("WWW-Authenticate", value);
            context.fail(403);
        }

        @Override
        public AuthHandler addAuthority(String authority) {
            return this;
        }

        @Override
        public AuthHandler addAuthorities(Set<String> authorities) {
            return this;
        }

        @Override
        public void parseCredentials(RoutingContext routingContext, Handler<AsyncResult<JsonObject>> handler) {
        }

        @Override
        public void authorize(User user, Handler<AsyncResult<Void>> handler) {
        }
    };
}
Also used : AuthHandler(io.vertx.ext.web.handler.AuthHandler) OAuth2AuthHandler(io.vertx.ext.web.handler.OAuth2AuthHandler) Set(java.util.Set) User(io.vertx.ext.auth.User) JsonObject(io.vertx.core.json.JsonObject) AuthHandler(io.vertx.ext.web.handler.AuthHandler) OAuth2AuthHandler(io.vertx.ext.web.handler.OAuth2AuthHandler) Handler(io.vertx.core.Handler) HttpClientOptions(io.vertx.core.http.HttpClientOptions) RoutingContext(io.vertx.ext.web.RoutingContext) AccessToken(io.vertx.ext.auth.oauth2.AccessToken) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth)

Example 34 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project cloud-pipeline by epam.

the class FirecloudManagerTest method setUp.

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    when(firecloudClient.getMethods(Mockito.eq(ACCESS_TOKEN))).thenReturn(new MockCall<>(getTestList()));
    when(firecloudClient.getMethod(Mockito.eq(ACCESS_TOKEN), Mockito.anyString(), Mockito.anyString(), Mockito.anyLong())).thenReturn(new MockCall<>(getExpectedMethodDescription()));
    when(firecloudClient.getConfigurations(Mockito.eq(ACCESS_TOKEN), Mockito.anyString(), Mockito.anyString())).thenReturn(new MockCall<>(getExpectedConfigurations()));
    when(firecloudClient.getInputsOutputs(Mockito.eq(ACCESS_TOKEN), Mockito.any())).thenReturn(new MockCall<>(getExpectedInputsOutputs()));
    when(credentialsManager.getDefaultToken()).thenReturn(new AccessToken(REFRESH_TOKEN, null));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Before(org.junit.Before)

Example 35 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project terra-workspace-manager by DataBiosphere.

the class ClientTestUtils method getClientForTestRunnerSA.

/**
 * Build the Workspace Manager Service API client object for the given server specification. It is
 * setting the access token for the Test Runner SA specified in the given server specification.
 *
 * <p>A Test Runner SA is a GCP SA with appropriate permissions / scopes to run all the client
 * tests within this repo. For example, to run resiliency tests against K8S infrastructure, you'll
 * need a SA powerful enough to do things like list, read, and update.
 *
 * @param server the server we are testing against
 * @return the API client object
 */
public static ApiClient getClientForTestRunnerSA(ServerSpecification server) throws IOException {
    if (server.testRunnerServiceAccount == null) {
        throw new IllegalArgumentException("Workspace Manager Service client service account is required");
    }
    // refresh the client service account token
    GoogleCredentials serviceAccountCredential = AuthenticationUtils.getServiceAccountCredential(server.testRunnerServiceAccount, AuthenticationUtils.userLoginScopes);
    AccessToken accessToken = AuthenticationUtils.getAccessToken(serviceAccountCredential);
    logger.debug("Generated access token for workspace manager service client SA: {}", server.testRunnerServiceAccount.name);
    return buildClient(accessToken, server);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)72 Test (org.junit.Test)41 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)30 Date (java.util.Date)22 IOException (java.io.IOException)19 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Client (javax.ws.rs.client.Client)10 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)10 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)10 JsonObject (io.vertx.core.json.JsonObject)9 URI (java.net.URI)9 Feature (javax.ws.rs.core.Feature)8 JerseyTest (org.glassfish.jersey.test.JerseyTest)8 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)6 InputStreamReader (java.io.InputStreamReader)6 Instant (java.time.Instant)6 WebTarget (javax.ws.rs.client.WebTarget)6 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)6 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)5 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)5