com.google.api.services.iam.v1.Iam Java Examples

The following examples show how to use com.google.api.services.iam.v1.Iam. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceAccountUtilTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  keyFile = tempFolder.getRoot().toPath().resolve("key.json");

  Iam iam = mock(Iam.class);
  Projects projects = mock(Projects.class);
  ServiceAccounts serviceAccounts = mock(ServiceAccounts.class);
      
  when(apiFactory.newIamApi(any(Credential.class))).thenReturn(iam);
  when(iam.projects()).thenReturn(projects);
  when(projects.serviceAccounts()).thenReturn(serviceAccounts);
  when(serviceAccounts.keys()).thenReturn(keys);
  when(keys.create(
      eq("projects/my-project/serviceAccounts/[email protected]"),
      any(CreateServiceAccountKeyRequest.class))).thenReturn(create);

  ServiceAccountKey serviceAccountKey = new ServiceAccountKey();
  byte[] keyContent = "key data in JSON format".getBytes(StandardCharsets.UTF_8);
  serviceAccountKey.setPrivateKeyData(Base64.encodeBase64String(keyContent));
  
  when(create.execute()).thenReturn(serviceAccountKey);
}
 
Example #2
Source File: DeleteServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #3
Source File: DeleteServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #4
Source File: CreateServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #5
Source File: ListServiceAccounts.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #6
Source File: RenameServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #7
Source File: EnableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #8
Source File: ListServiceAccountKeys.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-account-keys")
          .build();
  return service;
}
 
Example #9
Source File: CreateServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #10
Source File: DisableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Iam initService() throws GeneralSecurityException, IOException {
  // Use the Application Default Credentials strategy for authentication. For more info, see:
  // https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
  // Initialize the IAM service, which can be used to send requests to the IAM API.
  Iam service =
      new Iam.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JacksonFactory.getDefaultInstance(),
              new HttpCredentialsAdapter(credential))
          .setApplicationName("service-accounts")
          .build();
  return service;
}
 
Example #11
Source File: GcpLocalRunTabTest.java    From google-cloud-eclipse with Apache License 2.0 6 votes vote down vote up
private static void setUpServiceKeyCreation(
    IGoogleApiFactory mockApiFactory, boolean throwException) throws IOException {
  Iam iam = Mockito.mock(Iam.class);
  Projects projects = Mockito.mock(Projects.class);
  ServiceAccounts serviceAccounts = Mockito.mock(ServiceAccounts.class);
  Keys keys = Mockito.mock(Keys.class);
  Create create = Mockito.mock(Create.class);

  ServiceAccountKey serviceAccountKey = new ServiceAccountKey();
  byte[] keyContent = "key data in JSON format".getBytes();
  serviceAccountKey.setPrivateKeyData(Base64.encodeBase64String(keyContent));

  when(mockApiFactory.newIamApi(any(Credential.class))).thenReturn(iam);
  when(iam.projects()).thenReturn(projects);
  when(projects.serviceAccounts()).thenReturn(serviceAccounts);
  when(serviceAccounts.keys()).thenReturn(keys);
  when(keys.create(anyString(), Matchers.any(CreateServiceAccountKeyRequest.class)))
      .thenReturn(create);

  if (throwException) {
    when(create.execute()).thenThrow(new IOException("log from unit test"));
  } else {
    when(create.execute()).thenReturn(serviceAccountKey);
  }
}
 
Example #12
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * Get the API stub for accessing the IAM Service Accounts API.
 * @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
 * @throws IOException Thrown if there's an IO error initializing the api connection.
 * @throws GeneralSecurityException Thrown if there's a security error
 * initializing the connection.
 */
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
  if (serviceAccountsApiStub == null) {
    HttpTransport transport;
    GoogleCredential credential;
    JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    transport = GoogleNetHttpTransport.newTrustedTransport();
    credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
    if (credential.createScopedRequired()) {
      Collection<String> scopes = IamScopes.all();
      credential = credential.createScoped(scopes);
    }
    serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
        .build()
        .projects()
        .serviceAccounts();
  }
  return serviceAccountsApiStub;
}
 
