
    ;                         S r SSKJr  SSKJr  SSKJr  SSKrSSKJr  SSKJ	r
  SrS	rS
rSrSrSrSrSrSrSrSrSrSrSrSrSrSrSrS rS rS r S&S jr  S'S jr!S r"S  r#S! r$S" r%S# r&S$ r'S% r(g)(z*Smart Guardrails Recommendation Utilities.    )absolute_import)division)unicode_literalsN)insight)utila  Shutting down this project will immediately:
  - Stop all traffic and billing.
  - Start deleting resources.
  - Schedule the final deletion of the project after 30 days.
  - Block your access to the project.
  - Notify the owner of the project.

Learn more about the shutdown process at
https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects
zr*** HIGH-RISK CHANGE WARNING ***: If you shut down this project you risk losing data or interrupting your servicesz2. In the last 30 days we observed this project hadzAWe recommend verifying this is the correct project to shut down.
av  This service account lets App Engine and Cloud Functions access essential Cloud Platform services such as Datastore. Deleting this account will break any current or future App Engine applications and Cloud Functions in this project.

WARNING: You CANNOT  undo this action. Do not delete this service account unless you are sure you will never use App Engine in this project.a  This service account lets Compute Engine access essential Cloud Platform services such as logging and Cloud Storage. Deleting this account will prevent instances that are running as this account from accessing Cloud Platform services.

WARNING: You CANNOT undo this action. If you delete this account, instances in this project will only be able to access Cloud Platform services via custom service accounts.a:  Deleting this service account (SA) will delete all associated key IDs, and will prevent the account from authenticating to any Google Cloud service API.

You cannot restore or roll back this change easily. We highly recommend disabling the account first, testing for any unexpected impact, and only then deleting.
z*** HIGH-RISK CHANGE WARNING ***: If you delete this SA you risk interrupting your service, as we observed it was substantially used in the last 90 daysz>We recommend verifying this is the correct account to delete.
z'You are about to delete the role [{}].
z*** HIGH-RISK CHANGE WARNING ***: If you remove the role [{}], there is a high risk that you might cause interruptions because it was used in the last 90 daysz_We recommend you verify the details and replace them with less privileged roles, if necessary.
zuWe recommend replacing it with the role{} [{}], in order to remove unused permissions while preserving the used one.
z0google.resourcemanager.project.ChangeRiskInsightz+google.iam.serviceAccount.ChangeRiskInsightz#google.iam.policy.ChangeRiskInsightz5https://console.cloud.google.com/home/recommendations   c                    ^ ^ U U4S jnU$ )a'  Returns a function that matches an insight by policy binding.

Args:
  member: Member string to fully match.
  role: Member role to fully match.

Returns:
  A function that matches an insight object by policy binding. The returned
  function returns true iff both the member and the role match.
c                 n  > SnSnU R                   R                   GH  nUR                  S:X  d  M  UR                  R                  R
                   H  nUR                  S:X  d  M  UR                  R                  R
                   H  nUR                  S:X  d  M  UR                  R                  R
                   H_  nUR                  S:X  a  UR                  R                  T:X  a  SnUR                  S:X  d  MA  UR                  R                  T:X  d  M]  SnMa     M     M     GM     U=(       a    U$ )NFriskusageAtRiskiamPolicyUtilizationmemberTrole)contentadditionalPropertieskeyvalueobject_value
propertiesstring_value)	gcloud_insightmatches_membermatches_roleadditional_propertypfiam_pr   r   s	          ?lib/googlecloudsdk/api_lib/smart_guardrails/smart_guardrails.pyMatcher,_GetIamPolicyBindingMatcher.<locals>.Matcher   s    NL-55JJ		 	 F	*$**77BBAUUm#WW))4400WW11<<EYY(*{{//69'+nYY&({{//47%)l = 5 C  K *l*     )r   r   r   s   `` r   _GetIamPolicyBindingMatcherr#   v   s    +$ 
.r!   c                 B    SR                  [        U R                  5      $ )zReturns a message with a link to the associated recommendation.

Args:
  gcloud_insight: Insight object returned by the recommender API.

Returns:
  A string message with a link to the associated recommendation.
