
    mj1              	      *   U d 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ZddlZddl	Z	ddl
Z
ddlZddlZddlZddlmZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZmZ dd	lmZmZ d
g dg dddg ddddZde d<   dg g dZ!de d<   ddie!d ejD                   ejF                  e!dd      jI                               jK                         iZ&de d<    ejN                  d      Z( ejN                  d      Z)d d!ddd"Z*dCd#Z+dDd$Z,dd%dEd&Z-dFd'Z.dGd(Z/dHd)Z0	 	 	 	 dId*Z1	 	 	 	 dJd+Z2	 	 	 	 	 	 dKd,Z3	 	 	 	 	 	 	 	 dLd-Z4	 	 	 	 	 	 dMd.Z5dNd/Z6dOd0Z7	 	 	 	 	 	 dPd1Z8	 	 	 	 	 	 dQd2Z9	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dRd3Z:	 	 	 	 	 	 	 	 dSd4Z;	 	 	 	 	 	 	 	 	 	 dTd5Z<dUd6Z=dd7	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dVd8Z>dd9	 	 	 	 	 	 	 	 	 dWd:Z?dXd;Z@dYd<ZA	 	 	 	 	 	 	 	 dZd=ZB	 	 	 	 	 	 	 	 d[d>ZCddd?	 	 	 	 	 	 	 	 	 	 	 	 	 d\d@ZDd]dAZEeFdBk(  r eG eE             y)^zHOffline rehydration and sealed expected-state checks for Task26 bundles.    )annotationsN)BytesParser)compat32)Path)AnyMappingSequencecast)InvalidRequirementRequirement)InvalidVersionVersionz!task26-evidence-trust-boundary-v1)trusted_operator_accounthost_kernelselected_python_pip_toolchainsealed_wheel_bytes)content_identitydeterministic_tamper_detectionreproducibility*revocation_and_current_authority_selectionfail_closed_workflowzThese guarantees apply only while the trusted operator account, host kernel, selected Python/pip toolchain, and sealed wheel bytes remain trustworthy.zCoherent compromise of the trusted operator account or host administrator, including coherent modification of the repository, ledger, or verifier, is outside the Task26 threat model.)external_authenticitynon_repudiationowner_tamper_proof_or_worm+resistance_to_compromised_operator_or_adminFnone)schematrust_anchorsguarantees_within_boundaryscope_statementoutside_scopenot_claimedexternal_authenticity_claimedsignature_claimdict[str, object]TRUST_BOUNDARY	root_modedirectoriesentries_EMPTY_WHEELHOUSE_PAYLOADr   %task26-sealed-wheelhouse-inventory-v1inventory_sha256T,:	sort_keys
separators_EMPTY_WHEELHOUSEz[-_.]+z^[0-9a-f]{64}$z+task26-preexecution-candidate-derivation-v1&pre_execution_product_or_wheel_binding)r   derived_fromknown_before_golden_path"evidence_outputs_are_digest_inputsc                R    t        j                  | dddd      j                         S )NFTr.   )ensure_asciir2   r3   	allow_nan)jsondumpsencodevalues    /home/cube/projects/richard/traning coach/.omo/evidence/task26/task26-prebound-cross-mode-installed-st_01a01574-v12/gateway/platforms/task26_final_state.py	canonicalrB   S   s+    :: fh    c                   t        j                         }| j                  d      5 t        fdd      D ]  }|j	                  |        	 d d d        |j                         S # 1 sw Y   |j                         S xY w)Nrbc                 &     j                  d      S )Ni   )read)streams   rA   <lambda>zsha256_file.<locals>.<lambda>`   s    &++k":rC   rC   )hashlibsha256openiterupdate	hexdigest)pathdigestchunkrH   s      @rA   sha256_filerS   ]   sh    ^^F	4F:C@EMM%  A 
  
 s   &A&&A>	directoryc                  | j                         }|rt        j                  nt        j                  }|rddhnddh}t        j                  |j
                        se ||j
                        rS|j                  t        j                         k7  s2|s|j                  dk7  s!t        j                  |j
                        |vrt        d|        y )N  i@          z sealed private path is invalid: )lstatstatS_ISDIRS_ISREGS_ISLNKst_modest_uidosgeteuidst_nlinkS_IMODE
ValueError)rP   rU   infoexpectedmodess        rA   _privaterj   e   s    ::<D(t||dllH'UENeU^ET\\"%;;"**,&dmmq0<<%U2;D6BCC 3rC   c                    t        | t              rt        d | D              rt        | d      t	        t        t
        t        f   |       S )Nc              3  >   K   | ]  }t        |t                 y wN)
isinstancestr).0keys     rA   	<genexpr>z_object.<locals>.<genexpr>t   s     )Tesjc.B*Be   z is invalid)rn   dictanyrf   r
   ro   r   )r@   labels     rA   _objectrw   s   s@    eT"c)Te)T&TE7+.//S#X&&rC   c                J    t         j                  d|       j                         S )N-)_NORMALIZE_PROJECTsublowerr?   s    rA   _normal_projectr}   y   s    !!#u-3355rC   c           	     d   t        |        	 t        j                  |       5 }|j                         }t	        |      t	        t        |            k7  st        d |D              rt        d      |D cg c]  }|j                  d      s| }}t	        |      dk7  rt        d      t        t              j                  |j                  |d               }d d d        t        j                  d	d
            j!                         }t        |j                  dd
            j!                         }|r|st        d      	 t        t#        |            }	t'        d |j)                  d      xs g D              }
