def _extract_project_id()

in gcpdiag/queries/iam.py [0:0]


def _extract_project_id(email: str):
  if email in _service_account_cache:
    return _service_account_cache[email].project_id

  if email.endswith('.iam.gserviceaccount.com') and \
    not (email.startswith('service-') or email.split('@')[1].startswith('gcp-sa-')):
    project_id = re.split(r'[@ .]', email)[1]
    return project_id
    # extract project number from service agents and compute default SA
  elif email.partition('@')[2] in SERVICE_AGENT_DOMAINS or \
      email.partition('@')[2].startswith('gcp-sa-') or \
      email.endswith(DEFAULT_SERVICE_ACCOUNT_DOMAINS[1]):
    # AppEngine Default SA is unique
    if email.endswith(DEFAULT_SERVICE_ACCOUNT_DOMAINS[0]):
      return email.partition('@')[0]

    m = re.search(r'[\d]+', email.partition('@')[0])
    if m and (m.group(0) is not None):
      try:
        project_id = crm.get_project(m.group(0)).id
      except utils.GcpApiError:
        # Default to using '-' wildcard to infer the project.
        # - wildcard character is unreliable and should be used as last resort
        # because it can cause response codes to contain misleading error codes
        # such as 403 for deleted service accounts instead of returning 404
        # https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/get
        logging.warning(
            'Using "-" wildcard to infer host project for service account: %s. '
            'Rules which rely on method: projects.serviceAccounts.get to determine '
            'disabled vrs deleted status of %s may produce misleading results. '
            'See: https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/get',
            email, email)
        return '-'
      else:
        return project_id
  else:
    logging.warning(
        'Using "-" wildcard to infer host project for service account: %s. '
        'Rules which rely on method: projects.serviceAccounts.get to determine '
        'disabled vrs deleted status of %s may produce misleading results. '
        'See: https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/get',
        email, email)
    return '-'