Search in sources :

Example 96 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project jade-data-repo by DataBiosphere.

the class KubernetesClientUtils method buildKubernetesClientObject.

/**
 * Build the singleton Kubernetes client objects. This method should be called once at the
 * beginning of a test run, and then all subsequent fetches should use the getter methods instead.
 *
 * @param server the server specification that points to the relevant Kubernetes cluster
 */
public static void buildKubernetesClientObject(ServerSpecification server) throws Exception {
    // call the fetchGKECredentials script that uses gcloud to generate the kubeconfig file
    List<String> scriptArgs = new ArrayList<>();
    scriptArgs.add("tools/fetchGKECredentials.sh");
    scriptArgs.add(server.clusterShortName);
    scriptArgs.add(server.region);
    scriptArgs.add(server.project);
    ProcessUtils.executeCommand("sh", scriptArgs);
    // path to kubeconfig file, that was just created/updated by gcloud get-credentials above
    String kubeConfigPath = System.getProperty("user.home") + "/.kube/config";
    // load the kubeconfig object from the file
    InputStreamReader filereader = new InputStreamReader(new FileInputStream(kubeConfigPath), StandardCharsets.UTF_8);
    KubeConfig kubeConfig = KubeConfig.loadKubeConfig(filereader);
    // get a refreshed SA access token and its expiration time
    GoogleCredentials applicationDefaultCredentials = AuthenticationUtils.getApplicationDefaultCredential();
    AccessToken accessToken = AuthenticationUtils.getAccessToken(applicationDefaultCredentials);
    Instant tokenExpiration = accessToken.getExpirationTime().toInstant();
    String expiryUTC = tokenExpiration.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT);
    // USERS: build list of one user, the SA
    LinkedHashMap<String, Object> authConfigSA = new LinkedHashMap<>();
    authConfigSA.put("access-token", accessToken.getTokenValue());
    authConfigSA.put("expiry", expiryUTC);
    LinkedHashMap<String, Object> authProviderSA = new LinkedHashMap<>();
    authProviderSA.put("name", "gcp");
    authProviderSA.put("config", authConfigSA);
    LinkedHashMap<String, Object> userSA = new LinkedHashMap<>();
    userSA.put("auth-provider", authProviderSA);
    LinkedHashMap<String, Object> userWrapperSA = new LinkedHashMap<>();
    userWrapperSA.put("name", server.clusterName);
    userWrapperSA.put("user", userSA);
    ArrayList<Object> usersList = new ArrayList<>();
    usersList.add(userWrapperSA);
    // CONTEXTS: build list of one context, the specified cluster
    LinkedHashMap<String, Object> context = new LinkedHashMap<>();
    context.put("cluster", server.clusterName);
    context.put("user", // when is the user ever different from the cluster name?
    server.clusterName);
    LinkedHashMap<String, Object> contextWrapper = new LinkedHashMap<>();
    contextWrapper.put("name", server.clusterName);
    contextWrapper.put("context", context);
    ArrayList<Object> contextsList = new ArrayList<>();
    contextsList.add(contextWrapper);
    // CLUSTERS: use the cluster list read in from the kubeconfig file, because I can't figure out
    // how to get the certificate-authority-data and server address for the cluster via the Java
    // client library, only with gcloud
    ArrayList<Object> clusters = kubeConfig.getClusters();
    // build the config object, replacing the contexts and users lists from the kubeconfig file with
    // the ones constructed programmatically above
    kubeConfig = new KubeConfig(contextsList, clusters, usersList);
    kubeConfig.setContext(server.clusterName);
    // build the client object from the config
    ApiClient client = ClientBuilder.kubeconfig(kubeConfig).build();
    // set the global default client to the one created above because the CoreV1Api and AppsV1Api
    // constructors get the client object from the global configuration
    Configuration.setDefaultApiClient(client);
    kubernetesClientCoreObject = new CoreV1Api();
    kubernetesClientAppsObject = new AppsV1Api();
}
Also used : AppsV1Api(io.kubernetes.client.openapi.apis.AppsV1Api) InputStreamReader(java.io.InputStreamReader) Instant(java.time.Instant) ArrayList(java.util.ArrayList) ApiClient(io.kubernetes.client.openapi.ApiClient) FileInputStream(java.io.FileInputStream) LinkedHashMap(java.util.LinkedHashMap) AccessToken(com.google.auth.oauth2.AccessToken) KubeConfig(io.kubernetes.client.util.KubeConfig) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) CoreV1Api(io.kubernetes.client.openapi.apis.CoreV1Api)