z3View the full risk assessment at: {0}/view-link/{1})format_RECOMMENDATIONS_HOME_URLname)r   s    r   _GetInsightLinkr(      s#     @	G	G!4!4
 r!   c                 8   / nSnSnU R                   R                   H  nUR                  S:X  d  M  UR                  R                  R
                   H  nUR                  S:X  d  M  UR                  R                  R                   HG  nUS-  nU[        :  a  UR                  UR                  5        M/  U[        :X  d  M;  UR                  nMI     M     M     U[        :  a  SR                  U[        -
  S-   5      nU[        :  a  UR                  U5        U$ )ap  Extracts a list of string reasons from the resource change insight.

Args:
  gcloud_insight: Insight object returned by the recommender API.

Returns:
  A list of strings. If no reasons could be found, then returns empty list.
  The number of reasons is limited by _MAX_NUMBER_OF_REASONS, and the last
  reason indicates how many more reasons there are if applicable.
r    
importancedetailedReasons   z{} other importance indicators.)r   r   r   r   r   r   array_valueentries_MAX_NUMBER_OF_REASONSappendr   r%   )r   reasonsnum_reasonslast_reasonr   r   reasons          r   _GetResourceRiskReasonsr6      s     '+++33HH,."((55@@!55%%++33f1K33nnV001 66"//k 4 A I ))3::,,q0K **NN;	.r!   c                    [        U 5      nU(       d  SR                  X(       a  S5      $ S5      $ [        U5      S:X  a  SR                  XUS   5      $ SR                  X5      nUSR                  S U 5       5      -  nU$ )	a  Returns a risk message for resource deletion.

Args:
  gcloud_insight: Insight object returned by the recommender API.
  risk_message: String risk message.
  reasons_prefix: String prefix before listing reasons.
  add_new_line: Bool for if a new line is added when no reasons are present.

Returns:
  Formatted string risk message with reasons if any. The reasons are
  extracted from the gcloud_insight object.
z{}.{}
r*   r-   z{0}{1} {2}
r   z{0}{1}:
c              3   D   #    U  H  nS R                  U5      v   M     g7f)z  - {0}
N)r%   ).0r5   s     r   	<genexpr>*_GetDeletionRiskMessage.<locals>.<genexpr>   s     FgF[''//gs    )r6   r%   lenjoin)r   risk_messagereasons_prefixadd_new_liner2   messages         r   _GetDeletionRiskMessagerC      s}     $N3'	>>,EE"EE\Q  wqzJJ|<'	RWWFgFFF'	.r!   c                     [         R                  " U 5      nSR                  X5      nUR                  USSUS9nU H  nU(       d  Us  $ U" U5      (       d  M  Us  $    g)a  Returns the first insight fetched by the recommender API.

Args:
  release_track: Release track of the recommender.
  project_id: Project ID.
  insight_type: String insight type.
  request_filter: Optional string filter for the recommender.
  matcher: Matcher for the insight object. None means match all.

Returns:
  Insight object returned by the recommender API. Returns 'None' if no
  matching insights were found. Returns the first insight object that matches
  the matcher. If no matcher, returns the first insight object fetched.
z.projects/{0}/locations/global/insightTypes/{1}d   N)	page_sizelimitrequest_filter)r   CreateClientr%   List)	release_track
project_idinsight_typerH   matcherclientparent_nameresultrs	            r   _GetRiskInsightrS      sl    " .&AII+ ;;S^  & ahqzzh	 
 
r!   c                 0    [         R                  " SU 5      $ )zReturns true if email is used as a default App Engine Service Account.

Args:
  email: Service Account email.

Returns:
  Returns true if the given email is default App Engine Service Account.
  Returns false otherwise.
z8^([\w:.-]+)@appspot(\.[^.]+\.iam)?\.gserviceaccount\.com)research)emails    r   !_IsDefaultAppEngineServiceAccountrX      s     
A5
 r!   c                     U SR                  U5      :X  a  gU SR                  U5      :X  a  g[        R                  " SU 5      $ )a  Returns true if email is used as a default Compute Engine Service Account.

Args:
  email: Service Account email.
  project_number: Project number.

Returns:
  Returns true if the given email is a default Compue Engine Service Account.
  Returns false otherwise.
z!{0}@developer.gserviceaccount.comTz{0}@project.gserviceaccount.comz>^[0-9]+-compute@developer(\.[^.]+\.iam)?\.gserviceaccount\.com)r%   rU   rV   )rW   project_numbers     r   %_IsDefaultComputeEngineServiceAccountr[     sH     188HH
/66~FF	G
 r!   c                 F   / nU R                   R                   GH  nUR                  S:X  d  M  UR                  R                  R
                   H  nUR                  S:X  d  M  UR                  R                  R
                   H  nUR                  S:X  d  M  UR                  R                  R
                   HW  nUR                  S:X  d  M  UR                  R                  R                   H  nUR                  UR                  5        M      MY     M     M     GM     U$ )zReturns minimal roles extracted from the IAM policy binding insight.

Args:
  gcloud_insight: Insight returned by the recommender API.

