
    G!                        d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlm	Z	m
Z
 ddlmZ ddlmZ ddlZd	e	ee	ee
e   f   f   d
e
e	eef      dede	ee
e	eef      f   fdZde
e   de	eef   fdZde	eef   fdZde	eef   dee	eef   ffdZdedefdZdedefdZde	eef   dedededef
dZdede
e   fdZde
e   dede
e	eef      fdZdede
e	eef      fdZy) zLibrary for fetching TF Files.    )absolute_import)division)unicode_literalsN)DictList)run_subprocess)filesiam_bindingstfstate_json_listresource_namereturnc           	      >   i }| j                         D ]  \  }}|D ]{  }d|v r8|d   D ]0  }t        ||||      }|s||vrg ||<   ||   j                  |       2 d|v sD|d   D ]0  }t        ||||      }|s||vrg ||<   ||   j                  |       2 } |c S  y)a1  Gets the TFState information for the given IAM bindings.

  Args:
    iam_bindings: IAM bindings for the resource.
    tfstate_json_list: List of TFState files.
    resource_name: Resource name for which the finding was generated.

  Returns:
    List of TFState information for the given IAM bindings.
  ADDREMOVEN)itemsfetch_relevant_modulesappend)	r
   r   r   tfstate_informationmemberbindingtfstate_jsonroleresource_datas	            ;lib/googlecloudsdk/api_lib/scc/iac_remediation/terraform.py"get_tfstate_information_per_memberr      s     :<%++-ofg)	'	END0M4- 00,.!&)'..}= # 
W	H%D0M4- 00,.!&)'..}= & *& ) .    tf_files_pathsc                 v    t        t        t        f          }| D ]  }t        j                  |      }|||<    |S )zReads the original files content.

  Args:
    tf_files_paths: List of TF files paths.

  Returns:
    Dict of file path and file content.
  )dictstrr	   ReadFileContents)r   original_tf_files	file_pathoriginal_file_contents       r   read_original_files_contentr%   F   sC     38n&!i!229=#8i  " 
