
                             d Z ddlmZ ddlmZ ddlmZ ddlZddlmZ ddlm	Z	 ddl
Z
ddlmZ d	Z G d
 de	      Zd Zd Zd Zd Zd Zd Zd Zd Zd Zy)z,Utilities for Binary Authorization commands.    )absolute_import)division)unicode_literalsN)docker_name)Error)urllibz/binaryauthorization.googleapis.com/attestationsc                       e Zd ZdZy)BadImageUrlErrorz@Raised when a container image URL cannot be parsed successfully.N)__name__
__module____qualname____doc__     9lib/googlecloudsdk/command_lib/container/binauthz/util.pyr
   r
   !   s    Hr   r
   c                    |xs d}t         j                  j                  |       }|j                  r'|j                  st        dj                  |             |j                  s.t         j                  j                  dj                  |             }|j                  |      j                         j                  d      S )az  Returns the passed `image_url` with the scheme replaced.

  Args:
    image_url: The URL to replace (or strip) the scheme from. (string)
    scheme: The scheme of the returned URL.  If this is an empty string or
      `None`, the scheme is stripped and the leading `//` of the resulting URL
      will be stripped off.
  Raises:
    BadImageUrlError: `image_url` isn't valid.
   zMImage URL '{image_url}' is invalid because it does not have a host component.)	image_urlz//{}scheme/)
r   parseurlparser   netlocr
   format_replacegeturllstrip)r   r   
parsed_urls      r   ReplaceImageUrlSchemer    %   s     <R&||$$Y/* z00
	ViV02 2 
		&&v}}Y'?@J
 
		F		+	2	2	4	;	;C	@@r   c                    t        | d      }	 t        j                  |      }ddt        j                  |j                               id|j                  iddiS # t        j                  $ r}t	        |      d}~ww xY w)	a  Creates a dict representing a JSON signature object to sign.

  Args:
    container_image_url: See `containerregistry.client.docker_name.Digest` for
      artifact URL validation and parsing details.  `container_image_url` must
      be a fully qualified image URL with a valid sha256 digest.

  Returns:
    Dictionary of nested dictionaries and strings, suitable for passing to
    `json.dumps` or similar.
  r   )r   r   Ncriticalzdocker-referencezdocker-manifest-digestz)Google cloud binauthz container signature)identityimagetype)	r    r   DigestBadNameExceptionr
   six	text_typeas_repositorydigest)container_image_urlurlrepo_digestes       r   MakeSignaturePayloadDictr0   G   s     	(;BG#$$S)K  #--0I0I0K"L '(:(: >

 
 
	%	% 
1
s   A A>.A99A>c                     t        |       }t        j                  |dddd      }dj                  |      j	                  d      S )a  Creates a JSON bytestring representing a signature object to sign.

  Args:
    container_image_url: See `containerregistry.client.docker_name.Digest` for
      artifact URL validation and parsing details.  `container_image_url` must
      be a fully qualified image URL with a valid sha256 digest.

  Returns:
    A bytestring representing a JSON-encoded structure of nested dictionaries
    and strings.
  T   ),z: )ensure_asciiindent
separators	sort_keysz{}
utf-8)r0   jsondumpsr   encode)r,   payload_dictpayloads      r   MakeSignaturePayloadr>   e   sJ     **=>, JJ' 
w		&	&w	//r   c                     t        | d      }	 t        j                  |       |S # t        j                  $ r}t	        |      d}~ww xY w)zEnsures the given URL has no scheme (e.g.

  replaces "https://gcr.io/foo/bar" with "gcr.io/foo/bar" and leaves
  "gcr.io/foo/bar" unchanged).

  Args:
    artifact_url: A URL string.
  Returns:
    The URL with the scheme removed.
  r   r   N)r    r   r&   r'   r
   )artifact_urlurl_without_schemer/   s      r   RemoveArtifactUrlSchemerB      sR     -\"E )* 
 
	%	% 
1
s   & A	AA	c                     t        | d      }	 t        j                  |      }|j
                  S # t        j                  $ r}t	        |      d}~ww xY w)zReturns the digest of an image given its url.

  Args:
    artifact_url: An image url. e.g. "https://gcr.io/foo/bar@sha256:123"

  Returns:
    The image digest. e.g. "sha256:123"
  r   r   N)r    r   r&   r'   r
   r+   )r@   rA   r+   r/   s       r   GetImageDigestrD      sX     -\"E  23F 
 
	%	% 
1
s   0 AAAc           	          | j                  d      }|j                  d      }dj                  ddt        |      z  |dt        |      z  |g      S )zPae encode input using the specified dsse type.

  Args:
    dsse_type: DSSE envelope type.
    body: payload string.

  Returns:
    Pae-encoded payload byte string.
  r8       s   DSSEv1s   %d)r;   joinlen)	dsse_typebodydsse_type_bytes
body_bytess       r   	PaeEncoderM      sZ     $$W-/{{7#*	c/""c*o 
 r   c           	      F    ddddid| D cg c]  }d|i c}id}|S c c}w )zCreates a minimal PodSpec from a list of images.

  Args:
    images: list of images being evaluated.

  Returns:
    PodSpec object in JSON form.
  v1Podnamer   
containersr$   )
apiVersionkindmetadataspecr   )imagesr$   rV   s      r   GeneratePodSpecFromImagesrX      sG     
" v>ve'5)v>	
$ 
+	 ?s   c                     | d   j                  di       }|j                  t        d      }|rdj                  |g|z         |t        <   ndj                  |      |t        <   || d   d<   | S )a  Inlines attestations into a Kubernetes PodSpec.

  Args:
    pod_spec: The PodSpec provided by the user.
    attestations: List of attestations returned by the policy evaluator in comma
      separated DSSE form.

  Returns:
    Modified PodSpec with attestations inlined.
  rU   annotationsNr3   )get$_BINAUTHZ_ATTESTATION_ANNOTATION_KEYrG   )pod_specattestationsrZ   existing_attestationss       r   AddInlineAttestationsToPodSpecr`      s}     $((;+%//*D 8;	,.9K45 9<8NK45(3(:}%	/r   c                 ^    | d   dk7  rt        | d   d   |      | d   d<   | S t        | |      S )a,  Inlines attestations into a Kubernetes resource.

  Args:
    resource: The Kubernetes resource provided by the user.
    attestations: List of attestations returned by the policy evaluator in comma
      separated DSSE form.

  Returns:
    Modified Kubernetes resource with attestations inlined.
  rT   rP   rV   template)r`   )resourcer^   s     r   AddInlineAttestationsToResourcerd      sH     f#A$l$HVZ  O	',	??r   )r   
__future__r   r   r   r9   containerregistry.clientr   googlecloudsdk.core.exceptionsr   r(   	six.movesr   r\   r
   r    r0   r>   rB   rD   rM   rX   r`   rd   r   r   r   <module>ri      sj    3 &  '  0 0 
  6 %
Iu IAD<08*(*.2@r   