Search in sources :

Example 81 with AccessToken

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

the class PrivateResourceCleanupServiceTest method cleanupResourcesSuppressExceptions_cleansApplicationPrivateResource_succeeds.

@Test
@DisabledIfEnvironmentVariable(named = "TEST_ENV", matches = BUFFER_SERVICE_DISABLED_ENVS_REG_EX)
void cleanupResourcesSuppressExceptions_cleansApplicationPrivateResource_succeeds() {
    // Default user owns the workspace and group. Secondary user has workspace membership via group.
    // Add second user to group
    addUserToGroup(groupName, userAccessUtils.getSecondUserEmail(), ownerGroupApi);
    // Add group to workspace as writer
    SamRethrow.onInterrupted(() -> samService.grantWorkspaceRole(workspace.getWorkspaceId(), userAccessUtils.defaultUserAuthRequest(), WsmIamRole.WRITER, groupEmail), "grantWorkspaceRole");
    // Enable the WSM test app in this workspace. This has a test user as the "service account" so
    // we can delegate credentials normally.
    WsmApplication app = applicationDao.getApplication(TEST_WSM_APP);
    AccessToken saAccessToken = userAccessUtils.generateAccessToken(app.getServiceAccount());
    AuthenticatedUserRequest appRequest = new AuthenticatedUserRequest().email(app.getServiceAccount()).token(Optional.of(saAccessToken.getTokenValue()));
    wsmApplicationService.enableWorkspaceApplication(userAccessUtils.defaultUserAuthRequest(), workspace.getWorkspaceId(), TEST_WSM_APP);
    // Create application private bucket assigned to second user.
    ControlledResourceFields commonFields = ControlledResourceFixtures.makeDefaultControlledResourceFieldsBuilder().workspaceUuid(workspace.getWorkspaceId()).accessScope(AccessScopeType.ACCESS_SCOPE_PRIVATE).managedBy(ManagedByType.MANAGED_BY_APPLICATION).applicationId(TEST_WSM_APP).assignedUser(userAccessUtils.getSecondUserEmail()).build();
    ControlledGcsBucketResource resource = ControlledGcsBucketResource.builder().common(commonFields).bucketName(ControlledResourceFixtures.uniqueBucketName()).build();
    ApiGcpGcsBucketCreationParameters creationParameters = new ApiGcpGcsBucketCreationParameters().location("us-central1");
    // Create resource as application.
    controlledResourceService.createControlledResourceSync(resource, ControlledResourceIamRole.WRITER, appRequest, creationParameters);
    // Verify second user can read the private resource in Sam.
    SamRethrow.onInterrupted(() -> samService.checkAuthz(userAccessUtils.secondUserAuthRequest(), resource.getCategory().getSamResourceName(), resource.getResourceId().toString(), SamControlledResourceActions.READ_ACTION), "checkResourceAuth");
    // Remove second user from workspace via group.
    removeUserFromGroup(groupName, userAccessUtils.getSecondUserEmail(), ownerGroupApi);
    // Verify second user is no longer in workspace, but still has resource access because cleanup
    // hasn't run yet.
    assertFalse(SamRethrow.onInterrupted(() -> samService.isAuthorized(userAccessUtils.secondUserAuthRequest(), SamResource.WORKSPACE, resource.getWorkspaceId().toString(), SamWorkspaceAction.READ), "checkResourceAuth"));
    assertTrue(SamRethrow.onInterrupted(() -> samService.isAuthorized(userAccessUtils.secondUserAuthRequest(), resource.getCategory().getSamResourceName(), resource.getResourceId().toString(), SamControlledResourceActions.READ_ACTION), "checkResourceAuth"));
    // Manually enable and run cleanup.
    privateResourceCleanupConfiguration.setEnabled(true);
    // Calling "cleanupResources" manually lets us skip waiting for the cronjob to trigger.
    privateResourceCleanupService.cleanupResourcesSuppressExceptions();
    // Verify second user can no longer read the resource.
    assertFalse(SamRethrow.onInterrupted(() -> samService.isAuthorized(userAccessUtils.secondUserAuthRequest(), resource.getCategory().getSamResourceName(), resource.getResourceId().toString(), SamControlledResourceActions.READ_ACTION), "checkResourceAuth"));
    // Verify resource is marked "abandoned"
    ControlledResource dbResource = resourceDao.getResource(resource.getWorkspaceId(), resource.getResourceId()).castToControlledResource();
    assertEquals(PrivateResourceState.ABANDONED, dbResource.getPrivateResourceState().get());
    // Application can still read the resource, because applications have EDITOR role on their
    // application-private resources.
    assertTrue(SamRethrow.onInterrupted(() -> samService.isAuthorized(appRequest, resource.getCategory().getSamResourceName(), resource.getResourceId().toString(), SamControlledResourceActions.READ_ACTION), "checkResourceAuth"));
}
Also used : WsmApplication(bio.terra.workspace.service.workspace.model.WsmApplication) AccessToken(com.google.auth.oauth2.AccessToken) ControlledResource(bio.terra.workspace.service.resource.controlled.model.ControlledResource) AuthenticatedUserRequest(bio.terra.workspace.service.iam.AuthenticatedUserRequest) ControlledResourceFields(bio.terra.workspace.service.resource.controlled.model.ControlledResourceFields) ApiGcpGcsBucketCreationParameters(bio.terra.workspace.generated.model.ApiGcpGcsBucketCreationParameters) ControlledGcsBucketResource(bio.terra.workspace.service.resource.controlled.cloud.gcp.gcsbucket.ControlledGcsBucketResource) BaseConnectedTest(bio.terra.workspace.common.BaseConnectedTest) Test(org.junit.jupiter.api.Test) DisabledIfEnvironmentVariable(org.junit.jupiter.api.condition.DisabledIfEnvironmentVariable)

