Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(iam): add utility class for ServiceAccount test #10058

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
199 changes: 199 additions & 0 deletions iam/snippets/src/test/java/Util.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
/* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import com.google.cloud.iam.admin.v1.IAMClient;
import com.google.iam.admin.v1.CreateServiceAccountKeyRequest;
import com.google.iam.admin.v1.CreateServiceAccountRequest;
import com.google.iam.admin.v1.DeleteServiceAccountKeyRequest;
import com.google.iam.admin.v1.DeleteServiceAccountRequest;
import com.google.iam.admin.v1.DisableServiceAccountRequest;
import com.google.iam.admin.v1.GetServiceAccountKeyRequest;
import com.google.iam.admin.v1.KeyName;
import com.google.iam.admin.v1.ListServiceAccountKeysRequest;
import com.google.iam.admin.v1.ProjectName;
import com.google.iam.admin.v1.ServiceAccount;
import com.google.iam.admin.v1.ServiceAccountKey;
import com.google.iam.admin.v1.ServiceAccountName;
import java.io.IOException;
import java.util.List;

public class Util {
public static ServiceAccount setUpTest_createServiceAccount(
String projectId, String serviceAccountName) throws IOException, InterruptedException {

ServiceAccount serviceAccount =
ServiceAccount.newBuilder().setDisplayName("service-account-test").build();
CreateServiceAccountRequest request =
CreateServiceAccountRequest.newBuilder()
.setName(ProjectName.of(projectId).toString())
.setAccountId(serviceAccountName)
.setServiceAccount(serviceAccount)
.build();
try (IAMClient iamClient = IAMClient.create()) {
serviceAccount = iamClient.createServiceAccount(request);
}
awaitForServiceAccountCreation(projectId, serviceAccountName);
return serviceAccount;
}

public static void setUpTest_disableSertviceAccount(String projectId, String serviceAccountName)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Typo in method name: setUpTest_disableSertviceAccount. Should be setUpTest_disableServiceAccount.

Suggested change
public static void setUpTest_disableSertviceAccount(String projectId, String serviceAccountName)
public static void setUpTest_disableServiceAccount(String projectId, String serviceAccountName)
throws IOException {

throws IOException {
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);

try (IAMClient iamClient = IAMClient.create()) {
iamClient.disableServiceAccount(
DisableServiceAccountRequest.newBuilder()
.setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
.build());
}
}

public static void tearDownTest_deleteServiceAccount(String projectId, String serviceAccountName)
throws IOException {
try (IAMClient client = IAMClient.create()) {
String accountName = ServiceAccountName.of(projectId, serviceAccountName).toString();
String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The accountName variable is already a formatted string. You are then re-formatting it into accountEmail. Consider using accountName directly in the DeleteServiceAccountRequest to avoid this reformatting.

Suggested change
String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
DeleteServiceAccountRequest request =
DeleteServiceAccountRequest.newBuilder().setName(accountName).build();

Comment on lines +66 to +67

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It looks like accountName is already the name of the service account, so there's no need to call .toString() on it. Also, the accountEmail is constructed using accountName instead of serviceAccountName, which might lead to unexpected behavior. Consider using serviceAccountName instead.

Suggested change
String accountName = ServiceAccountName.of(projectId, serviceAccountName).toString();
String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", accountName, projectId);
String accountEmail = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);

DeleteServiceAccountRequest request =
DeleteServiceAccountRequest.newBuilder().setName(accountEmail).build();
client.deleteServiceAccount(request);
}
}

public static IAMClient.ListServiceAccountsPagedResponse test_listServiceAccounts(
String projectId) throws IOException {
try (IAMClient iamClient = IAMClient.create()) {
return iamClient.listServiceAccounts(String.format("projects/%s", projectId));
}
}

public static ServiceAccount test_getServiceAccount(String projectId, String serviceAccountName)
throws IOException {
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
String accountFullName = String.format("projects/%s/serviceAccounts/%s", projectId, email);
try (IAMClient iamClient = IAMClient.create()) {
return iamClient.getServiceAccount(accountFullName);
}
}

public static ServiceAccountKey setUpTest_createServiceAccountKey(
String projectId, String serviceAccountName) throws IOException, InterruptedException {
awaitForServiceAccountCreation(projectId, serviceAccountName);
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
try (IAMClient iamClient = IAMClient.create()) {
CreateServiceAccountKeyRequest req =
CreateServiceAccountKeyRequest.newBuilder()
.setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
.build();
ServiceAccountKey createdKey = iamClient.createServiceAccountKey(req);
String serviceAccountKeyId = getServiceAccountKeyIdFromKey(createdKey);
awaitForServiceAccountKeyCreation(projectId, serviceAccountName, serviceAccountKeyId);

return createdKey;
}
}

public static void setUpTest_disableServiceAccountKey(
String projectId, String serviceAccountName, String serviceAccountKeyId) throws IOException {
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
String name =
String.format(
"projects/%s/serviceAccounts/%s/keys/%s", projectId, email, serviceAccountKeyId);
try (IAMClient iamClient = IAMClient.create()) {
iamClient.disableServiceAccountKey(name);
}
}

public static String getServiceAccountKeyIdFromKey(ServiceAccountKey key) {
return key.getName().substring(key.getName().lastIndexOf("/") + 1).trim();
}
Comment on lines +120 to +122

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Consider adding a null check for the key parameter to avoid a potential NullPointerException if key is null.

Suggested change
public static String getServiceAccountKeyIdFromKey(ServiceAccountKey key) {
return key.getName().substring(key.getName().lastIndexOf("/") + 1).trim();
}
public static String getServiceAccountKeyIdFromKey(ServiceAccountKey key) {
return key != null ? key.getName().substring(key.getName().lastIndexOf("/") + 1).trim() : null;
}


public static void tearDownTest_deleteServiceAccountKey(
String projectId, String serviceAccountName, String serviceAccountKeyId) throws IOException {
String accountEmail =
String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
String name = KeyName.of(projectId, accountEmail, serviceAccountKeyId).toString();

DeleteServiceAccountKeyRequest request =
DeleteServiceAccountKeyRequest.newBuilder().setName(name).build();

try (IAMClient iamClient = IAMClient.create()) {
iamClient.deleteServiceAccountKey(request);
}
}

public static List<ServiceAccountKey> test_listServiceAccountKeys(
String projectId, String serviceAccountName) throws IOException {
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
ListServiceAccountKeysRequest request =
ListServiceAccountKeysRequest.newBuilder()
.setName(String.format("projects/%s/serviceAccounts/%s", projectId, email))
.build();

try (IAMClient iamClient = IAMClient.create()) {
return iamClient.listServiceAccountKeys(request).getKeysList();
}
}

public static ServiceAccountKey test_getServiceAccountKey(
String projectId, String serviceAccountName, String serviceAccountKeyId) throws IOException {
String email = String.format("%s@%s.iam.gserviceaccount.com", serviceAccountName, projectId);
String name =
String.format(
"projects/%s/serviceAccounts/%s/keys/%s", projectId, email, serviceAccountKeyId);
try (IAMClient iamClient = IAMClient.create()) {
return iamClient.getServiceAccountKey(
GetServiceAccountKeyRequest.newBuilder().setName(name).build());
}
}

private static void awaitForServiceAccountCreation(String projectId, String serviceAccountName)
throws InterruptedException {
boolean isAccountCreated = false;
long time = 1000;
long timeLimit = 60000;
while (!isAccountCreated) {
try {
test_getServiceAccount(projectId, serviceAccountName);
isAccountCreated = true;
} catch (Exception e) {
Thread.sleep(time);
time *= 2;
if (time > timeLimit) {
break;
}
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Catching Exception is too broad. It's better to catch specific exceptions like IOException or InterruptedException and handle them appropriately. Also, consider logging the exception to provide more context when the await fails.

      } catch (IOException | InterruptedException e) {
        Thread.sleep(time);
        time *= 2;
        if (time > timeLimit) {
          // Log the exception here
          break;
        }
      }

}

private static void awaitForServiceAccountKeyCreation(
String projectId, String serviceAccountName, String serviceAccountKeyId)
throws InterruptedException {
boolean isAccountCreated = false;
long time = 1000;
long timeLimit = 60000;
while (!isAccountCreated) {
try {
test_getServiceAccountKey(projectId, serviceAccountName, serviceAccountKeyId);
isAccountCreated = true;
} catch (Exception e) {
if (time > timeLimit) {
break;
}
Thread.sleep(time);
time *= 2;
}
}
Comment on lines +182 to +199

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

Similar to awaitForServiceAccountCreation, catching Exception is too broad here. Catch specific exceptions and log them for better error handling.

      } catch (IOException | InterruptedException e) {
        if (time > timeLimit) {
          // Log the exception here
          break;
        }
        Thread.sleep(time);
        time *= 2;
      }

}
}