t+        |      |	|
t-        |       | j/                         j0                  t/        j2                  | j/                         j4                        dS c c}w # 1 sw Y   xY w# t        j                  $ r}t        d      |d }~ww xY w# t$        $ r}t        d      |d }~ww xY w)Nc              3  p   K   | ].  }|j                  d       xs dt        |      j                  v  0 yw)/..N)
startswithr   parts)rp   names     rA   rr   z"_wheel_identity.<locals>.<genexpr>   s3     ZTYDts+GttDz7G7G/GGTYs   46zwheel members are invalidz.dist-info/METADATArZ   z%wheel METADATA cardinality is invalid)policyr   zdependency wheel is invalidName r   z$wheel project/version is unavailablezwheel version is invalidc              3  2   K   | ]  }t        |        y wrm   ro   )rp   r@   s     rA   rr   z"_wheel_identity.<locals>.<genexpr>   s     [3Y#e*3Y   zRequires-Dist)projectversionrequires_distrK   sizemode)rj   zipfileZipFilenamelistlensetru   rf   endswithr   r   
parsebytesrG   
BadZipFilero   getstripr   r   sortedget_allr}   rS   r\   st_sizere   r`   )rP   archivenamesr   metadata_namesmessageexcr   version_textr   requirementss              rA   _wheel_identityr   }   s   TNA__T"g$$&EE
c#e*o-ZTYZZ !<==!&!&$--8M*N   >"a' !HII!2==^A./G #" '++fb)*002Gw{{9b1288:L,?@@>gl+, [7???3S3YWY3Y[[L"7+%d#		##TYY[001 ' #"  A67S@A  >34#=>s`   G. AG!4GGAG!G. H G!!G+&G. .HHH	H/H**H/c                `    t         d       g }g } g}|ry|j                         }t        |d       t        t        j                  |      d       D ]3  }t        |j                        }|j                         }t        j                  |j                        rt        d      t        j                  |j                        rmt        |d       |j                  |j                         j                         t        j                   |j                        d       |j                  |       t        j"                  |j                        r-|j$                  dk(  rt        |       |j                  |       +t        d       |ryt        | fd	      t        |d
       fS )NTrT   c                    | j                   S rm   )r   )items    rA   rI   z#_wheelhouse_files.<locals>.<lambda>   s    DIIrC   )rq   zwheelhouse symlink is forbidden)relative_pathr   z.whlz.wheelhouse contains an unbound non-wheel entryc                B    | j                        j                         S rm   )relative_toas_posix)rP   roots    rA   rI   z#_wheelhouse_files.<locals>.<lambda>   s    (8(8(>(G(G(IrC   c                    t        | d         S )Nr   r   )rows    rA   rI   z#_wheelhouse_files.<locals>.<lambda>   s    CO0D,ErC   )rj   popr   rb   scandirr   rP   r[   r\   r_   r`   rf   r]   appendr   r   re   r^   suffix)r   wheelsr)   pendingrU   entryrP   rg   s   `       rA   _wheelhouse_filesr      sO    TT"F+-KfG
KKM	d+BJJy17MNNE

#D::<D||DLL) !BCC||DLL)."")-)9)9$)?)H)H)J $T\\ : t$dll+v0Ed# !QRR% O . 	vIJ{ EF rC   c                   i }t               }| D ]j  \  }}t        |j                  dd            }t        |j                  dd            }||f}||v s||v rt        d      |j	                  |       ||f||<   l | D ]*  \  }}|j                  d      }	t        |	t              st        d      |	D ]  }
	 t        t        |
            }|j                  t        d      |j                  |j                  j                         sV|j                  t        |j                              }|t        d	|j                         t        |d
   j                  dd            }|j                  s|j                  j                  |d      rt        d|j                          - y # t        $ r}t        d      |d }~ww xY w)Nr   r   r   z/duplicate project/version in explicit wheel setr   z)wheel dependency declarations are invalidz'wheel dependency declaration is invalidz%direct URL dependencies are forbiddenzmissing dependency: rZ   T)prereleaseszdependency version mismatch: )r   ro   r   rf   addrn   listr   r   urlmarkerevaluater}   r   	specifiercontains)r   projects
identitiesrP   identityr   r   rq   _pathr   rawrequirementr   
dependencyselected_versions                  rA   _validate_dependency_closurer      s    >@H'*uJ hhll9b12hll9b12 *8 3NOOs!8, ! "x||O4,-HIICU)#c(3 * !HII!!-k6H6H6Q6Q6S!ok6F6F&GHJ! #78H8H7I!JKK":a=#4#4Y#CD$$[-B-B-K-K d .L . !#@AQAQ@R!STT!  	 " & U !JKQTTUs   7F--	G6GGc                  |D cg c]  }|t        |      f }}| g }g }n]t        |       \  }}|D cg c]  }|t        |      f }}|D cg c](  \  }}d|j                  |       j                         i|* }}}| d}	g }n-t	        j
                  | j	                         j                        }	t        g ||       |	|d}
ddi|
dt        j                  t        |
            j                         iS c c}w c c}w c c}}w )zMBuild an exact recursive inventory and prove the explicit dependency closure.Nr   r'   r   r,   r-   )r   r   r   r   r\   re   r`   r   rJ   rK   rB   rO   )
