
                            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Zddl	m
Z
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ dede
eef   fdZdedefdZde
eef   defdZde
eef   dee
eef      fdZdedefdZy)z,Module for interacting with Terraform files.    )absolute_import)division)unicode_literalsN)DictListAny)const)parsers)run_subprocess)errors)filesroot_dirreturnc                 4   i }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t        j                  |      ||<    |r|S )a  Fetches all the relevant TF files in the given directory recusively and returns a dictionary of the file paths and contents.

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

  Returns:
    A dictionary of the TF files in the given directory {path: contents}.
  .z.tfz.tfvars)collectionsdequepopleftoslistdirpathjoinisdir
startswithappendisfileendswithr   ReadFileContents)r   tf_files	dir_queuecurrent_diritem	item_paths         ?lib/googlecloudsdk/api_lib/scc/remediation_intents/terraform.pyfetch_tf_filesr%   "   s      (
+)
 	##%K

;''',,{D1i	y	!s#


9
%77>>)$


U
#y'9'9)'D&&s+#44Y? ( 	 
/    dir_pathc                    	 t        j                         }t        j                  |        ddg}t        j                  |t
        j                         	 g d}t        j                  |t
        j                  d      }t        j                  |       t        j                  |d         S # t        $ r#}t        j                  t        |            d}~ww xY w# t        $ r#}t        j                  t        |            d}~ww xY w)	zFetches the TfState json for the given directory and returns in json format.

  Args:
    dir_path: The path of the directory to fetch the TfState data from.

  Returns:
    The json of the TfState data or throws an exception if there is an error.
  	terraforminit)timeout_secN)r)   showz-jsonT)r+   strip_outputr   )r   getcwdchdirr   GetOutputLinesr	   TF_CMD_TIMEOUT	Exceptionr   TfStateFetchingErrorstrjsonloads)r'   org_dircmdetfstate_datas        r$   fetch_tfstater;   @   s    .iikGHHX
C!!#53G3GH.
(C!00--DL HHW::l1o&& 
 .

%
%c!f
--. 
 .

%
%c!f
--.s1   AB, AC ,	C5CC	D$DDmodified_tf_filesc           
      z   i }| j                         D ]  \  }}t        j                  |      ||<    | j                         D ]X  \  }}t        j                  ||       	 ddd|g}t	        j
                  |ddt        j                  t        j                        }Z ddg}	 t	        j
                  |ddt        j                  t        j                        }|j                         D cg c]  \  }}t        j                  ||       }}}y# t        j                  $ r}|j                         D cg c]  \  }}t        j                  ||       nc c}}w }}}t        j                  j                  ||j                  |j                        cY d}~c S d}~ww xY w# t        j                  $ r|}|j                         D cg c]  \  }}t        j                  ||       nc c}}w }}}t        j                  j                  |j                  |j                  	      cY d}~S d}~ww xY wc c}}w )
zValidates the given TF files and returns the appropriate error message if any.

  Args:
    modified_tf_files: The dictionary of the modified TF files {path: contents}.

  Returns:
    The error message if any in string format, otherwise None.
  r)   fmtz-write=trueT)textcheckstdoutstderr)	file_pathrA   rB   Nvalidate)rA   rB   )itemsr   r   WriteFileContents
subprocessrunPIPECalledProcessErrorr	   TF_FMT_ERROR_MSGformatrA   rB   TF_VALIDATE_ERROR_MSG)	r<   original_tf_filesrC   _file_contentr8   r9   fpfcs	            r$   validate_tf_filesrS   ^   s    ')'--/li#(#9#9)#Di  0 "3!8!8!:i	I|4%	:c
..
a	 ";. 
j!#	A& 6G5L5L5NO5N62rur2&5N!O	E (( 	 *//11fb" 
!
!"b
)1a 
 ##**ahhqxx +  	* 
	&	& 	 (--/	/FB 	B'/	A 	
 &&--xx .  	 PsZ    <D#6F% , H7F"#F6 E
?FF"F"%H48H/ G,+>H/)H4/H4tfstate_jsonc                     g dt         t        t        f   ffd| j                  di       j                  di       } |       S )a{  Traverses the TfState json and returns a list of resources in json format.

  Args:
    tfstate_json: The json of the TfState data. Structure:
                  {
                      "values": {
                          "root_module": {
                              "resources": [ ... ],  # List of resources
                              "child_modules": [     # List of nested modules
                                  {
                                      "resources": [ ... ],
                                      "child_modules": [ ... ]
                                  }
                              ]
                          }
                      }
                  }
  Returns:
    A list of json objects, each representing a resource in the TfState.
    or an empty list if there are no resources in the TfState or if the TfState
    is not in the expected format.
  modulec                 d    d| v rj                  | d          d| v r| d   D ]
  } |        y y )N	resourceschild_modules)extend)rV   childall_resourcestraverses     r$   r]   z,get_resources_from_tfstate.<locals>.traverse   sA    f6+./& /*% + !r&   valuesroot_module)r   r4   r   get)rT   r_   r\   r]   s     @@r$   get_resources_from_tfstatera      sM    4 -tCH~    2.22="E+
;	r&   c                 D   t        |       }t        |      }i t        j                  D ci c]  }|t        j
                   c}t        j                  D ci c]  }|t        j                   c}}|j                  |v r ||j                     ||      S yc c}w c c}w )a  Parses the tfstate file for the given finding.

  Args:
    dir_path: The path of the directory to parse the tfstate file from.
    finding_data: SCC Finding data in form of class
      (securityposture.messages.Finding).

  Returns:
    The structured data depending on the finding category, in string format. If
    the finding category is not supported, returns an empty string.
   )	r;   ra   r	   IAM_RECOMMENDER_FINDINGSr
   iam_recommender_parserFIREWALL_FINDINGSfirewall_parsercategory)r'   finding_datatftstate_jsonrX   rh   
parser_maps         r$   parse_tf_filerl      s      )-(7)	  88	8h G22
28		  11	1h G++
+1		* j(,:l++,YEE			s   BB)__doc__
__future__r   r   r   r   r5   r   rG   typingr   r   r   .googlecloudsdk.api_lib.scc.remediation_intentsr	   r
   googlecloudsdk.command_lib.coder   2googlecloudsdk.command_lib.scc.remediation_intentsr   googlecloudsdk.core.utilr   r4   r%   r;   rS   ra   rl    r&   r$   <module>ru      s    3 &  '   	  " " @ B : E *S T#s(^ <.C .4 .<<c3h <C <~%sCx.%	$sCx.%PC # r&   