Returns: A list of strings. Empty if no minimal roles were found.
r   r   r   minimalRoles)
r   r   r   r   r   r   r.   r/   r1   r   )r   minimal_rolesr   r   r   r   r   s          r   _GetPolicyBindingMinimalRolesr_   "  s     -+33HH&("((55@@!55M!77''22auu..77//::%99.#kk55==d!(():):; > ; 3 A I 
r!   c                     U (       a6  [         R                  [        U 5      S::  a  SOSSR                  U 5      5      $ [        $ )zReturns advice for policy binding deletion.

Args:
  minimal_roles: A string list of minimal recommended roles.

Returns: A string advice on safe deletion.
r-   r*   sz, )_POLICY_BINDING_REPLACE_ADVICEr%   r=   r>   _POLICY_BINDING_DELETE_ADVICE)r^   s    r   _GetPolicyBindingDeletionAdvicerd   8  s>     )00- A%3		-0H  )(r!   c           	          [        X[        5      nU(       a7  SR                  [        [	        U[
        [        S9[        [        U5      /5      $ [        $ )a-  Returns a risk assesment message for project deletion.

Args:
  release_track: Release track of the recommender.
  project_id: Project ID.

Returns:
  String message prompt to be displayed for project deletion.
  If the project deletion is high risk, the message includes the
  Active Assist warning.
r8   )r   r?   r@   )	rS   _PROJECT_INSIGHT_TYPEr>   _PROJECT_WARNING_MESSAGErC   _PROJECT_RISK_MESSAGE_PROJECT_REASONS_PREFIX_PROJECT_ADVICEr(   )rK   rL   risk_insights      r   GetProjectDeletionRiskrl   H  sX     !!6, 99 '.2	

 	%	 	 	 
"!r!   c                 H   [         R                  " U5      n[        U5      (       a  [        $ [	        X#5      (       a  [
        $ SR                  X25      n[        X[        US9nU(       a4  SR                  [        [        U[        5      [        [        U5      /5      $ [        $ )a3  Returns a risk assesment message for service account deletion.

Args:
  release_track: Release track of the recommender.
  project_id: String project ID.
  service_account: Service Account email ID.

Returns:
  String Active Assist risk warning message to be displayed in
  service account deletion prompt.
zFtargetResources: //iam.googleapis.com/projects/{0}/serviceAccounts/{1})rH   r8   )project_utilGetProjectNumberrX   %_SA_DELETE_APP_ENGINE_WARNING_MESSAGEr[   )_SA_DELETE_COMPUTE_ENGINE_WARNING_MESSAGEr%   rS   _SA_INSIGHT_TYPEr>   _SA_WARNING_MESSAGErC   _SA_RISK_MESSAGE
_SA_ADVICEr(   )rK   rL   service_accountrZ   target_filterrk   s         r   GetServiceAccountDeletionRiskrx   g  s      00<.&7700*?KK44N
F>+  !!1-, 99.>?%	   
r!   c                 |   X"R                  S5      S-   S n[        X#5      n[        U U[        US9nU(       ap  SR	                  [        U[        R	                  U5      SS9[        [        U5      5      5      nSR                  [        R	                  U5      U[        U5      /5      $ [        R	                  U5      $ )	a  Returns a risk assesment message for IAM policy binding deletion.

Args:
  release_track: Release track of the recommender.
  project_id: String project ID.
  member: IAM policy binding member.
  member_role: IAM policy binding member role.

Returns:
  String Active Assist risk warning message to be displayed in IAM policy
  binding deletion prompt.
  If no risk exists, then returns 'None'.
:r-   N)rN   z{} {}F)rA   r8   )findr#   rS   _POLICY_BINDING_INSIGHT_TYPEr%   rC   #_POLICY_BINDING_DELETE_RISK_MESSAGErd   r_   r>   &_POLICY_BINDING_DELETE_WARNING_MESSAGEr(   )rK   rL   r   member_rolepolicy_matcherrk   r?   s          r   GetIamPolicyBindingDeletionRiskr     s    $ ;;s#a'*+&.vC. "	, >>/66{C	

 	(),7	
	L 99.55kB%   
0	6	6{	CCr!   )r*   T)NN))__doc__
__future__r   r   r   rU   "googlecloudsdk.api_lib.recommenderr   #googlecloudsdk.command_lib.projectsr   rn   rg   rh   ri   rj   rp   rq   rs   rt   ru   r~   r}   rc   rb   rf   rr   r|   r&   r0   r#   r(   r6   rC   rS   rX   r[   r_   rd   rl   rx   r   r"   r!   r   <module>r      s   1 &  ' 	 6 D	 0 
 O  I 
2 &E *   O
 / '
 $ : 
 K @ D  <   BD CG4 KO@(,) ">"J,Dr!   