wheelhouserequired_wheelsrP   root_wheelsdependency_wheelsr*   pathsr)   r   r(   payloads              rA   build_wheelhouse_inventoryr      sN    >MM_TD/$/0_KMEG+-.z:{GLMutdOD$9:uM #4

 #4h  !1!1*!=!F!F!H #4 	 
  $	LL!2!:!:;	 !C;!C1B!CD"G 	9
 	GNN9W+=>HHJ 3 N N
s   C<D-Dc                  t        |d      }t        |      h dk7  s|j                  d      dk7  rt        d      |j                  d      }|j                  d      }|j                  d      ||d	}t	        |t
              rNt	        |t
              r>|j                  d
      t        j                  t        |            j                         k7  rt        d      t        | |      }||k7  rt        d      |S )Nsealed wheelhouse inventory>   r   r*   r(   r)   r-   r   r,   -sealed wheelhouse inventory schema is invalidr*   r)   r(   r'   r-   z-sealed wheelhouse inventory digest is invalidr   z4wheelhouse inventory differs from sealed expectation)rw   r   r   rf   rn   r   rJ   rK   rB   rO   r   )r   rh   r   documentr*   r)   r   actuals           rA   verify_wheelhouse_inventoryr     s     x!>?H
8}   

	0
1 HIIll9%G,,}-K\\+."G w%+t,<<*+>>)G,-779: HII'OF OPPMrC   c                   |j                  d      }t        |t              st        d      | |rt        d      g S g }|D ]~  }t	        |d      }|j                  d      }t        |t
              r0t        |      j                         sdt        |      j                  v rt        d      |j                  | |z          |S )Nr*   z%sealed wheelhouse entries are invalidz sealed wheelhouse is unavailablezsealed wheelhouse rowr   r   z!sealed wheelhouse path is invalid)
r   rn   r   rf   rw   ro   r   is_absoluter   r   )r   	inventoryr*   r   r   r   relatives          rA   _bound_wheel_pathsr   8  s     mmI&Ggt$@AA?@@	Ec2377?+8S)H~))+tH~+++@AAZ(*+  LrC   c           	        t        | d      }t        |j                  d      d      }t        |j                  d      d      }|j                  d      }|j                  d      dk7  s;|j                  d      d	k7  s'|d
dddk7  st        |t              rt	        |      dk7  rt        d      ddg}t        ||d      D ]  \  }\  }}t        |d      }	|	j                  d      }
t        |	      h dk7  s|	j                  d      |k7  s|	j                  d      |k7  st        |
t              rt        |
      j                         sndt        |
      j                  v sWt        j                  t        |	j                  dd                  )t        |	j                  d            t        us	|	d   dk  st        d       y )Nzportable installed runtimeorigin_proofzportable origin proof	executionzportable origin executionmodulesr   $installed-golden-runtime-portable-v1 task26-installed-origin-proof-v1private_empty_controlledTFcwd_authoritypython_isolatedpythonpath_inherited   z*portable installed origin proof is invalidgatewayhermescheckin_cliprofilestrictzportable origin moduleinstalled_relative_path>   r   modulerK   distributionr   r   r   r   rK   r   r   rZ   z1portable installed origin module proof is invalid)rw   r   rn   r   r   rf   zipr   ro   r   r   r   _HEX_DIGEST	fullmatchtypeint)runtime_portableruntimeproofr   r   expected_pairsr   r   r   r   r   s              rA   "_validate_portable_origin_contractr   P  s   &(DEGGKK/1HIE		+.0KLIii	"GH!GG99X"DD7#$)

 '4(w<1EFF+-GHN'*7N4'P##flc347745H wwx F*ww~&,6h,H~))+tH~+++$$S2)>%?@HCGGFO$C/6{QPQQ+ (QrC   c                    t         j                  |       t        d      d| | t        d}t	        j
                  t        |            j                         |d<   |S )zNBuild the outer pre-execution product binding wrapper without evidence inputs.z!outer candidate digest is invalid"task26-outer-candidate-manifest-v1)r   candidate_digestproduct_binding_sha256derivation_contractmanifest_sha256)r   r   rf   CANDIDATE_DERIVATION_CONTRACTrJ   rK   rB   rO   )r   r   s     rA   build_outer_candidate_manifestr  {  s\    -.6<==6,"2<	#H #*..81D"E"O"O"QHOrC   c                   t        |      }|j                         sd|j                  v rt        d      | |z  }t	        |       t        t        j                  |j                  d            d      }t        |      h dk7  rt        d      |j                         D ci c]  \  }}|dk7  s|| }}}t        |j                  d	d
            }|j                  d      dk7  st        j                  |      j|j                  d      |k7  sV|j                  d      t        k7  s>|j                  d      t!        j"                  t%        |            j'                         k7  rt        d      |t)        |      fS c c}}w )Nr   z(outer candidate manifest path is invalidutf-8encodingzouter candidate manifest>   r   r  r   r  r  z*outer candidate manifest schema is invalidr  r   r   r   r   r  r  z+outer candidate manifest binding is invalid)r   r   r   rf   rj   rw   r<   loads	read_textr   itemsro   r   r   r   r  rJ   rK   rB   rO   rS   )	bundler   r   rP   r   rq   r@   unsigned	candidates	            rA    _verify_outer_candidate_manifestr    sj    M"H!7CDDHDTN