Example #13
Source File: ServiceAccountCleanupTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteExpiredTestServiceAccounts() throws IOException {
  var iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
      .setApplicationName(TestNamespaces.TEST_NAMESPACE_PREFIX)
      .build();

  var accounts = listServiceAccounts(iam);

  for (final ServiceAccount account : accounts) {
    var displayName = account.getDisplayName();
    if (displayName == null || !TestNamespaces.isExpiredTestNamespace(displayName, NOW)) {
      continue;
    }
    log.info("Deleting old test service account: {}", account.getEmail());
    try {
      var request = iam.projects().serviceAccounts()
          .delete("projects/styx-oss-test/serviceAccounts/" + account.getEmail());
      executeWithRetries(request);
    } catch (Throwable e) {
      log.error("Failed to delete old test service account: {}", account.getEmail(), e);
    }
  }
}
 
Example #14
Source File: StyxScheduler.java    From styx with Apache License 2.0 6 votes vote down vote up
private static ServiceAccountKeyManager createServiceAccountKeyManager() {
  try {
    final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
    final GoogleCredential credential = GoogleCredential
        .getApplicationDefault(httpTransport, jsonFactory)
        .createScoped(IamScopes.all());
    final Iam iam = new Iam.Builder(
        httpTransport, jsonFactory, credential)
        .setApplicationName(SERVICE_NAME)
        .build();
    return new ServiceAccountKeyManager(iam);
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #15
Source File: Authenticator.java    From styx with Apache License 2.0 6 votes vote down vote up
Authenticator(GoogleIdTokenVerifier googleIdTokenVerifier,
              CloudResourceManager cloudResourceManager,
              Iam iam,
              AuthenticatorConfiguration configuration,
              WaitStrategy retryWaitStrategy,
              StopStrategy retryStopStrategy) {
  this.googleIdTokenVerifier =
      Objects.requireNonNull(googleIdTokenVerifier, "googleIdTokenVerifier");
  this.cloudResourceManager =
      Objects.requireNonNull(cloudResourceManager, "cloudResourceManager");
  this.iam = Objects.requireNonNull(iam, "iam");
  this.domainWhitelist = configuration.domainWhitelist();
  this.resourceWhitelist = configuration.resourceWhitelist();
  this.allowedAudiences = configuration.allowedAudiences();
  this.retryWaitStrategy = Objects.requireNonNull(retryWaitStrategy, "retryWaitStrategy");
  this.retryStopStrategy = Objects.requireNonNull(retryStopStrategy, "retryStopStrategy");
}
 
Example #16
Source File: ManagedServiceAccountKeyCredentialTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  var defaultCredentials = GoogleCredentials.getApplicationDefault();

  var serviceCredentials = ImpersonatedCredentials.create(
      defaultCredentials, SERVICE_ACCOUNT,
      List.of(), List.of("https://www.googleapis.com/auth/cloud-platform"), 300);

  try {
    serviceCredentials.refreshAccessToken();
  } catch (IOException e) {
    // Do not run this test if we do not have permission to impersonate the test user.
    Assume.assumeNoException(e);
  }

  iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      new HttpCredentialsAdapter(serviceCredentials.createScoped(IamScopes.all())))
      .setApplicationName("styx-test")
      .build();
}
 