Example 97 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project terra-resource-buffer by DataBiosphere.

the class BufferServiceUtils method getClient.

/**
 * Build the Buffer Service API client object for the given server specification.
 *
 * @param server the server we are testing against
 * @return the API client object
 */
public static ApiClient getClient(ServerSpecification server) throws IOException {
    if (Strings.isNullOrEmpty(server.bufferUri)) {
        throw new IllegalArgumentException("Buffer Service URI cannot be empty");
    }
    if (server.bufferClientServiceAccount == null) {
        throw new IllegalArgumentException("Buffer Service client service account is required");
    }
    // refresh the client service account token
    GoogleCredentials serviceAccountCredential = AuthenticationUtils.getServiceAccountCredential(server.bufferClientServiceAccount, AuthenticationUtils.userLoginScopes);
    AccessToken accessToken = AuthenticationUtils.getAccessToken(serviceAccountCredential);
    logger.debug("Generated access token for buffer service client SA: {}", server.bufferClientServiceAccount.name);
    // build the client object
    ApiClient apiClient = new ApiClient();
    apiClient.setBasePath(server.bufferUri);
    apiClient.setAccessToken(accessToken.getTokenValue());
    return apiClient;
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) ApiClient(bio.terra.buffer.client.ApiClient)

Example 98 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryRequestInitializerTest method testInitialize.

@Test
public void testInitialize() throws Exception {
    Credentials creds = GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000))));
    ArtifactRegistryRequestInitializer initializer = new ArtifactRegistryRequestInitializer(creds, 100);
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent("test content")).build();
    GenericUrl url = new GenericUrl("https://www.example.com");
    HttpRequestFactory requestFactory = transport.createRequestFactory(initializer);
    HttpRequest request = requestFactory.buildHeadRequest(url);
    Assert.assertEquals(request.getReadTimeout(), 100);
    Assert.assertEquals(request.getHeaders().getFirstHeaderStringValue("Authorization"), "Bearer test-access-token");
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) AccessToken(com.google.auth.oauth2.AccessToken) GenericUrl(com.google.api.client.http.GenericUrl) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Credentials(com.google.auth.Credentials) Test(org.junit.Test)

Example 99 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testHeadExists.

@Test
public void testHeadExists() throws Exception {
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setStatusCode(HttpStatusCodes.STATUS_CODE_OK)).build();
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    Assert.assertTrue(wagon.resourceExists("my/resource"));
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) AccessToken(com.google.auth.oauth2.AccessToken) Test(org.junit.Test)

Example 100 with AccessToken

use of com.microsoft.identity.common.internal.providers.oauth2.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testAuthenticatedPut.

@Test
public void testAuthenticatedPut() throws Exception {
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse()).build();
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    File f = FileTestUtils.createUniqueFile("my/artifact/dir", "test");
    Files.asCharSink(f, Charset.defaultCharset()).write("test content");
    wagon.put(f, "my/resource");
    String authHeader = transport.getLowLevelHttpRequest().getFirstHeaderValue("Authorization");
    Assert.assertEquals("Bearer test-access-token", authHeader);
    Assert.assertEquals("test content", transport.getLowLevelHttpRequest().getContentAsString());
    Assert.assertEquals("https://maven.pkg.dev/my-project/my-repo/my/resource", transport.getLowLevelHttpRequest().getUrl());
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) AccessToken(com.google.auth.oauth2.AccessToken) File(java.io.File) Test(org.junit.Test)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)78 Test (org.junit.Test)44 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)33 Date (java.util.Date)23 IOException (java.io.IOException)20 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Instant (java.time.Instant)10 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 ServiceAccountCredentials (com.google.auth.oauth2.ServiceAccountCredentials)6 Credential (io.cdap.cdap.proto.security.Credential)6 InputStreamReader (java.io.InputStreamReader)6 Clock (java.time.Clock)6 WebTarget (javax.ws.rs.client.WebTarget)6