4>>7>346PH 8}   EFF%-^^%5%5zsE@Q9QU
%5   HLL!3R89IX"FF  +3<<01Y><<-.2OO<<)*>>)H-.88:; FGGk$'''s   "E>0E>c                  t        | j                  d      | d      }t        | j                  d      | d      }| j                  d      }| j                  d      }| j                  d      |k7  st        j                  t	        |            t        j                  t	        |            |j                  d      |k7  st        j                  t	        |j                  d	d
                  	 ]t        j                  t	        |j                  dd
                  	 .t        j                  t	        |j                  dd
                  t        | d      |||d   |d   |j                  d	      |j                  d      dS )Ncandidate_authorityz
 authoritytask26_contractz Task26 contractr   source_tree_digestruntime_modecurrent_qualified_candidateregistry_head_sha256r   ledger_head_sha256
chain_headz- candidate or authority projection is invalid)r   r  task26_chain_headauthority_current_candidateauthority_registry_headauthority_ledger_head)rw   r   r   r   ro   rf   )resultr   	authoritycontractr  source_trees         rA   _candidate_result_projectionr"    sv    

#89dV:;NOIvzz"34>N6OPH

-.I**12K

>"d*  Y08  [!12:==679D  	4b9:
    	2B78
    X\\,%C!DEMD6!NOPP%)%l3'01N'O#,==1G#H!*/C!D rC   c          
        t        |d      }t        |d      }t        | |      \  }	}
|d   |d   k7  rt        d      t        fd|d   |d   |d   |d   |	fD              rt        d	      ||fD ]6  }t	        |      }|j                         sd
|j                  v s-t        d       d||||||
|	dd}t        j                  t        |            j                         |d<   |S )Nsourcer   	installedr  z3source and installed tree provenance digests differc              3  (   K   | ]	  }|k7    y wrm    )rp   r@   r   s     rA   rr   z)build_candidate_parity.<locals>.<genexpr>  s#      	
E 	!!
   r   r  9source, installed, authority, and outer candidates differr   z'candidate parity bundle path is invalid%task26-cross-mode-candidate-parity-v1)r   rK   r   )r   r   source_bundle_relative_pathinstalled_bundle_relative_pathr$  r&  outer_manifestparity_sha256)r"  r  rf   ru   r   r   r   rJ   rK   rB   rO   )r  r   source_resultinstalled_resultr,  r-  outer_manifest_relative_pathr$  r&  outer_candidate	outer_shar   rP   r   s    `            rA   build_candidate_parityr5    s1    *-hGF,-=KPI!A,"OY "#y1E'FFNOO
 	 %&01()34
	 	 TUU02PQH~!3FGG R
 :,'B*H9 /
#H !(y/B C M M OH_OrC   c          
     $   t        |d      }t        |      h dk7  rt        d      |j                         D ci c]  \  }}|dk7  s|| }}}t        |j	                  d      d      }|j	                  d      }|j	                  d      d	k7  sb|j	                  d
      k7  sN|j	                  d      t        j                  t        |            j                         k7  st        |t              st        d      t        | |      \  }	}