Example #17
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials,
                                                        String serviceAccount, String targetAudience)
    throws IOException {
  final String tokenServerUrl = "https://oauth2.googleapis.com/token";
  final Header header = jwtHeader();
  final JsonWebToken.Payload payload = jwtPayload(
      targetAudience, serviceAccount, tokenServerUrl);
  final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,
      new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build();
  final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "."
                         + Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload));
  byte[] contentBytes = StringUtils.getBytesUtf8(content);
  final SignBlobResponse signResponse;
  try {
    signResponse = iam.projects().serviceAccounts()
        .signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest()
            .encodeBytesToSign(contentBytes))
        .execute();
  } catch (GoogleJsonResponseException e) {
    if (e.getStatusCode() == 403) {
      throw new IOException(
          "Unable to sign request for id token, missing Service Account Token Creator role for self on "
          + serviceAccount + " or IAM api not enabled?", e);
    }
    throw e;
  }
  final String assertion = content + "." + signResponse.getSignature();
  final TokenRequest request = new TokenRequest(
      httpTransport, JSON_FACTORY,
      new GenericUrl(tokenServerUrl),
      "urn:ietf:params:oauth:grant-type:jwt-bearer");
  request.put("assertion", assertion);
  final TokenResponse tokenResponse = request.execute();
  return (String) tokenResponse.get("id_token");
}
 
Example #18
Source File: EndToEndTestBase.java    From styx with Apache License 2.0 5 votes vote down vote up
private void setUpServiceAccounts() throws IOException {
  // Create workflow service account
  iam = new Iam.Builder(
      Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
      GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
      .setApplicationName(testNamespace)
      .build();
  workflowServiceAccount = iam.projects().serviceAccounts()
      .create("projects/styx-oss-test",
          new CreateServiceAccountRequest().setAccountId(workflowServiceAccountId)
              .setServiceAccount(new ServiceAccount().setDisplayName(testNamespace)))
      .execute();
  log.info("Created workflow test service account: {}", workflowServiceAccount.getEmail());

  // Set up workflow service account permissions
  var workflowServiceAccountFqn = "projects/styx-oss-test/serviceAccounts/" + workflowServiceAccount.getEmail();
  var workflowServiceAccountPolicy = iam.projects().serviceAccounts()
      .getIamPolicy(workflowServiceAccountFqn)
      .execute();
  if (workflowServiceAccountPolicy.getBindings() == null) {
    workflowServiceAccountPolicy.setBindings(new ArrayList<>());
  }
  workflowServiceAccountPolicy.getBindings()
      .add(new Binding().setRole("projects/styx-oss-test/roles/StyxWorkflowServiceAccountUser")
          .setMembers(List.of("serviceAccount:[email protected]")));
  // TODO: set up a styx service account instead of using styx-circle-ci@
  workflowServiceAccountPolicy.getBindings()
      .add(new Binding().setRole("roles/iam.serviceAccountKeyAdmin")
          .setMembers(List.of("serviceAccount:[email protected]")));
  iam.projects().serviceAccounts().setIamPolicy(workflowServiceAccountFqn,
      new SetIamPolicyRequest().setPolicy(workflowServiceAccountPolicy))
      .execute();
}
 
Example #19
Source File: GrantableRoles.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

    GoogleCredentials credential =
        GoogleCredentials.getApplicationDefault()
            .createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));

    Iam service =
        new Iam.Builder(
                GoogleNetHttpTransport.newTrustedTransport(),
                JacksonFactory.getDefaultInstance(),
                new HttpCredentialsAdapter(credential))
            .setApplicationName("grantable-roles")
            .build();

    String fullResourceName = args[0];

    // [START iam_view_grantable_roles]
    QueryGrantableRolesRequest request = new QueryGrantableRolesRequest();
    request.setFullResourceName(fullResourceName);

    QueryGrantableRolesResponse response = service.roles().queryGrantableRoles(request).execute();

    for (Role role : response.getRoles()) {
      System.out.println("Title: " + role.getTitle());
      System.out.println("Name: " + role.getName());
      System.out.println("Description: " + role.getDescription());
      System.out.println();
    }
    // [END iam_view_grantable_roles]
  }
 
