Skip to content

Commit 3659832

Browse files
authored
Infra iam enforcer service accounts (#36215)
* Updated compliance checks to skip service accounts that do not match the project_id, this is because we do not want to track gcp's service accounts * Refactor IAM user roles in users.yml to add service accounts and update permissions
1 parent 65dfd30 commit 3659832

File tree

2 files changed

+533
-7
lines changed

2 files changed

+533
-7
lines changed

infra/enforcement/iam.py

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,15 @@
2727
CONFIG_FILE = "config.yml"
2828

2929
class IAMPolicyComplianceChecker:
30+
31+
def is_project_service_account_email(self, email: Optional[str]) -> bool:
32+
"""
33+
Returns True if the email is not a service account, or if it is a service account and the email contains the project_id.
34+
"""
35+
if email and email.endswith('.gserviceaccount.com'):
36+
return self.project_id in email
37+
return True
38+
3039
def __init__(self, project_id: str, users_file: str, logger: logging.Logger, sending_client: Optional[SendingClient] = None):
3140
self.project_id = project_id
3241
self.users_file = users_file
@@ -94,6 +103,10 @@ def _export_project_iam(self) -> List[Dict]:
94103
for member_str in binding.members:
95104
if member_str not in members_data:
96105
username, email_address, member_type = self._parse_member(member_str)
106+
# Skip service accounts not matching the project_id
107+
if member_type == "serviceAccount" and not self.is_project_service_account_email(email_address):
108+
self.logger.debug(f"Skipping service account not matching project_id ({self.project_id}): {email_address}")
109+
continue
97110
if member_type == "unknown":
98111
self.logger.warning(f"Skipping member {member_str} with no email address")
99112
continue # Skip if no email address is found, probably a malformed member
@@ -190,8 +203,9 @@ def check_compliance(self) -> List[str]:
190203
Returns:
191204
A list of strings describing any compliance issues found.
192205
"""
193-
current_users = {user['email']: user for user in self._export_project_iam()}
194-
existing_users = {user['email']: user for user in self._read_project_iam_file()}
206+
207+
current_users = {user['email']: user for user in self._export_project_iam() if self.is_project_service_account_email(user.get('email'))}
208+
existing_users = {user['email']: user for user in self._read_project_iam_file() if self.is_project_service_account_email(user.get('email'))}
195209

196210
if not existing_users:
197211
error_msg = f"No IAM policy found in the {self.users_file}."

0 commit comments

Comments
 (0)