
    =                        S r SSKJr  SSKJr  SSKJr  SSKrSSKrSSKJr	  SSK
r
SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK J!r"  SSK#J$r$  SSK%J&r&  \
R                  " SSSSS.5      r'Sr(Sr)Sr*\(\)\*4r+Sr,Sr-\
R                  " \*\*\)\(S.5      r.S\*4S\)4S\(4/r/S r0S! r1S" r2S# r3S$ r4S1S% jr5S& r6S' r7\Rp                  " SS(9  S2S) j5       r9S* r:S+ r; S3S, jr<S4S- jr=S1S. jr>S/ r?S0 r@g)5zFUtility for interacting with `artifacts docker upgrade` command group.    )absolute_import)division)unicode_literalsN)
exceptions)ResourceExhausted)client_util)organizations)projects_api)folders)storage_api)storage_util)apis)requests)util)log)console_attr zus.zasia.zeu.)zgcr.ioz	us.gcr.iozasia.gcr.ioz	eu.gcr.ioz roles/artifactregistry.repoAdminzroles/artifactregistry.writerzroles/artifactregistry.reader)zstorage.objects.getzstorage.objects.listzstorage.objects.createzstorage.objects.delete)/artifactregistry.repositories.downloadArtifacts-artifactregistry.repositories.uploadArtifacts-artifactregistry.repositories.deleteArtifactsr   r   r   z:Too many IAM policies. Analysis cannot be fully completed.c                 ~    U R                  SS5      n[        U5      S:X  a  SR                  US   US   5      $ U S-   $ )N:      z{0}.{1}.a.appspot.comr   z.appspot.com)splitlenformat)projectchunkss     8lib/googlecloudsdk/command_lib/artifacts/upgrade_util.pybucket_suffixr!   X   sD    ==a &[A"))&)VAY??	>	!!    c                 L    [         U    n[        U5      nSR                  X#5      $ )Nz)//storage.googleapis.com/{0}artifacts.{1})_DOMAIN_TO_BUCKET_PREFIXr!   r   domainr   prefixsuffixs       r    bucket_resource_namer)   `   s'    #F+&!&	4	;	;F	KKr"   c                 :    [         U    n[        U5      nSU SU 3$ )Nzgs://z
artifacts.)r$   r!   r%   s       r    
bucket_urlr+   g   s)    #F+&!&
6(	++r"   c                 $    SR                  U 5      $ )Nz2//cloudresourcemanager.googleapis.com/projects/{0})r   )r   s    r    project_resource_namer-   m   s    	=	D	DW	MMr"   c                 6    [        U USSUS9u  p4[        U5      $ )aC  Generates an AR-equivalent IAM policy for a GCR registry.

Args:
  domain: The domain of the GCR registry.
  project: The project of the GCR registry.
  use_analyze: If true, use AnalyzeIamPolicy to generate the policy

Returns:
  An iam.Policy.

Raises:
  Exception: A problem was encountered while generating the policy.
F)skip_bucketfrom_ar_permissionsuse_analyze)iam_mappolicy_from_map)r&   r   r1   m_s        r    
iam_policyr6   r   s,      

$! 
	r"   c                     [         R                  " [        5      nU R                   H*  nXR                     R                  UR                  5        M,     U$ )zConverts an iam.Policy object to a map of roles to sets of users.

Args:
  policy: An iam.Policy object