t        |j	                  d      d      }t        |j	                  d      d      }|j	                  d      |j	                  d      k7  s}|j	                  d      |
k7  si|j	                  d
      |	k7  sUt        fd|	|j	                  d
      |j	                  d      |j	                  d
      |j	                  d      fD              rt        d      t        t        t        t        f   |      S c c}}w )Nzcandidate parity>   r   r$  r&  r/  r.  r   r,  r-  z"candidate parity schema is invalidr/  r.  zouter manifest parityr   r   r+  r   z"candidate parity digest is invalidr$  zsource candidate parityr&  zinstalled candidate parityr  rK   c              3  (   K   | ]	  }|k7    y wrm   r(  )rp   r@   expected_candidates     rA   rr   z*verify_candidate_parity.<locals>.<genexpr>!  s#      	
 ''r)  r  r*  )rw   r   rf   r  r   rJ   rK   rB   rO   rn   ro   r  ru   r
   rt   object)r  parityr8  r   rq   r@   r  outerr   r3  r4  r$  r&  s     `          rA   verify_candidate_parityr<    s    v12H
8} 	 	 =>>%-^^%5%5zsE9OU
%5   HLL!124KLEyy)HX"II<<*+/AA<<(>>)H-.88:;(C(=>>!A&(!SOYX\\(+-FGF[13OPI

'(IMM:N,OO99X)+99'(O; 	
  

-.

8901;<	
 	
 TUUS&[!8,,As   H
Hc          
     h   t        | d       t        |       t        |       t        |       t        t        j                  |j	                  d            d      }t        |      h dk7  s|j                  d      dk7  rt        d	      |j                  d
      }|j                         D ci c]  \  }}|d
k7  s|| }}}|t        j                  t        |            j                         k7  rt        d      |j                  d      t        k7  rt        d      t        |j                  d             t        | |j                  d      t!        |j                  dd                   d|fd|ffD ]J  \  }	}
t        |j                  |	      |	      }||
j"                  t%        |
      dk7  s=t        d|	 d       t        |j                  d      d      }t        |      h dk7  rt        d      dD ]  }	t        |j                  |	      |	      }|j                  d      }t'        |t               r0t)        |      j+                         sdt)        |      j,                  v rt        d|	 d      | |z  }t        |       |j                  d       t%        |      k7  st        d|	 d       t        |j                  d!      d"      }d#D ]O  }| d$z  |z  }t        |       |j                  |j/                  d%      d&z         t%        |      k7  sFt        d'       |S c c}}w )(zGValidate the hash-bound portable expectation before creating a runtime.TrT   r  r  zsealed expected state>   r   verifierr  r   hermes_wheelprofile_wheeltrust_boundarydocument_sha256expected_statusr   candidate_parityr   provenance_helperexpected_result_sha256r   task26-sealed-final-state-v1z'sealed expected-state schema is invalidrB  z'sealed expected-state digest is invalidrA  z)sealed evidence trust boundary is invalidr   rD  r   r   r8  r?  r@  filenamerK   sealed  digest differsr   r   >   r   r*   r(   r)   r-   r   )r>  rE  r   r   z path is invalidrK   r  zsealed authority)zregistry.jsonzqualification-ledger.jsonzcandidate-authorityz.json_sha256zsealed authority digest differs)rj   rw   r<   r
  r  r   r   rf   r  rJ   rK   rB   rO   r&   r   r<  ro   r   rS   rn   r   r   r   removesuffix)r  expected_pathr?  r@  rh   claimedrq   r@   r  rv   rP   bindingr   r   targetr  r   s                    rA   verify_expected_staterS  0  s	    Vt$]\]

=**G*<=H 8}   
h	#A	ABCCll,-G-5^^-=Z-=zsEHYAYU
-=HZ'..8!45??AABCC||$%7DEE&x||4F'GH'(x||,>CD 
&	-(t (,,u-u5499D8IJJwug_=>> l35RSJ
:   HII2(,,u-u5;;/8S)H~))+tH~+++wug-=>??(";;x K$77wug_=>> 3 [13EFI>//$6==**73i?@KE
 
 >?? ? Oa [s   1L.?L.c                ^    | j                         D ci c]  \  }}|dvr|| c}}S c c}}w )N>   package_authorityrehydration_origin_proof)r  )r  rq   r@   s      rA   _portable_verifier_resultrW    s@     !,,.(JCGG 	U
(  s   ))r   c                  t        |j                  d      d      }t        |       |t        t              nt        |||f      }d|t        |      |j                  t        |      d|j                  t        |      d||t        | |z        d|t        | |z        d|j                  d      t        j                  t        t        |                  j                         t        | dz        t        | d	z        |j                  d
      |j                  d      dt        | ||||	|
|      t        d}t        j                  t        |            j                         |d<   |S )zIBuild, but do not write or freeze, one successor expected-state document.r  zcandidate authority resultr   rG  rI  )r   rK   statusz!candidate-authority/registry.jsonz-candidate-authority/qualification-ledger.jsonr  r  )registry_sha256zqualification-ledger_sha256r  r  )r   r0  r1  r,  r-  r2  )r   r   r   r?  r@  r   r>  rE  rC  rF  r  rD  rA  rB  )rw   r   r   rt   r4   r   r   rS   rJ   rK   rB   rW  rO   r5  r&   )r  r   r   r?  r@  verifier_relative_pathprovenance_relative_pathverifier_resultsource_verifier_resultr,  r-  r2  r   authority_resultwheelhouse_inventoryr   s                   rA   build_expected_statera    s   " 124P ''78  	'(E
  1, !12$))!,/

 &**!-0
 +3!&+A"AB

 6!&+C"CD
 +..x8")../@A#

)+*<<  ,7HH, %5$8$89O$P"2"6"67K"L	
 3-0,(C+I)E
 )Y-#H\ #*..81D"E"O"O"QHOrC   controlled_cwdc          	        t        |d      }t        |j                  d      d      }|j                  d      dk7  s|j                  d      dk7  s~|j                  d      d	uskt        |      d
dhk7  s[t        |j                  d      t              r<|Et        t	        |d               j                  d      |j                  d      k7  rt        d      t        | j                  d      d      }g }dD ]  \  }}	|j                  |      }
t        |
t              st        d      t        |
      }	 |j                  d      }|j                  |j                  d            j                         }|j                         }|j                         s.t        j                  |j                        r|j                  dk7  rt        d      t        |j                  |	      |	 d      }|j                  d      }t        |t               st        d      |D cg c]2  }t        |t"              r |j                  d      |k(  rt        |d      4 }}t%        |      }t'        |      dk7  s8|d   j                  d      |k7  s!|d   j                  d      |j(                  k7  rt        d      |j+                  |	||||j(                  d         d!d"dd	d#|d$S # t        t        f$ r}t        d      |d}~ww xY wc c}w )%z@Bind imported package origins to exact installed inventory rows.zrehydrated origin prober   zrehydrated module originsr   z!task26-rehydrated-origin-probe-v1isolatedrZ   pythonpath_presentFr   r   cwdNTr   z,rehydrated Python isolation proof is invaliddistributionsruntime distributions)r   r   z#rehydrated module origin is invalidz1module origin is outside rehydrated site-packagesz.rehydrated module origin is not a regular file distributioninstalled_inventoryzinstalled inventory is invalidrP   zinstalled inventory rowr   rK   r   z5module origin differs from installed RECORD inventory)r   r   r   rK   r   r   r   r   )r   r   r   )rw   r   r   rn   ro   r   resolverf   r   r   OSErrorr\   
is_symlinkr^   r`   rd   r   rt   rS   r   r   r   )r   site_packagesproberc  evidencer   rh  
proof_rowsr   roleraw_pathrP   resolvedr   r   metadatar   r   r   matchesrQ   s                        rA   verify_runtime_origin_proofrx    s    u78Hhll9-/JKGX"EE<<
#q(<<,-U:w<I}55(,,u-s3&S%)*22$2?%%T%23 GHHGKK8:QRM*,JK;;v&(C(BCCH~	||4|0H++M,A,A,A,NOXXZH
 ==?!<< 0 01  A%MNN}0064&8NO $$%:;	)T*=>> !
 #t$H)D C23  	 

 X&LAqz~~h'61qz~~f%)9)99TUU $ +3  ((	