Example #20
Source File: AuthenticatorFactory.java    From styx with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
Iam buildIam(HttpTransport httpTransport, JsonFactory jsonFactory, GoogleCredential credential, String service) {
  return new Iam.Builder(
      httpTransport, jsonFactory, credential)
      .setApplicationName(service)
      .build();
}
 
Example #21
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 5 votes vote down vote up
Impl(Iam iam, CloudResourceManager crm, Directory directory, String serviceAccountUserRole,
     AuthorizationPolicy authorizationPolicy, WaitStrategy waitStrategy, StopStrategy retryStopStrategy,
     String message, List<String> administrators, List<String> blacklist) {
  this.iam = Objects.requireNonNull(iam, "iam");
  this.crm = Objects.requireNonNull(crm, "crm");
  this.directory = Objects.requireNonNull(directory, "directory");
  this.serviceAccountUserRole = Objects.requireNonNull(serviceAccountUserRole, "serviceAccountUserRole");
  this.authorizationPolicy = Objects.requireNonNull(authorizationPolicy, "authorizationPolicy");
  this.waitStrategy = Objects.requireNonNull(waitStrategy, "waitStrategy");
  this.retryStopStrategy = Objects.requireNonNull(retryStopStrategy, "retryStopStrategy");
  this.message = Objects.requireNonNull(message, "message");
  this.administrators = Objects.requireNonNull(administrators, "administrators");
  this.blacklist = Objects.requireNonNull(blacklist, "blacklist");
}
 
Example #22
Source File: Authenticator.java    From styx with Apache License 2.0 5 votes vote down vote up
Authenticator(GoogleIdTokenVerifier googleIdTokenVerifier,
              CloudResourceManager cloudResourceManager,
              Iam iam,
              AuthenticatorConfiguration configuration) {
  this(googleIdTokenVerifier, cloudResourceManager, iam, configuration,
      DEFAULT_RETRY_WAIT_STRATEGY,
      DEFAULT_RETRY_STOP_STRATEGY);
}
 
Example #23
Source File: GoogleApiFactory.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
@Override
public Iam newIamApi(Credential credential) {
  Preconditions.checkNotNull(transportCache, "transportCache is null");
  HttpTransport transport = transportCache.getUnchecked(GoogleApi.IAM_API);
  Preconditions.checkNotNull(transport, "transport is null");
  Preconditions.checkNotNull(jsonFactory, "jsonFactory is null");

  Iam iam = new Iam.Builder(transport, jsonFactory, credential)
      .setApplicationName(CloudToolsInfo.USER_AGENT).build();
  return iam;
}
 
Example #24
Source File: ServiceAccountUtil.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and saves a service account key the App Engine default service account.
 *
 * @param credential credential to use to create a service account key
 * @param projectId GCP project ID for {@code serviceAccountId} 
 * @param destination path of a key file to be saved
 */
public static void createAppEngineDefaultServiceAccountKey(IGoogleApiFactory apiFactory,
    Credential credential, String projectId, Path destination)
        throws FileAlreadyExistsException, IOException {
  Preconditions.checkNotNull(credential, "credential not given");
  Preconditions.checkState(!projectId.isEmpty(), "project ID empty");
  Preconditions.checkArgument(destination.isAbsolute(), "destination not absolute");

  if (!Files.exists(destination.getParent())) {
    Files.createDirectories(destination.getParent());
  }

  Iam iam = apiFactory.newIamApi(credential);
  Keys keys = iam.projects().serviceAccounts().keys();
  
  String projectEmail = projectId;
  // The appengine service account for google.com:gcloud-for-eclipse-testing 
  // would be gcloud-for-eclipse-testing.google.com@appspot.gserviceaccount.com.
  if (projectId.contains(":")) {
    String[] parts = projectId.split(":");
    projectEmail = parts[1] + "." + parts[0];
  }
  String serviceAccountId = projectEmail + "@appspot.gserviceaccount.com";

  String keyId = "projects/" + projectId + "/serviceAccounts/" + serviceAccountId;
  CreateServiceAccountKeyRequest createRequest = new CreateServiceAccountKeyRequest();
  ServiceAccountKey key = keys.create(keyId, createRequest).execute();

  byte[] jsonKey = Base64.decodeBase64(key.getPrivateKeyData());
  Files.write(destination, jsonKey);
}
 