Returns:
  A map of roles to sets of users
)collectionsdefaultdictsetbindingsroleupdatemembers)policyrole_to_membersbindings      r    map_from_policyrB      sA      ++C0/gLL!((9 !	r"   c                    [         R                  " 5       n[        5       nU R                  5        H6  u  p4UR	                  UR                  U[        [        U5      5      S95        M8     [        US S9nUR                  US9$ )zConverts a map of roles to sets of users to an iam.Policy object.

Args:
  role_to_members: A map of roles to sets of users

Returns:
  An iam.Policy.
)r<   r>   c                     U R                   $ N)r<   )bs    r    <lambda>!policy_from_map.<locals>.<lambda>   s    AFFr"   )key)r;   )		artifactsGetMessageslistitemsappendBindingtuplesortedPolicy)r@   messagesr;   r<   r>   s        r    r3   r3      s|     ""$(V(&,,.mdOO&/* 	 	
 / H"23(	(	++r"   )maxsizec                    Sn/ nU(       a-  U(       a  [        U5      nO[        X5      n[        XX45      u  pgONU(       a  [        U[        US9u  pgO5U(       a  [        U[
        US9u  pgO[        X5      n	[        U[
        XS9u  pgUc  SU4$ [        R                  " [        5      n
U(       aP  U[        S   S      n[         H4  u  pUR                  Xl   5      nU H  nX   R                  U5        M     M6     X4$ UR                  5        H!  u  p[        U   nX   R                  U5        M#     [        5       n[        R                  " [        5      n[          Hp  nX   nU Vs1 s H  nUR#                  S5      (       a  M  UiM     nnUR%                  U5        U(       d  MK  UR                  U5        UU   R                  U5        Mr     UU4$ s  snf )a  Generates an AR-equivalent IAM mapping for a GCR registry.

Args:
  domain: The domain of the GCR registry.
  project: The project of the GCR registry.
  skip_bucket: If true, get iam policy for project instead of bucket. This can
    be useful when the bucket doesn't exist.
  from_ar_permissions: If true, use AR permissions to generate roles that
    would not need to be added to AR since user already has equivalent access
    for docker commands
  best_effort: If true, lower the scope when encountering auth errors
  use_analyze: If true, use AnalyzeIamPolicy to generate the policy

Returns:
  (map, failures) where map is a map of roles to sets of users and
  failures is a list of scopes that failed

Raises:
  Exception: A problem was encountered while generating the policy.
N)best_effortr   zdeleted:)r-   r)   get_permissions_using_analyzeget_permissions_with_ancestors_AR_PERMISSIONS_PERMISSIONSr+   r8   r9   r:   _AR_PERMISSIONS_TO_ROLESintersectionaddrM   _PERMISSION_TO_ROLEr=   	_AR_ROLES
startswithdifference_update)r&   r   r/   r0   rV   r1   perm_to_membersfailuresresource
gcs_bucketr@   r>   needed_permr<   memberpermupgraded_members	final_mapr4   s                      r    r2   r2      s   : /(&w/h%f6h =.!OX "@
?#ox 
$B\{%
!  0
$B\:%
! >++C0/ 6q9!<=G5$$_%ABg&!!&)  6 $$ ',,.mdt$D  ) /
 U%%c*)d#G "B'Qj)Aq'GB./G$dO7#  
H	 Cs   )GGc                    [         R                  " U S9n/ nSn[        [        UR                  5      5       H9  u  px[        U5      n	 U(       a  [        [        X5      nO[        [        X5      n  O   UR                  (       a  UR                  R                  (       d  [        S UR                  R                    5       5      n
SR#                  U
5      nU(       d  [$        R&                  " U5      eSU 3n[(        R*                  " 5       n[,        R.                  R1                  UR3                  SS5       S	U 35        [4        R6                  " [8        5      nUR                  R:                   H  nUR                  (       d  [$        R&                  " [<        5      eUR>                  R@                  b  U(       d  [$        R&                  " S
5      e[9        5       nUR>                  RB                   H&  n[E        U5      (       a  M  URG                  U5        M(     URH                   H6  nURJ                   H#  nURL                  nUU   RO                  U5        M%     M8     M     X4$ ! [        R                   aB    UR                  U	5        U(       d  e U[        UR                  5      S-
  :X  a  SU4s s  $  GM  f = f)z?Returns a map of permissions to members using AnalyzeIamPolicy.
project_idNr   c              3   8   #    U  H  oR                   v   M     g 7frE   )cause).0errs     r    	<genexpr>0get_permissions_using_analyze.<locals>.<genexpr>*  s     O'N))'Ns   
zVEncountered errors when analyzing IAM policy. This may result in incomplete bindings: zWarning:red z)Conditional IAM binding is not supported.)(crmGetAncestry	enumeratereversedancestorresource_from_ancestoranalyze_iam_policyrY   rZ   apitools_exceptionsHttpForbiddenErrorrN   r   fullyExploredmainAnalysisrL   nonCriticalErrorsjoinar_exceptionsArtifactRegistryErrorr   GetConsoleAttrr   statusPrintColorizer8   r9   r:   analysisResults_ANALYSIS_NOT_FULLY_EXPLORED
iamBinding	conditionr>   is_conveniencer]   accessControlListsaccesses
permissionr=   )r   rd   r0   rV   ancestryrc   analysisnumr{   scopeerrors	error_msgwarning_msgconrb   resultr>   rg   aclaccessrh   s                        r    rW   rW     sG    __0((( (*;*;!<=mc"8,E	%oxG%lHD >$ 
		x'<'<'J'JOx'<'<'N'NOOF		&!I//	::	!!*	-  
%
%
'CJJZ67qFG++C0/%%55f//0LMM"".{//
5  eG##++			kk&	 , ((LL&  $$W- ! )# 6, 
	""[ 11 ooe	H%%&*	*X~ 
+	s   (I++AK Kc                     U R                  S5      =(       d)    U R                  S5      =(       d    U R                  S5      $ )NzprojectOwner:zprojectEditor:zprojectViewer:)r`   )ss    r    r   r   O  s7    ll?# (	
&	'(	
&	'r"   c                 F    [        XU5      u  pE[        XU5      u  pgXeU-   4$ rE   )recursive_get_rolesget_permissions)rm   permissionsre   rV   rolesrc   permsperm_failuress           r    rX   rX   W  s/     (
L/%([I%	=(	((r"   c                    [         R                  " U S9n[        R                  " [        5      nU(       ay  [
        R                  " 5       R                  [        R                  R                  U5      5      R                   H*  nXER                     R                  UR                  5        M,     / n[        UR                   5       GH1  n/ n UR"                  R$                  S:X  a5  [         R                  " [&        R(                  " U 5      5      R                  nOUR"                  R$                  S:X  a5  [*        R                  " UR"                  R,                  5      R                  nO\UR"                  R$                  S:X  aB  [.        R0                  " 5       R                  UR"                  R,                  5      R                  nU H*  nXER                     R                  UR                  5        M,     GM4     XF4$ ! [2        R4                   an    UR7                  UR"                  R$                  S-   UR"                  R,                  -   5        U(       d  e UR"                  R$                  S:X  a  SU4s s  $  GM  f = f)z]Returns a map of roles to members for the given project + ancestors (and bucket if provided).rl   r   folderorganizationzs/N)rw   rx   r8   r9   r:   r   StorageClientGetIamPolicyr   BucketReferenceFromUrlr;   r<   r=   r>   rz   r{   
resourceIdtypeprojects_utilParseProjectr   idr	   Clientr~   r   rN   )	rm   rV   re   r   r@   rA   rc   rd   r;   s	            r    r   r   _  s   __
3(++C0/!!#	l22:::F	G		 	
 ll#**7??;		 (8,,-hH				!	!Y	.##&&z2

( 	 ##x/''(;(;(>(>?HH##~5  "//0C0C0F0FGPP 	 '%,,W__=  .* 
	"" 11 ooh))..58K8K8N8NNO				!	!Y	.X~ 
/	s   D*G??A9J Jc                 V   / n[         R                  " [        5      n[        R                  " SS5      nUR                  5        H  u  pgU Vs/ s H  n[        U5      (       a  M  UPM     nnUR                  US9n	 [        [        R                  " SS5      R                  R                  U	5      R                  5      n
U  H  nX;   d  M
  XL   R                  U5        M     M     XC4$ s  snf ! [        R                   a%  nUR                  U5        U(       d  Ue SnAM  SnAff = f)aq  Returns a map of permissions to members for the given roles.

Args:
  permissions: The permissions to look for. All other permissions are ignored.
  role_map: A map of roles to members.
  best_effort: If true, warn instead of failing on auth errors.

Returns:
  (map, failures) where map is a map of permissions to members and failures
  is a list of roles that failed
iamv1)nameN)r8   r9   r:   r   GetMessagesModulerM   r   IamRolesGetRequestGetClientInstancer   GetincludedPermissionsr~   r   rN   r=   )r   role_maprV   rc   permission_mapiam_messagesr<   r>   r4   requestrole_permissionseps                r    r   r     s    (**3/.''t4,~~'md!;'Q):q'G; --4-8G


 
 
-5W 	
	  ) ! (& 
	!!% < 11 ood	s%   C*%C*=AC//D(D##D(c                 t   [         R                  " 5       nUR                  n[         R                  " 5       n UR	                  UR                  U UUS95      $ ! [        R                   a,  nUR                  S:X  a  [        R                  " S5      ee SnAf[         a    [        R                  " S5      ef = f)a  Calls AnalyzeIamPolicy for the given resource.

Args:
  permissions: for the access selector
  resource: for the resource selector
  scope: for the scope

Returns:
  An CloudassetAnalyzeIamPolicyResponse.
Raises:
  ResourceExhausted: If the request fails due to analyzeIamPolicy quota.
)(analysisQuery_accessSelector_permissions/analysisQuery_resourceSelector_fullResourceNamer   i  zzInsufficient quota for AnalyzeIamPolicy. Use --no-use-analyze-iam to generate IAM policies without using AnalyzeIamPolicy.N)asset	GetClientr   rK   AnalyzeIamPolicy!CloudassetAnalyzeIamPolicyRequestr~   	HttpErrorstatus_coder   r   r   )r   rd   r   clientservicerS   r   s          r    r}   r}     s     ??&II' (##225@<D 	3 	
  
	&	& 
}}//C  
	 

-
-	A s   A B7,'B$B7c                 ~   U R                   R                  S:X  a%  SR                  U R                   R                  5      $ U R                   R                  S:X  a%  SR                  U R                   R                  5      $ U R                   R                  S:X  a%  SR                  U R                   R                  5      $ g)zConverts an ancestor to a resource name.

Args:
  ancestor: an ancestor proto return from GetAncestry

Returns:
  The resource name of the ancestor
r   zorganizations/{0}r   zfolders/{0}r   zprojects/{0}N)r   r   r   r   )r{   s    r    r|   r|     s     /%%h&9&9&<&<==) 3 3 6 677*  !4!4!7!788 +r"   )T)FT)NTrE   )A__doc__
__future__r   r   r   r8   	functoolsapitools.base.pyr   r~   
frozendictgoogle.api_core.exceptionsr    googlecloudsdk.api_lib.artifactsr   googlecloudsdk.api_lib.assetr   r   +googlecloudsdk.api_lib.cloudresourcemanagerr	   r
   rw   'googlecloudsdk.api_lib.resource_managerr   googlecloudsdk.api_lib.storager   r   googlecloudsdk.api_lib.utilr   $googlecloudsdk.command_lib.artifactsr   rJ   #googlecloudsdk.command_lib.projectsr   r   googlecloudsdk.corer   googlecloudsdk.core.consoler   r$   _REPO_ADMIN_WRITER_READERr_   rZ   rY   r^   r[   r   r!   r)   r+   r-   r6   rB   r3   	lru_cacher2   rW   r   rX   r   r   r}   r|    r"   r    <module>r      sb   M &  '   >  8 H = E K ; 6 7 , F E # 4%00	2   1
)
) '7+	 !++"#%)	-   7@4g>4kB  A 
"L,N
4 ,0 T" W #Wt=#@ ;?)"#J""J$N9r"   