G LZ 57#$)

  I $ 	C	
s   7AK"7L"L1K==Lc                F   t        | j                  d      d      }i }dD ]#  }t        |j                  |      | d      }|j                  d      }t        |t              rt	        d |D              rt        | d      |D cg c]^  }dt        t        |j                  d	d
                  j                  vr,t        |j                  d	d
            j                  d      s|` }}dD ci c]  }||j                  |       }	}||	d<   t        j                  t        |            j                         |	d<   |	||<   & t        | j                  d      d      }
d|
j                  d      |
j                  d      d|| j                  d      dS c c}w c c}w )Nrh  ri  )r   r   rj  rk  c              3  >   K   | ]  }t        |t                 y wrm   )rn   rt   )rp   r   s     rA   rr   z$_portable_runtime.<locals>.<genexpr>1  s      6
1>#
3%%rs   z installed inventory is invalidr   rP   r   z.dist-info/RECORD)distribution_namedistribution_versionmetadata_sha256wheel_filenamewheel_sha256wheel_record_sha256installed_inventory_sha256interpreterzruntime interpreterr   rK   r   )rK   r   r   )r   r  rh  r   )rw   r   rn   r   ru   rf   r   ro   r   r   rJ   rK   rB   rO   )r   rh  portable_distributionsrs  r   raw_inventoryr   r   rq   portable_distributionr  s              rA   _portable_runtimer  +  s   GKK8:QRM02%}0064&8NO$(()>?-.# 6
1>6
 3
 v%DEFF %
$4CGGFB$7 89???+,556IJ $ 	 

4
 !!#&& 	 
4
 8A34>Enni ?

)+ 	:; (=t$9 &: '++m46KLK8!ooh/"y1
 0N3 /

4
s   A#F0Fc                     t         j                  j                         D  ci c]*  \  } }| j                  d      s| j                  d      s| |, }} }|j	                  dt         j
                  ddd       |S c c}} w )NPYTHONPIP1)PYTHONNOUSERSITEPIP_CONFIG_FILEPIP_NO_INDEXPIP_DISABLE_PIP_VERSION_CHECK)rb   environr  r   rN   devnull)rq   r@   environments      rA   _clean_environmentr  W  s     ****,,JC~~h'u0E 	U
,  
  #!zz-0		
 s   /A:c               
   t        |d       t        |j                               rt        d      t	        j
                  t        |       d|t        |      dd      }t        |j                               rt        d      |S )NTrT   z"controlled Python cwd is not empty)checkrg  envcapture_outputtextz)Python subprocess wrote to controlled cwd)rj   ru   iterdirrf   
subprocessrunr   rt   )commandrc  r  	completeds       rA   _run_pythonr  h  sy     ^t,
>!!#$=>>WI >!!#$DEErC   c                    d|fd|ffD ]J  \  }}t        | j                  |      |      }||j                  t        |      dk7  s=t	        d| d       y )Nr?  r@  rI  rK  rL  )rw   r   r   rS   rf   )rh   r?  r@  rv   rP   rQ  s         rA   _verify_bound_wheel_hashesr  ~  se     
&	-(t (,,u-u5499D8IJJwug_=>>rC   )r   temp_parentc                   t         |||      }t        ||j                  d      ||f      }t        t	        j
                  d|            }|j                  d       |dz  j                  d       t               	 |d	z  }	t        t        j                  d
dd	t        |	      g       |	j                  d       |	t        j                  dk(  rdndz  t        ||||f      }t        |||       t!        ||      }
t              d
ddddddgd |
D        t        |      t        |      }t        |       t        t              d
ddg      j"                  j%                         }t        |      }|dz   t        t'        |d   d      d         z  }d}t        t              d
d|t        |      t        |	      t        |      t        |      t        |      g	      j"                  }t'        t)        j*                  |      d      }t'        |j                  d      d      }t-        |||j                  d       !      }||d"<   t/        |      |j                  d#      k7  rt1        d$      j3                  t5        |      d%z          j                  d&        t        t'        |d'   d'      d         z  t7         |j                  d(      t        |j                  d)d*            +      dB fd,} |d-d.      } |d/d0      }t9        |d1      j                  d1      k7  st9        |d2      j                  d2      k7  rt1        d3      t'        |j                  d4      d5      }t'        |j                  d6      d7      }|j                  d8      |j                  d9      k7  s|j                  d)      |j                  d)      k7  s|j                  d:      |j                  d:      k7  sj|j                  d;      |j                  d;      k7  sGt;        j<                  t5        t?        |                  jA                         |j                  d<      k7  rt1        d=      ||d><   |	 t        ||||f       t        |||       |jC                         rc|jE                  d?      D ]7  }	 |jG                         r|j                  |jI                         rdnd&       9 tM        jN                  |d@A       S S # tJ        $ r Y ^w xY w# |jC                         rr|jE                  d?      D ]F  }	 |jG                         r|j                  |jI                         rdnd&       9# tJ        $ r Y Dw xY w tM        jN                  |d@A       w w xY w# 	 t        ||||f       t        |||       |jC                         rr|jE                  d?      D ]F  }	 |jG                         r|j                  |jI                         rdnd&       9# tJ        $ r Y Dw xY w tM        jN                  |d@A       w w # |jC                         rr|jE                  d?      D ]F  }	 |jG                         r|j                  |jI                         rdnd&       9# tJ        $ r Y Dw xY w tM        jN                  |d@A       w w xY wxY w)CzECreate an isolated offline runtime, rerun verification, and scrub it.)r?  r@  r   r   ztask26-rehydrate-)prefixdirrW   zcontrolled-cwdr%  venv-Iz-mrc  r  ntzScripts/python.exez
bin/pythonpipinstallz
--no-indexz	--no-depsz--no-compilec              3  2   K   | ]  }t        |        y wrm   r   )rp   rP   s     rA   rr   z'rehydrate_and_verify.<locals>.<genexpr>  s     5$4Dc$i$4r   z-cz9import sysconfig; print(sysconfig.get_paths()['purelib'])zruntime.jsonrE  zprovenance helperr   a  import hashlib,importlib.util,json,os,pathlib,sys;p=pathlib.Path(sys.argv[1]);s=importlib.util.spec_from_file_location('sealed_provenance',p);m=importlib.util.module_from_spec(s);s.loader.exec_module(m);r=m.collect_installed_runtime(venv=pathlib.Path(sys.argv[2]),site_packages=pathlib.Path(sys.argv[3]),profile_wheel=pathlib.Path(sys.argv[4]),hermes_wheel=pathlib.Path(sys.argv[5]));import checkin_cli,gateway;o={'schema':'task26-rehydrated-origin-probe-v1','isolated':sys.flags.isolated,'pythonpath_present':'PYTHONPATH' in os.environ,'cwd':os.getcwd(),'modules':{'gateway':gateway.__file__,'checkin_cli':checkin_cli.__file__}};print(json.dumps({'runtime':r,'origin_probe':o},sort_keys=True,separators=(',',':')))zrehydrated probe documentr   zrehydrated runtimeorigin_proberb  r   r   z5rehydrated runtime differs from sealed portable bytes   
rX   r>  rD  r   r   rH  c           
        t        t        j                  | d                  }|z  }t        t        	      dt              t        |      dt        
      g      }t	        t        j                  |j                        |      S )Nr   r  z--rehydrated-runtimer  )r   ro   r   r  rw   r<   r
  stdout)relative_keyrv   r   target_bundler  r  rc  r  r:  pythonruntime_pathr>  s        rA   run_verifierz*rehydrate_and_verify.<locals>.run_verifier  s    C

< <=>H"X-M#KM&*%  .'I 4::i&6&67??rC   r,  z!rehydrated source verifier resultr-  z$rehydrated installed verifier resultr$  r&  z4rehydrated source/installed candidate parity differsr  zrehydrated authorityr  zexpected authorityrY  rC  r  r  rF  z=rehydrated verifier result differs from sealed expected staterV  *F)ignore_errors)r  ro   rv   ro   returndict[str, Any])(rS  r   r   r   tempfilemkdtempchmodmkdirr  r  sys
executablero   rb   r   r  r   r  r   rw   r<   r
  rx  r  rf   write_bytesrB   r<  r"  rJ   rK   rW  rO   existsrglobrn  is_dirrm  shutilrmtree) r  rO  r?  r@  r   r  rh   r   	temporaryr  dependency_pathsr  site_packages_textro  helperrp  probe_outputprobe_documentruntime_documentr   r  r0  r  r  expected_authorityrP   rc  r  r:  r  r  r>  s    `                         @@@@@@rA   rehydrate_and_verifyr    s    %!#	H ,\"&5I
 X%%-@kRSIOOE!11Ne$$&Kr>6!^^T4T;)#	

 	

