
    ;X                     x   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SKJ
r
  SSK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\R4                  5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r " S S\5      r g)z"All the BigQuery CLI IAM commands.    )absolute_import)division)print_functionN)Optional)app)flags)client_connection)client_dataset)client_reservation)client_routine)client_table)utils)bigquery_command)bq_cached_client)bq_id_utilsc                   ^   ^  \ rS rSrSrS\S\R                  4U 4S jjrS r	S r
S rS	rU =r$ )
_IamPolicyCmd!   zCommon superclass for commands that interact with BQ's IAM meta API.

Provides common flags, identifier decoding logic, and GetIamPolicy and
SetIamPolicy logic.
namefvc                 B  > [         [        U ]  X5        SU l        [        R
                  " SSSU-  SUS9  [        R
                  " SSSU-  SUS9  [        R
                  " S	SS
U-  US9  [        R
                  " SSSU-  US9  [        R
                  " SSSU-  US9  g)zInitialize.

Args:
  name: the command name string to bind to this handler class.
  fv: the FlagValues flag-registry object.
  verb: the verb string (e.g. 'Set', 'Get', 'Add binding to', ...) to print
    in various descriptions.
Fdatasetz7%s IAM policy for dataset described by this identifier.d)
short_nameflag_valuestablez5%s IAM policy for table described by this identifier.t
connectionz:%s IAM policy for connection described by this identifier.r   routinez7%s IAM policy for routine described by this identifier.reservationz;%s IAM policy for reservation described by this identifier.N)superr   __init__surface_in_shellr   DEFINE_booleanselfr   r   verb	__class__s       $platform/bq/frontend/commands_iam.pyr#   _IamPolicyCmd.__init__(   s     
-'1 "D	ADH 
?$F 
DtK	 
ADH	 
EL	    c           	      ^   [         R                  " U R                  U R                  U R                  U R
                  U R                  5      (       a  [        R                  " S5      eU(       d%  [        R                  " SU R                  < S35      eU R                  (       a  [        R                  " XS9nU$ U R                  (       a  [        R                  " XS9nU$ U R                  (       a0  [        R                  " UU[        R                  R                   S9nU$ U R
                  (       a  [        R"                  " XS9nU$ U R                  (       a0  [        R$                  " UU[        R                  R                   S9nU$ [        R&                  " XS9n[(        R*                  " U[(        R,                  R.                  [(        R,                  R0                  [(        R,                  R2                  [(        R,                  R4                  4SU< SU R                  < S3SS	9  U$ )
NzOCannot specify more than one of -d, -t, --routine, --connection, --reservation.zMust provide an identifier for .)id_fallbacks
identifier)r/   r0   default_locationzInvalid identifier "z" for T)is_usage_error)frontend_utilsValidateAtMostOneSelectedr   r   r   r    r!   r   
UsageError_command_namebq_client_utilsGetTableReferenceGetDatasetReferenceGetConnectionReferencebq_flagsLOCATIONvalueGetRoutineReferenceGetReservationReferenceGetReferencer   	typecheckApiClientHelperDatasetReferenceTableReferenceRoutineReferenceReservationReference)r'   clientr0   	references       r*   GetReferenceFromIdentifier(_IamPolicyCmd.GetReferenceFromIdentifierZ   s   //  NN  NN262D2D
F  vv!33iL G 
!55iD ? 
!88#,,22i< 3 
!55i0 + 
		!99#,,22i(  "..i 
))::))88))::))>>	 0:4;M;M
N
 r,   c                 <   [        U[        R                  R                  5      (       a#  [        R
                  " UR                  5       US9$ [        U[        R                  R                  5      (       a#  [        R                  " UR                  5       US9$ [        U[        R                  R                  5      (       a#  [        R                  " UR                  5       US9$ [        U[        R                  R                  5      (       a#  [        R                   " UR                  5       US9$ [        U[        R                  R"                  5      (       a#  [$        R&                  " UR)                  5       US9$ [+        SR-                  [/        U5      S95      e)aM  Get the IAM policy for a table, dataset, routine or reservation.

Args:
  reference: A DatasetReference, TableReference, ConnectionReference,
    RoutineReference, or ReservationReference.

Returns:
  The policy object, composed of dictionaries, lists, and primitive types.

Raises:
  RuntimeError: reference isn't an expected type.
)iampolicy_clientrH   )	apiclientrH   )rG   rH   #Unexpected reference type: {r_type}r_type)
isinstancer   rB   rD   r   get_table_iam_policyGetIAMPolicyApiClientrC   r
   GetDatasetIAMPolicyConnectionReferencer	   GetConnectionIAMPolicyGetConnectionV1ApiClientrE   r   GetRoutineIAMPolicyrF   r   GetReservationIAMPolicyGetReservationApiClientRuntimeErrorformattype)r'   rG   rH   s      r*   GetPolicyForReference#_IamPolicyCmd.GetPolicyForReference   sY    )[88GGHH..!779Y  
I{::KK	L	L//002i  
I{::NN	O	O55002i  
I{::KK	L	L//002i  
;..CC
 
  77224	  -44DO4L r,   c                 F   [        U[        R                  R                  5      (       a$  [        R
                  " UR                  5       UUS9$ [        U[        R                  R                  5      (       a$  [        R                  " UR                  5       UUS9$ [        U[        R                  R                  5      (       a$  [        R                  " UR                  5       UUS9$ [        U[        R                  R                  5      (       a$  [        R                   " UR                  5       UUS9$ [        U[        R                  R"                  5      (       a$  [$        R&                  " UR)                  5       UUS9$ [+        SR-                  [/        U5      S95      e)a\  Set the IAM policy for a table, dataset, connection, routine, or reservation.

Args:
  reference: A DatasetReference, TableReference, ConnectionReference,
    RoutineReference, or ReservationReference.
  policy: The policy object, composed of dictionaries, lists, and primitive
    types.

Raises:
  RuntimeError: reference isn't an expected type.
)rL   rH   policy)rM   rH   ra   )rG   rH   ra   rN   rO   )rQ   r   rB   rD   r   set_table_iam_policyrS   rC   r
   SetDatasetIAMPolicyrU   r	   SetConnectionIAMPolicyrW   rE   r   SetRoutineIAMPolicyrF   r   SetReservationIAMPolicyrZ   r[   r\   r]   )r'   rG   rH   ra   s       r*   SetPolicyForReference#_IamPolicyCmd.SetPolicyForReference   sm    )[88GGHH..!779 
 
I{::KK	L	L//002 
 
I{::NN	O	O55002 
 
I{::KK	L	L//002 
 
;..CC
 
  77224 
 -44DO4L r,   )r$   )__name__
__module____qualname____firstlineno____doc__strr   
FlagValuesr#   rI   r^   rg   __static_attributes____classcell__r)   s   @r*   r   r   !   s8    .3 .E$4$4 .d;z%N. .r,   r   c                   d   ^  \ rS rSrSrS\S\R                  4U 4S jjrS\S\	\
   4S jrS	rU =r$ )
GetIamPolicy   zHget-iam-policy [(-d|-t|-connection|--reservation|-routine)] <identifier>r   r   c                 H   > [         TU ]  XS5        U R                  U5        g )NGetr"   r#   _ProcessCommandRcr'   r   r   r)   s      r*   r#   GetIamPolicy.__init__        	GTu%2r,   r0   returnc                     [         R                  R                  5       nU R                  X!5      nU R	                  X#5      n[
        R                  " USS9  g)aA  Get the IAM policy for a resource.

Gets the IAM policy for a dataset, table, routine, connection, or
reservation resource, and prints it to stdout. The policy is in JSON format.

Usage:
get-iam-policy <identifier>

Examples:
  bq get-iam-policy ds.table1
  bq get-iam-policy --project_id=proj -t ds.table1
  bq get-iam-policy proj:ds.table1
  bq get-iam-policy --reservation proj:ds.reservation1

Arguments:
  identifier: The identifier of the resource. Presently only table, view,
    connection, and reservation resources are fully supported. (Last
    updated: 2025-08-22)

prettyjsondefault_formatN)r   Clientrw   rI   r^   bq_utilsPrintFormattedJsonObject)r'   r0   rG   rH   result_policys        r*   RunWithArgsGetIamPolicy.RunWithArgs   sK    ( $$((*F//CI..vAM%%lr,    ri   rj   rk   rl   usagern   r   ro   r#   r   intr   rp   rq   rr   s   @r*   rt   rt      s=    
X%3 E$4$4 C HSM  r,   rt   c                   h   ^  \ rS rSrSrS\S\R                  4U 4S jjrS\S\S\	\
   4S	 jrS
rU =r$ )SetIamPolicyi  zSset-iam-policy [(-d|-t|-connection|--reservation|-routine)] <identifier> <filename>r   r   c                 H   > [         TU ]  XS5        U R                  U5        g )NSetrx   rz   s      r*   r#   SetIamPolicy.__init__  r|   r,   r0   filenamer}   c                 (   [         R                  R                  5       nU R                  X15      n[	        US5       n[
        R                  " U5      nU R                  X4U5      n[        R                  " USS9  SSS5        g! , (       d  f       g= f)a  Set the IAM policy for a resource.

Sets the IAM policy for a dataset, table, routine, connection, or
reservation resource. After setting the policy, the new policy is printed to
stdout. Policies are in JSON format.

If the 'etag' field is present in the policy, it must match the value in the
current policy, which can be obtained with 'bq get-iam-policy'. Otherwise
this command will fail. This feature allows users to prevent concurrent
updates.

Usage:
set-iam-policy <identifier> <filename>

Examples:
  bq set-iam-policy ds.table1 /tmp/policy.json
  bq set-iam-policy --project_id=proj -t ds.table1 /tmp/policy.json
  bq set-iam-policy proj:ds.table1 /tmp/policy.json
  bq set-iam-policy --reservation proj:ds.reservation1 /tmp/policy.json

Arguments:
  identifier: The identifier of the resource. Presently only table, view,
    routine, connection, and reservation resources are fully supported.
    (Last updated: 2025-09-05)
  filename: The name of a file containing the policy in JSON format.
rr   r   N)
r   r   rw   rI   openjsonloadrg   r   r   )r'   r0   r   rG   rH   file_objra   r   s           r*   r   SetIamPolicy.RunWithArgs  ss    6 $$((*F//CI	h	yy"f00FKm''
 
		s   >B
Br   r   rr   s   @r*   r   r     sD    
c%3 E$4$4 "C "3 "8C= " "r,   r   c                   P   ^  \ rS rSrSrS\S\R                  S\4U 4S jjrSr	U =r
$ )_IamPolicyBindingCmdi>  zCommon superclass for AddIamPolicyBinding and RemoveIamPolicyBinding.

Provides the flags that are common to both commands, and also inherits
flags and logic from the _IamPolicyCmd class.
r   r   r(   c                    > [         [        U ]  XU5        [        R                  " SS SUS9  [        R                  " SS SUS9  [        R
                  " SUS9  [        R
                  " SUS9  g )Nmembera>  The member part of the IAM policy binding. Acceptable values include "user:<email>", "group:<email>", "serviceAccount:<email>", "allAuthenticatedUsers" and "allUsers".

"allUsers" is a special value that represents every user. "allAuthenticatedUsers" is a special value that represents every user that is authenticated with a Google account or a service account.

Examples:
  "user:myaccount@gmail.com"
  "group:mygroup@example-company.com"
  "serviceAccount:myserviceaccount@sub.example-company.com"
  "domain:sub.example-company.com"
  "allUsers"
  "allAuthenticatedUsers"r   rolea&  The role part of the IAM policy binding.

Examples:

A predefined (built-in) BigQuery role:
  "roles/bigquery.dataViewer"

A custom role defined in a project:
  "projects/my-project/roles/MyCustomRole"

A custom role defined in an organization:
  "organizations/111111111111/roles/MyCustomRole")r"   r   r#   r   DEFINE_stringmark_flag_as_requiredr&   s       r*   r#   _IamPolicyBindingCmd.__init__E  su    	
.t>	' #& 
	> " 
b9	B7r,   r   )ri   rj   rk   rl   rm   rn   r   ro   r#   rp   rq   rr   s   @r*   r   r   >  s-    '83 '8E$4$4 '8C '8 '8r,   r   c                   t   ^  \ rS rSrSrS\S\R                  4U 4S jjrS\S\	\
   4S jr\S	 5       rS
rU =r$ )AddIamPolicyBindingiq  zMadd-iam-policy-binding --member=<member> --role=<role> [(-d|-t)] <identifier>r   r   c                 L   > [         [        U ]  XSS9  U R                  U5        g )NzAdd binding tor(   )r"   r   r#   ry   rz   s      r*   r#   AddIamPolicyBinding.__init__w  s'    	
t-d=M-N2r,   r0   r}   c           	         [         R                  R                  5       nU R                  X!5      nU R	                  X#5      nSU Vs/ s H  oUR                  5       PM     sn;  a  [        S5      eU R                  X@R                  U R                  5        U R                  X#U5      n[        SR                  U R                  U R                  UR                  US95        [        R                  " USS9  gs  snf )a0  Add a binding to a BigQuery resource's policy in IAM.

Usage:
  add-iam-policy-binding --member=<member> --role=<role> <identifier>

One binding consists of a member and a role, which are specified with
(required) flags.

Examples:

  bq add-iam-policy-binding \
    --member='user:myaccount@gmail.com' \
    --role='roles/bigquery.dataViewer' \
    table1

  bq add-iam-policy-binding \
    --member='serviceAccount:my.service.account@my-domain.com' \
    --role='roles/bigquery.dataEditor' \
    project1:dataset1.table1

  bq add-iam-policy-binding \
   --member='allAuthenticatedUsers' \
   --role='roles/bigquery.dataViewer' \
   --project_id=proj -t ds.table1

Arguments:
  identifier: The identifier of the resource. Presently only table and view
    resources are fully supported. (Last updated: 2020-08-03)
etagPolicy doesn't have an 'etag' field. This is unexpected. The etag is required to prevent unexpected results from concurrent edits.zhSuccessfully added member '{member}' to role '{role}' in IAM policy for {resource_type} '{identifier}':
r   r   resource_typer0   r   r   N)r   r   rw   rI   r^   lower
ValueErrorAddBindingToPolicyr   r   rg   printr\   typenamer   r   r'   r0   rG   rH   ra   keyr   s          r*   r   AddIamPolicyBinding.RunWithArgs{  s    < $$((*F//CI'':FV4VciikV44M  	FKK;..v&IM	;
&;;#,, 	  
	
 %%l% 5   C7c                    U R                  SS5      S:  a(  [        SR                  U R                  SS5      S95      eU R                  S/ 5      n[	        U[
        5      (       d!  [        SR                  [        U5      S95      eU HP  n[	        U[        5      (       d!  [        S	R                  [        U5      S95      eUR                  S
5      U:X  d  MP    O   S
U0nUR                  U5        UR                  S/ 5      n[	        U[
        5      (       d!  [        SR                  [        U5      S95      eX;  a  UR                  U5        U $ )a  Add a binding to an IAM policy.

Args:
  policy: The policy object, composed of dictionaries, lists, and primitive
    types. This object will be modified, and also returned for convenience.
  member: The string to insert into the 'members' array of the binding.
  role: The role string of the binding to remove.

Returns:
  The same object referenced by the policy arg, after adding the binding.
version   >Only policy versions up to 1 are supported. version: {version}Noner   bindingsNPolicy field 'bindings' does not have an array-type value. 'bindings': {value}r=   ]At least one element of the policy's 'bindings' array is not an object type. element: {value}r   membersTPolicy binding field 'members' does not have an array-type value. 'members': {value})	getr   r\   
setdefaultrQ   listreprdictappend)ra   r   r   r   bindingr   s         r*   r   &AddIamPolicyBinding.AddBindingToPolicy  sC    zz)Q!#NF6::i8F9    R0Hh%%$FhF(	  &&3f4=f)	
 	
 
V		$  goog  B/Ggt$$*FgF'	  nnVMr,   r   )ri   rj   rk   rl   r   rn   r   ro   r#   r   r   r   staticmethodr   rp   rq   rr   s   @r*   r   r   q  sR     
3 E$4$4 5C 5HSM 5n : :r,   r   c                   t   ^  \ rS rSrSrS\S\R                  4U 4S jjrS\S\	\
   4S jr\S	 5       rS
rU =r$ )RemoveIamPolicyBindingi  zPremove-iam-policy-binding --member=<member> --role=<role> [(-d|-t)] <identifier>r   r   c                 L   > [         [        U ]  XSS9  U R                  U5        g )NzRemove binding fromr   )r"   r   r#   ry   rz   s      r*   r#   RemoveIamPolicyBinding.__init__  s.    	
 $0, 1  	2r,   r0   r}   c           	         [         R                  R                  5       nU R                  X!5      nU R	                  X#5      nSU Vs/ s H  oUR                  5       PM     sn;  a  [        S5      eU R                  X@R                  U R                  5        U R                  X#U5      n[        SR                  U R                  U R                  UR                  US95        [        R                  " USS9  gs  snf )aA  Remove a binding from a BigQuery resource's policy in IAM.

Usage:
  remove-iam-policy-binding --member=<member> --role=<role> <identifier>

One binding consists of a member and a role, which are specified with
(required) flags.

Examples:

  bq remove-iam-policy-binding \
    --member='user:myaccount@gmail.com' \
    --role='roles/bigquery.dataViewer' \
    table1

  bq remove-iam-policy-binding \
    --member='serviceAccount:my.service.account@my-domain.com' \
    --role='roles/bigquery.dataEditor' \
    project1:dataset1.table1

  bq remove-iam-policy-binding \
   --member='allAuthenticatedUsers' \
   --role='roles/bigquery.dataViewer' \
   --project_id=proj -t ds.table1

Arguments:
  identifier: The identifier of the resource. Presently only table and view
    resources are fully supported. (Last updated: 2020-08-03)
r   r   zlSuccessfully removed member '{member}' from role '{role}' in IAM policy for {resource_type} '{identifier}':
r   r   r   N)r   r   rw   rI   r^   r   r   RemoveBindingFromPolicyr   r   rg   r   r\   r   r   r   r   s          r*   r   "RemoveIamPolicyBinding.RunWithArgs  s    < $$((*F//CI'':FV4VciikV44M  	  dii@..v&IM	;
&;;#,, 	  
	
 %%l% 5r   c           	      8   U R                  SS5      S:  a(  [        SR                  U R                  SS5      S95      eU R                  S/ 5      n[        U[        5      (       d!  [        SR                  [        U5      S95      eU H  n[        U[        5      (       d!  [        S	R                  [        U5      S95      eUR                  S
5      U:X  d  MP  UR                  S/ 5      n[        U[        5      (       d!  [        SR                  [        U5      S95      e[        U5       H@  u  pgXq:X  d  M  XV	 U Vs/ s H  oR                  S/ 5      (       d  M  UPM     nnX0S'   U s  s  $    M     [        R                  " SR                  XS95      es  snf )a  Remove a binding from an IAM policy.

Will remove the member from the binding, and remove the entire binding if
its members array is empty.

Args:
  policy: The policy object, composed of dictionaries, lists, and primitive
    types. This object will be modified, and also returned for convenience.
  member: The string to remove from the 'members' array of the binding.
  role: The role string of the binding to remove.

Returns:
  The same object referenced by the policy arg, after adding the binding.
r   r   r   r   r   r   r   r   r   r   r   r   z7No binding found for member '{member}' in role '{role}')r   r   )
r   r   r\   rQ   r   r   r   	enumerater   r5   )	ra   r   r   r   r   r   jmember_jbs	            r*   r   .RemoveIamPolicyBinding.RemoveBindingFromPolicy3  s   $ zz)Q!#NF6::i8F9  zz*b)Hh%%$FhF(	  &&3f4=f)	
 	
 
V		$++i,'4((.T']+	  %W-KA
 $,D8auuY/C8HD!):M .# 4 ..AHH 	I 	
  Es   >FFr   )ri   rj   rk   rl   r   rn   r   ro   r#   r   r   r   r   r   rp   rq   rr   s   @r*   r   r     sR     
3 E$4$4 5C 5HSM 5n ? ?r,   r   )!rm   
__future__r   r   r   r   typingr   abslr   r   r;   r   clientsr	   r
   r   r   r   r   r7   frontendr   r   r3   r   BigqueryCmdr   rt   r   r   r   r   r   r,   r*   <module>r      s    ( '  %       % " & "   , % % , K$00 K\ =  F)= )X.8= .8f|. |~C1 Cr,   