r   response_dictc                 `    | j                         D ]  \  }}t        j                  ||      } y)z{Updates the TF files with the response dict.

  Args:
    response_dict: Response dict containing the updated TF files.

  N)r   r	   WriteFileContents)r&   r#   	file_data_s       r   update_tf_filesr+   X   s.     ,113i	95A 4r   c                 p   t        t        t        f          }| j                         D ]l  \  }}t        j                  |      }|||<   	 t        j
                  ||      }ddd|g}t        j                  |dd       t        j                  |      | |<   n ddg}	 t        j                  |dd      }t        |       t        j                  d	|d
   t        j                        rd| fS y# t        $ r}t        |       d|fcY d}~c S d}~ww xY w# t        $ r}t        |       d|fcY d}~S d}~ww xY w)a"  Validates the TFState information for the given IAM bindings.

  Args:
    response_dict: response dict containing the updated TF files.

  Returns:
    True if the response is valid, False otherwise.
    updated_response_dict: Updated response dict containing the original TF
    files.
  	terraformfmtz-write=true   F)timeout_secshow_stderrNvalidateSuccessr   T)FN)r   r    r   r	   r!   r(   r   GetOutputLines	Exceptionr+   research
IGNORECASE)	r&   r"   r#   r)   r$   r*   cmdevalidate_outputs	            r   validate_tf_filesr<   e   s6    38n&+113i!229=#8i 

!
!)Y
7a%	:c##CRUK!&!7!7	!BmI 4 
j!#$33O #$ii	?1-r}}=	  '(AXo 
 %&!8Os=   	AC,D ,	D5DDD	D5D0*D50D5dir_pathc                     	 t        j                  |        ddg}t        j                  |d       	 g d}t        j                  |d      }|S # t        $ r
}Y d}~yd}~ww xY w# t        $ r
}Y d}~yd}~ww xY w)zFetches the TFState json for the given directory.

  Args:
    dir_path: The path of the directory to fetch the TFState files from.

  Returns:
    The json of the TFState file or None if there is an error.
  r-   init
   )r0   N )r-   showz-json)oschdirr   r4   r5   )r=   r9   r*   r   s       r   fetch_tfstate_json_from_dirrE      sz    HHX
C!!#26
(C!00"EL 
 
 
 
 s"   0A A& 	A#A#&	A94A9r#   c                 Z    t        j                  |       }t        j                  |      }|S )zFetches the TFState json for the given tfstate file path.

  Args:
    file_path: The path of the file to fetch the TFState json from.

  Returns:
    The json of the TFState files.
  )r	   r!   hcl2loads)r#   filer   s      r   fetch_tfstate_json_from_filerJ      s(     
				*$D!,	r   r   	role_namemember_namec                     d}d| vsd| d   vs
d| d   d   vr|S | d   d   d   D ]G  }d|v sd|d   v sd|d   v sd|d   v s |d   d   |k(  s,|d   d   |k(  s8|d   d   |k(  sD|} |S  |S )z:Fetches the relevant modules from the given TFState files.rA   valuesroot_module	resourcesr   r   
project_id )r   r   rK   rL   r   resources         r   r   r      s    
 -l"	l84	4	L2=A	Ax(7DhH**hx((HX..Xx(K7Xv&)3X|,=m	 E 
r   root_dirc                 &   g }t        j                  | g      }|r|j                         }t        j                  |      D ]  }t        j
                  j                  ||      }t        j
                  j                  |      r$|j                  d      rT|j                  |       ft        j
                  j                  |      s|j                  d      s$|j                  d      s|j                  d      r|j                  |        |r|S )zFinds all the TF files in the given directory.

  Args:
    root_dir: The path of the directory to find the TF files in.

  Returns:
    A list of the TF files paths in the given directory.
  .z.tfz.tfvars)collectionsdequepopleftrC   listdirpathjoinisdir
startswithr   isfileendswith)rT   tf_filesqueuecurrent_diritem	item_paths         r   find_tf_filesrf      s     (


XJ
'%--/K

;''',,{D1i	y	!s#
,,y
!77>>)$


U
#y'9'9)'D&&s+	" ( 	 
/r   tfstate_file_pathsc                 f    g }| r#| D ]  }|j                  t        |              |S t        |      S )zFetches the TFState list for the given TFState file paths.

  Args:
    tfstate_file_paths: List of TFState file paths.
    root_dir: The path of the root directory.

  Returns:
    List of TFState json.
  )r   rJ   find_tfstate_jsons)rg   rT   r   tfstate_file_paths       r   fetch_tfstate_listrk      sD     /
&'8
9 0 
 h''r   c                    g }t        j                  | g      }|r|j                         }|j                  t	        |             t        j                  |      D ]e  }|j                  d      rt
        j                  j                  ||      }t
        j                  j                  |      sU|j                  |       g |r|S )zFinds the TFState jsons in the given directory.

  Args:
    dir_path: The path of the directory to find the TFState jsons in.

  Returns:
    List of TFState jsons.
  rV   )rW   rX   rY   r   rE   rC   rZ   r^   r[   r\   r]   )r=   tfstate_jsonsrb   rc   rd   re   s         r   ri   ri      s     -


XJ
'%--/K4[AB

;'__S!GGLLd3	77==#
,,y
!	 ( 	 
r   )__doc__
__future__r   r   r   rW   rC   r6   typingr   r   googlecloudsdk.command_lib.coder   googlecloudsdk.core.utilr	   rG   r    r   r%   r+   boolr<   rE   rJ   r   rf   rk   ri   rR   r   r   <module>rt      s   % &  '  	 	  : * $sDd3i001$DcN+$ $ 
#tDcN#
#$	$NIcN$
6S>
6$S>$
DcN$N# # .C C sCx.#&58 	6C DI 4S	 
$sCx.0	$sCx.r   