5D-lS/*L9
	
 	#8\=I-j)DK
 6$45
 
 
 	N	
 )FK	 *#	
 & 	 /0 >1#H013FG
 
d 	  #FFD	M"M"L!
 *#
 & 	 !JJ|$&A
 #y)+?
 3~.)	
 ,8(-.(,,?Q2RRTUU  +;!<u!DE5!CHZ(*5oF
 
 )LL+,"8<<0BB#GH
	@ 	@" %)+N
 ,.T
 )XFzz(#$+FEzz+&' STTJJ,-/E
	 %LL%';
 JJx HLL1B$CCzz,->P1QQ}}34!%%&<=>}}12!%%&:;<~~3F;<ik||456
 O  .:)*	>'!. =
 'x}M!%OOC0D??,$

DKKM5uE	 1 iu= " #  !%OOC0D??,$

DKKM5uE"  1 iu= "	>'!. =
 'x}M!%OOC0D??,$

DKKM5uE"  1 iu= "y!%OOC0D??,$

DKKM5uE"  1 iu= "s   	PV6 T/T "#T  	T,+T,/%V3V
%V3&#V
	V3
	VV3VV36[8Y$[:X/
[#X/.[/	X;	8[:X;	;[%[>Z3
[#Z3
2[3	Z?<[>Z??[[c            	     .   t        j                         } | j                  dt               | j                  dt               | j                  dt        d       | j                  dt        d       | j                  dt               | j                  d	t               | j	                         }	 t        |j                  |j                  |j                  |j                  |j                  |j                  
      }t%        t!        j&                  |dd             y# t        t        t        j                  t         j"                  f$ rF}t%        t!        j&                  dt)        |      dd      t*        j,                         Y d }~yd }~ww xY w)Nr  )r   expected_statez--hermes-wheelT)r   requiredz--profile-wheelz--wheelhousez--temp-parent)r?  r@  r   r  TASK26_REHYDRATION_FAIL)rY  reason)r2   )filerZ   r.   r1   r   )argparseArgumentParseradd_argumentr   
parse_argsr  r  r  r?  r@  r   r  rm  rf   r  SubprocessErrorr<   JSONDecodeErrorprintr=   ro   r  stderr)parserargsr  r   s       rA   mainr  Y  sQ   $$&F
t,
(t4
(tdC
)tD
T2
d3D%KK**,,((
, 
$**Vt

CD 	""	  	JJ4CI 	
 s   2AD! !-F<FF__main__)r@   r9  r  bytes)rP   r   r  ro   )rP   r   rU   boolr  None)r@   r9  rv   ro   r  r  )r@   ro   r  ro   )rP   r   r  r%   )r   r   r  z*tuple[list[Path], list[dict[str, object]]])r   z+Sequence[tuple[Path, Mapping[str, object]]]r  r  )r   Path | Noner   Sequence[Path]r  r%   )r   r  rh   r9  r   r  r  r%   )r   r  r   Mapping[str, object]r  z
list[Path])r   r9  r  r  )r   ro   r  r%   )r  r   r   ro   r  ztuple[str, str])r  r  r   ro   r  r%   )r  r   r   ro   r0  r  r1  r  r,  ro   r-  ro   r2  ro   r  r%   )r  r   r:  r9  r8  ro   r  r%   )
r  r   rO  r   r?  r   r@  r   r  r  )r  r  r  r%   )r  r   r   ro   r   r  r?  r   r@  r   r[  ro   r\  ro   r]  r  r^  r  r,  ro   r-  ro   r2  ro   r   r  r  r%   )
r   r  ro  r   rp  r9  rc  r  r  r%   )r   r  r  r%   )r  zdict[str, str])r  zSequence[str]rc  r   r  zMapping[str, str]r  z subprocess.CompletedProcess[str])rh   r  r?  r   r@  r   r  r  )r  r   rO  r   r?  r   r@  r   r   r  r  r  r  r%   )r  r   )H__doc__
__future__r   r  rJ   r<   rb   rer  r\   r  r  r  r   email.parserr   email.policyr   pathlibr   typingr   r   r	   r
   packaging.requirementsr   r   packaging.versionr   r   r&   __annotations__r+   rK   r=   r>   rO   r4   compilerz   r   r  rB   rS   rj   rw   r}   r   r   r   r   r   r   r   r  r  r"  r5  r<  rS  rW  ra  rx  r  r  r  r  r  r  __name__
SystemExitr(  rC   rA   <module>r     s   N "    	 	    
   $ !  / / B 5 2#	
	+ &+A!%! !F 0 ,  5
(
( 

%!	
 &( ik
( $ 
  RZZ	* bjj*+;< $*/	!  /4 D'6$N 
 / F!U7!U	!UH## $# 	#L$$$ $	$
 $N(<0(RV ( (!$ ( (F +.B.. . (	.
 +. "%. %(. #&. .b/-/- /-9</-/-dRRR 	R
 R Rj, #KK K +	K
 K K  K "K *K 1K "%K %(K #&K K Kf #'M!MM M
  M M`)X"  #	
 &,	?"	?26	?GK	?		?$ ##L>L>L> 	L>
 L> L> L> L>^!H z
TV
 rC   