Example 82 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project java-bigtable by googleapis.

the class BigtableChannelPrimerTest method setup.

@Before
public void setup() throws IOException {
    fakeService = new FakeService();
    metadataInterceptor = new MetadataInterceptor();
    server = FakeServiceBuilder.create(fakeService).intercept(metadataInterceptor).start();
    primer = BigtableChannelPrimer.create(OAuth2Credentials.create(new AccessToken(TOKEN_VALUE, null)), "fake-project", "fake-instance", "fake-app-profile", ImmutableList.of("table1", "table2"));
    channel = ManagedChannelBuilder.forAddress("localhost", server.getPort()).usePlaintext().build();
    logHandler = new LogHandler();
    Logger.getLogger(BigtableChannelPrimer.class.toString()).addHandler(logHandler);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Before(org.junit.Before)

Example 83 with AccessToken

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

the class CredentialRetrieverFactoryTest method setUp.

@Before
public void setUp() throws CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException, IOException {
    Mockito.when(mockDockerCredentialHelperFactory.create(Mockito.anyString(), Mockito.any(Path.class), Mockito.anyMap())).thenReturn(mockDockerCredentialHelper);
    Mockito.when(mockDockerCredentialHelper.retrieve()).thenReturn(FAKE_CREDENTIALS);
    Mockito.when(mockGoogleCredentials.getAccessToken()).thenReturn(new AccessToken("my-token", null));
}
Also used : Path(java.nio.file.Path) AccessToken(com.google.auth.oauth2.AccessToken) Before(org.junit.Before)

Example 84 with AccessToken

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

the class OAuth2 method authenticate.

@Override
public Authenticator authenticate(Vertx vertx, Map<String, String> config, MultiMap headerMap, Handler<AsyncResult<Void>> resultHandler) {
    OAuth2ClientOptions credentials = new OAuth2ClientOptions(mapToJson(config));
    if (config.get("oauthUri") != null) {
        credentials.setSite(config.get("oauthUri"));
    }
    if (config.get("clientId") != null) {
        credentials.setClientID(config.get("clientId"));
    }
    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 = OAuth2Auth.create(vertx, flowType, credentials);
    oauth2.getToken(params, tokenResult -> {
        if (tokenResult.succeeded()) {
            log.debug("OAuth2 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) OAuth2ClientOptions(io.vertx.ext.auth.oauth2.OAuth2ClientOptions) JsonObject(io.vertx.core.json.JsonObject) OAuth2Auth(io.vertx.ext.auth.oauth2.OAuth2Auth) OAuth2FlowType(io.vertx.ext.auth.oauth2.OAuth2FlowType)

Example 85 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project java-spanner-jdbc by googleapis.

the class ITJdbcConnectTest method testConnectWithOAuthToken.

@Test
public void testConnectWithOAuthToken() throws Exception {
    GoogleCredentials credentials;
    if (hasValidKeyFile()) {
        credentials = GoogleCredentials.fromStream(new FileInputStream(getKeyFile()));
    } else {
        try {
            credentials = GoogleCredentials.getApplicationDefault();
        } catch (IOException e) {
            credentials = null;
        }
    }
    // Skip this test if there are no credentials set for the test case or environment.
    if (credentials != null) {
        credentials = credentials.createScoped(SpannerOptions.getDefaultInstance().getScopes());
        AccessToken token = credentials.refreshAccessToken();
        String urlWithOAuth = createBaseUrl() + ";OAuthToken=" + token.getTokenValue();
        try (Connection connectionWithOAuth = DriverManager.getConnection(urlWithOAuth)) {
            // Try to do a query using the connection created with an OAuth token.
            testDefaultConnection(connectionWithOAuth);
        }
    }
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Connection(java.sql.Connection) CloudSpannerJdbcConnection(com.google.cloud.spanner.jdbc.CloudSpannerJdbcConnection) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ParallelIntegrationTest(com.google.cloud.spanner.ParallelIntegrationTest) 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