Example #25
Source File: AuthenticatorFactoryTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldBuildIam() {
  final Iam iam = new DefaultAuthenticatorFactory()
      .buildIam(httpTransport, jsonFactory, googleCredential, "test");
  assertThat(iam.getRequestFactory().getTransport(), is(httpTransport));
  assertThat(iam.getJsonFactory(), is(jsonFactory));
  assertThat(iam.getRequestFactory().getInitializer(), is(googleCredential));
  assertThat(iam.getApplicationName(), is("test"));
}
 
Example #26
Source File: ServiceAccountCleanupTest.java    From styx with Apache License 2.0 5 votes vote down vote up
private List<ServiceAccount> listServiceAccounts(Iam iam) throws IOException {
  var accounts = new ArrayList<ServiceAccount>();
  String pageToken = null;
  do {
    var request = iam.projects().serviceAccounts().list("projects/styx-oss-test")
        .setPageToken(pageToken);
    var listResponse = executeWithRetries(request);
    accounts.addAll(listResponse.getAccounts());
    pageToken = listResponse.getNextPageToken();
  } while (pageToken != null);
  return accounts;
}
 
Example #27
Source File: AuthenticatorFactoryTest.java    From styx with Apache License 2.0 4 votes vote down vote up
@Override
Iam buildIam(HttpTransport httpTransport, JsonFactory jsonFactory,
             GoogleCredential credential,
             String service) {
  return iam;
}
 
Example #28
Source File: ManagedServiceAccountKeyCredential.java    From styx with Apache License 2.0 4 votes vote down vote up
Builder(Iam iam) {
  this.iam = Objects.requireNonNull(iam, "iam");
  setServiceAccountPrivateKey(DummyKey.INSTANCE);
}
 
Example #29
Source File: GoogleApiFactoryTest.java    From google-cloud-eclipse with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewIamApi() {
  Iam iam = googleApiFactory.newIamApi(mock(Credential.class));
  assertEquals("https://iam.googleapis.com/", iam.getBaseUrl());
}
 
Example #30
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
static ServiceAccountUsageAuthorizer create(String serviceAccountUserRole,
                                            AuthorizationPolicy authorizationPolicy,
                                            GoogleCredentials credentials,
                                            String gsuiteUserEmail,
                                            String serviceName,
                                            String message,
                                            List<String> administrators,
                                            List<String> blacklist) {

  final HttpTransport httpTransport;
  try {
    httpTransport = GoogleNetHttpTransport.newTrustedTransport();
  } catch (GeneralSecurityException | IOException e) {
    throw new RuntimeException(e);
  }

  final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();

  final CloudResourceManager crm = new CloudResourceManager.Builder(
      httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
      .setApplicationName(serviceName)
      .build();

  final Iam iam = new Iam.Builder(
      httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
      .setApplicationName(serviceName)
      .build();

  final GoogleCredential directoryCredential = new ManagedServiceAccountKeyCredential.Builder(iam)
      .setServiceAccountId(ServiceAccounts.serviceAccountEmail(credentials))
      .setServiceAccountUser(gsuiteUserEmail)
      .setServiceAccountScopes(Set.of(ADMIN_DIRECTORY_GROUP_MEMBER_READONLY))
      .build();

  final Directory directory = new Directory.Builder(httpTransport, jsonFactory, directoryCredential)
      .setApplicationName(serviceName)
      .build();

  return new Impl(iam, crm, directory, serviceAccountUserRole, authorizationPolicy,
      Impl.DEFAULT_WAIT_STRATEGY, Impl.DEFAULT_RETRY_STOP_STRATEGY, message, administrators, blacklist);
}