
    Wwgh                        d Z ddlZddlmZ ddlmZmZmZ ddlm	Z	m
Z
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dlmZ ddlmZ ddlmZmZ ddlm Z  ddl!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z-m.Z. g dZ/ ej`                  e1      Z2 G d de"      Z3 G d d      Z4 G d de      Z5 G d de      Z6 G d d      Z7ddd d!d"d#d$d%Z8e8js                         D  ci c]  \  } }|| 
 c}} Z:dVd&ejv                  fd'Z< ed()       G d* d+             Z=e G d, d-e             Z>e G d. d/e             Z?e G d0 d1e"             Z@e G d2 d3e             ZA ed()       G d4 d5             ZB G d6 d7e      ZC ed()       G d8 d9             ZD ed()       G d: d;             ZE ed()       G d< d=             ZF ed()       G d> d?             ZG	 	 	 dWd@e+fdAZHdXd@e+dBeIfdCZJ	 dVdDe+fdEZKdFej                  dGej                  fdHZMdIej                  dGeeNeNf   fdJZO	 	 dYdKe)dLe
eI   dMe
eP   fdNZQ	 	 	 	 dZdOZRdPe+dQeGfdRZSdPe+dFej                  dQeGfdSZT G dT dUej                        ZUyc c}} w )[zQ
Utilities to deal with signature form fields and their properties in PDF files.
    N)	dataclass)EnumFlagunique)ListOptionalSetTupleUnion)x509)KeyUsage)AuthorityWithCert)InvalidCertificateError)ValidationPath)generic)
RawContent)pdf_name
pdf_string)BoxConstraints)OrderedEnumPdfErrorPdfReadErrorPdfWriteErrorget_and_applyrd)
PdfHandler)BasePdfFileWriter)SigningErrorUnacceptableSignerError)SigFieldSpecSigSeedValFlagsSigCertConstraintsSigSeedValueSpecSigCertConstraintFlagsSigSeedSubFilterSeedValueDictVersionSeedLockDocumentSigCertKeyUsageMDPPermFieldMDPActionFieldMDPSpecSignatureFormFieldInvisSigSettingsVisibleSigSettingsenumerate_sig_fieldsappend_signature_fieldensure_sig_flagsprepare_sig_fieldapply_sig_field_spec_propertiesannot_width_heightget_sig_field_annotc                        e Zd ZdZdZ	 dZ	 dZy)r)   zL
    Indicates a ``/DocMDP`` level.

    Cf. Table 254  in ISO 32000-1.
             N)__name__
__module____qualname____doc__
NO_CHANGES
FILL_FORMSANNOTATE     J/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/sign/fields.pyr)   r)   @   s+     J J HrB   r)   c                   6    e Zd ZdZddee   fdZd ZdefdZ	y)	SeedSignatureTypea+  
    Signature type indicator to be embedded into the seed value dictionary
    attached to a signature field.

    :param mdp_perm:
        If not ``None``, indicates that the signature field is intended for
        a certification signature. The :class:`MDPPerm` value passed as the
        ``mdp_perm`` parameter indicates the modification policy that the
        certification signature should use.

        A value of ``None`` indicates that the signature field is intended for
        an approval signature (i.e. a non-certification signature).
    Nmdp_permc                     || _         y NrF   )selfrF   s     rC   __init__zSeedSignatureType.__init__m   s	     rB   c                 X    t        |t              xr |j                  | j                  k(  S rH   )
isinstancerE   rF   rJ   others     rC   __eq__zSeedSignatureType.__eq__p   s'    u/0 0$--/	
rB   returnc                     | j                   d uS rH   rI   rJ   s    rC   certification_signaturez)SeedSignatureType.certification_signaturev   s    }}D((rB   rH   )
r:   r;   r<   r=   r   r)   rK   rP   boolrT   rA   rB   rC   rE   rE   ^   s)    !'!2 !
) )rB   rE   c                   D    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 d	Z	 d
Zy)r!   a  
    Flags for the ``/Ff`` entry in the seed value dictionary for a signature
    field. These mark which of the constraints are to be strictly enforced,
    as opposed to optional ones.

    .. warning::
        The flags :attr:`LEGAL_ATTESTATION` and :attr:`APPEARANCE_FILTER` are
        processed in accordance with the specification when creating a
        signature, but support is nevertheless limited.

        * PyHanko does not support legal attestations at all, so given that
          the :attr:`LEGAL_ATTESTATION` requirement flag only restricts the
          legal attestations that can be used by the signer, pyHanko can safely
          ignore it when signing.

          On the other hand, since the validator is not aware of
          legal attestations either, it cannot validate signatures that
          make :attr:`~.SigSeedValueSpec.legal_attestations` a mandatory
          constraint.
        * Since pyHanko does not define any named appearances, setting
          the :attr:`APPEARANCE_FILTER` flag and the
          :attr:`~.SigSeedValueSpec.appearance` entry in the seed value
          dictionary will make pyHanko refuse to sign the document.

          When validating, the situation is different: since pyHanko has no
          way of knowing whether the signer used the named appearance imposed
          by the seed value dictionary, it will simply emit a warning and
          continue validating the signature.
    r7   r8                @         N)r:   r;   r<   r=   FILTER	SUBFILTERVREASONSLEGAL_ATTESTATIONADD_REV_INFODIGEST_METHODLOCK_DOCUMENTAPPEARANCE_FILTERrA   rB   rC   r!   r!   z   su    < F
 I 	
A G  L M M rB   r!   c                   D    e Zd ZdZdZ	 dZ	 dZ	 dZ	 dZ	 dZ		 dZ
	 eez  Zy	)
r$   a^  
    Flags for the ``/Ff`` entry in the certificate seed value dictionary for
    a dictionary field. These mark which of the constraints are to be
    strictly enforced, as opposed to optional ones.

    .. warning::
        While this enum records values for all flags, not all corresponding
        constraint types have been implemented yet.
    r7   r8   rW   rX   rY   rZ   r[   N)r:   r;   r<   r=   SUBJECTISSUEROID
SUBJECT_DNRESERVED	KEY_USAGEURLUNSUPPORTEDrA   rB   rC   r$   r$      sk     G F C J H I C S.KrB   r$   c                       e Zd ZdZ	 	 ddee   dee   fdZd Zed        Z	e	 	 ddee
e      dee
e      fd       Zd	e
e   fd
Zd	e
e   fdZd Zy)r(   u  
    Encodes the key usage bits that must (resp. must not) be active on the
    signer's certificate.

    .. note::
        See § 4.2.1.3 in :rfc:`5280` and :class:`.KeyUsage` for more
        information on key usage extensions.

    .. note::
        The human-readable names of the key usage extensions are recorded
        in ``camelCase`` in :rfc:`5280`, but this class uses
        the naming convention of :class:`.KeyUsage` in ``asn1crypto``.
        The conversion is done by replacing ``camelCase`` with ``snake_case``.
        For example, ``nonRepudiation`` becomes ``non_repudiation``, and
        ``digitalSignature`` turns into ``digital_signature``.

    .. note::
        This class is intended to closely replicate the definition of the
        KeyUsage entry Table 235 in ISO 32000-1.
        In particular, it does *not* provide a mechanism to deal
        with extended key usage extensions (cf. § 4.2.1.12 in :rfc:`5280`).

    :param must_have:
        The :class:`.KeyUsage` object encoding the key usage extensions
        that must be present on the signer's certificate.
    :param forbidden:
        The :class:`.KeyUsage` object encoding the key usage extensions
        that must *not* be present on the signer's certificate.
    N	must_have	forbiddenc                     ||nt        t                     | _        ||| _        y t        t                     | _        y rH   )r   setrq   rr   )rJ   rq   rr   s      rC   rK   zSigCertKeyUsage.__init__  s0    
 '0&;#%&/&;#%rB   c                 d     dt         f fddj                  fdt        d      D              S )z
        Encode the key usage requirements in the format specified in the PDF
        specification.

        :return:
            A string.
        bitc                 F    j                   |    ryj                  |    ryy)N10Xrq   rr   )rv   rJ   s    rC   fmt_bitz4SigCertKeyUsage.encode_to_sv_string.<locals>.fmt_bit0  s$    ~~c"$rB    c              3   .   K   | ]  } |        y wrH   rA   ).0rv   r|   s     rC   	<genexpr>z6SigCertKeyUsage.encode_to_sv_string.<locals>.<genexpr>8  s     8ws|8s   	   )intjoinrange)rJ   r|   s   `@rC   encode_to_sv_stringz#SigCertKeyUsage.encode_to_sv_string'  s*    	 	 ww8uQx888rB   c                 n    dd fd}t        t         |d            t         |d                  S )a  
        Parse a PDF KeyUsage string into an instance of
        :class:`.SigCertKeyUsage`. See Table 235 in ISO 32000-1.

        :param ku_str:
            A PDF KeyUsage string.
        :return:
            An instance of :class:`.SigCertKeyUsage`.
        Nr   c                 .     t         fdD              S )Nc              3   0   K   | ]  }|k(  rd nd  yw)r7   r   NrA   )r   valwith_vals     rC   r   zISigCertKeyUsage.read_from_sv_string.<locals>._as_tuple.<locals>.<genexpr>H  s     GcXo14Gs   )tuple)r   ku_strs   `rC   	_as_tuplez6SigCertKeyUsage.read_from_sv_string.<locals>._as_tupleG  s    GGGGrB   rx   ry   r{   )r(   r   )clsr   r   s    ` rC   read_from_sv_stringz#SigCertKeyUsage.read_from_sv_string:  s=     	H y~.y~.
 	
rB   c                     t        t        |
t               n|      t        |t                           S |            S )a  
        Initialise a :class:`.SigCertKeyUsage` object from two sets.

        :param must_have:
            The key usage extensions that must be present on the signer's
            certificate.
        :param forbidden:
            The key usage extensions that must *not* be present on the signer's
            certificate.
        :return:
            A :class:`.SigCertKeyUsage` object encoding these.
        r{   )r(   r   rt   )r   rq   rr   s      rC   	from_setszSigCertKeyUsage.from_setsO  sA    $ 	(9suyI	(9suI
 	
?HI
 	
rB   rQ   c                 .    | j                   j                  S )zr
        Return the set of key usage extensions that must be present
        on the signer's certificate.
        )rq   nativerS   s    rC   must_have_setzSigCertKeyUsage.must_have_setf      
 ~~$$$rB   c                 .    | j                   j                  S )zv
        Return the set of key usage extensions that must not be present
        on the signer's certificate.
        )rr   r   rS   s    rC   forbidden_setzSigCertKeyUsage.forbidden_setm  r   rB   c                     t        |t              xrD | j                         |j                         k(  xr! | j                         |j                         k(  S rH   )rM   r(   r   r   rN   s     rC   rP   zSigCertKeyUsage.__eq__t  sO    uo. >""$(;(;(==>""$(;(;(==	
rB   NN)r:   r;   r<   r=   r   r   rK   r   classmethodr   r	   strr   r   r   rP   rA   rB   rC   r(   r(      s    @ )-(,QH%Q H%Q9& 
 
(  )-(,
CH%
 CH%
 
,%s3x %%s3x %
rB   r(   CNSerialNumberCLSTOOU)z2.5.4.3z2.5.4.5z2.5.4.6z2.5.4.7z2.5.4.8z2.5.4.10z2.5.4.11namec              #      K   | j                   }|D ]G  }|D ]@  }|d   }|d   }|j                  }|rt        j                  ||      }||j                  f B I y w)Ntypevalue)chosendottedname_type_abbrevsgetr   )r   abbreviate_oidsrdnsrdntype_and_valueoidr   keys           rC   x509_name_keyval_pairsr     sp     ![[D $! 
	$N!/!7C #7+E**C'++C5u||##
	$$s   AAT)frozenc                   Z   e Zd ZU dZ ed      Zeed<   	 dZee	e
j                        ed<   	 dZee
j                     ed<   	 dZee	e
j                        ed<   	 dZee   ed<   	  ed	      Zej(                  ed
<   	 dZee	e      ed<   	 ed        Zd Zde
j                  dee   fdZy)r"   z
    This part of the seed value dictionary allows the document author
    to set constraints on the signer's certificate.

    See Table 235 in ISO 32000-1.
    r   flagsNsubjects
subject_dnissuersinfo_urlz/Browserurl_type	key_usagec                    t        |t        j                        r|j                         }	 |d   dk7  rt	        d      	 t        |j                  dd            }|j                  dd      D cg c]+  }t        j                  j                  |j                        - }}|j                  dd      D cg c]+  }t        j                  j                  |j                        - }}d	 }t        j                  j                  |j                  d
d      D 	ci c]#  }|j                         D ]  \  }}	 ||      |	 % c}	}}      }
d }t        |d|      }|j                  d      }|j                  d      }||xs d|
xs d|xs d||d}||||d<    | di |S # t
        $ r Y nw xY wc c}w c c}w c c}	}}w )z
        Read a PDF dictionary into a :class:`.SigCertConstraints` object.

        :param pdf_dict:
            A :class:`~.generic.DictionaryObject`.
        :return:
            A :class:`.SigCertConstraints` object.
        /Type/SVCertz!Object /Type entry is not /SVCert/Ffr   /SubjectrA   /Issuerc                 T    | dd  } t         j                  | j                         |       S )Nr7   )name_type_abbrevs_revr   upper)attrs    rC   format_attrz7SigCertConstraints.from_pdf_object.<locals>.format_attr  s(    8D ),,TZZ\4@@rB   
/SubjectDNc                 R    | D cg c]  }t         j                  |       c}S c c}w rH   )r(   r   )r   kus     rC   parse_key_usagez;SigCertConstraints.from_pdf_object.<locals>.parse_key_usage  s!    FIJO77;JJJs   $	/KeyUsage/URL/URLTypeN)r   r   r   r   r   r   r   )rM   r   IndirectObject
get_objectr   KeyErrorr$   r   r   Certificateloadoriginal_bytesNamebuilditemsr   )r   pdf_dictr   certr   r   r   dn_dirr   r   subject_dnsr   r   urlr   kwargss                   rC   from_pdf_objectz"SigCertConstraints.from_pdf_object  s    h 6 67**,H	 I-"#FGG . 'x||E1'=> !Z4
 !!$"5"56
 
 !Y3
 !!$"5"56
 

	A iioo 'll<< #)<<>  D% D!5(!
	K "(KI	ll6"<<
+ (D%-$"
 ?x3!)F:}V}Y  		

s#   F" /0F250F7(F<"	F/.F/c                    t        j                  t        d      t        d      t        d      t        j                  | j                  j
                        i      }| j                  2t        j                  d | j                  D              |t        d      <   | j                  rst        j                  t        j                  t        | j                  d      D ci c]  \  }}t        d|z         t        |       c}}      g      |t        d	      <   | j                  2t        j                  d
 | j                  D              |t        d      <   | j                  9t        | j                        |t        d      <   | j                  |t        d      <   | j                  2t        j                  d | j                  D              |t        d      <   |S c c}}w )z
        Render this :class:`.SigCertConstraints` object to a PDF dictionary.

        :return:
            A :class:`~.generic.DictionaryObject`.
        r   r   r   c              3   b   K   | ]'  }t        j                  |j                                ) y wrH   r   ByteStringObjectdumpr   r   s     rC   r   z3SigCertConstraints.as_pdf_object.<locals>.<genexpr>  s&      ?:>((5?   -/r   T)r   /r   c              3   b   K   | ]'  }t        j                  |j                                ) y wrH   r   r   s     rC   r   z3SigCertConstraints.as_pdf_object.<locals>.<genexpr>2  s&      >:>((5>r   r   r   r   c              3   N   K   | ]  }t        |j                                 y wrH   )r   r   )r   r   s     rC   r   z3SigCertConstraints.as_pdf_object.<locals>.<genexpr>:  s%      @9;
21134@s   #%r   )r   DictionaryObjectr   NumberObjectr   r   r   ArrayObjectr   r   r   r   r   r   r   )rJ   resultr   r   s       rC   as_pdf_objectz SigCertConstraints.as_pdf_object  s    ))!8I#6!5!5djj6F6F!G
 ==$+2+>+> ?BF--? ,F8J'( ?? .5-@-@,, /E $/ *U %S3Y/E1BB	.F8L)* <<#*1*=*= >BF,,> +F8I&' ==$'1$--'@F8F#$+/==F8J'(>>%,3,?,? @?C~~@ -F8K() -s   "Gsignervalidation_pathc                 `   | j                   }|t        j                  z  rt        d      |t        j                  z  r8| j
                  ,d | j
                  D        }|j                  |vrt        d      |t        j                  z  r| j                  z|t        d      |j                         D ch c](  }t        |t              r|j                  j                  * }}| j                  D ]  }|j                  |v s n t        d      |t        j                  z  r~| j                  rrt!        t#        | j                              }t!        t#        |j$                              t'        fd|D              s"t        d| j                  j(                  z         |t        j*                  z  rg| j,                  Zd	d
lm}	 | j,                  D ]:  }
	  |	|
j3                         |
j5                         d      j7                  |        y t        d      yyc c}w # t8        $ r Y Zw xY w)a  
        Evaluate whether a signing certificate satisfies the required
        constraints of this :class:`.SigCertConstraints` object.

        :param signer:
            The candidate signer's certificate.
        :param validation_path:
            Validation path of the signer's certificate.
        :raises UnacceptableSignerError:
            Raised if the conditions are not met.
        zRCertificate constraint flags include mandatory constraints that are not supported.Nc              3   4   K   | ]  }|j                     y wrH   )issuer_serial)r   ss     rC   r   z2SigCertConstraints.satisfied_by.<locals>.<genexpr>]  s     Aa!//A   z+Signer certificate not on SVCert whitelist.zValidation path not provided.z<Signer certificate cannot be traced back to approved issuer.c              3   &   K   | ]  }|v  
 y wrH   rA   )r   r   subject_names     rC   r   z2SigCertConstraints.satisfied_by.<locals>.<genexpr>  s     It|+Is   zASubject does not have some of the following required attributes: r7   )KeyUsageConstraintsT)r   key_usage_forbiddenmatch_all_key_usageszeThe signer satisfies none of the key usage extension profiles specified in the seed value dictionary.)r   r$   ro   NotImplementedErrorrh   r   r   r   ri   r   iter_authoritiesrM   r   certificaterk   r   listr   subjectallhuman_friendlyrm   r   validation.settingsr   r   r   validater   )rJ   r   r   r   
acceptable	authoritypath_iss_serialsissuerrequirement_listr   r   r   s              @rC   satisfied_byzSigCertConstraints.satisfied_by@  s7   $ 

)555%* 
 *222mm' B4==AJ##:5-A  *111t||7O&-.MNN "1!A!A!C i):; %%33   
 ,, ''+;;
 .  *5554??  $$:4??$KL 6v~~ FGLI8HII-#%)__%C%CD 
 *444nn(@nn 	'"$"2"2"4,.,<,<,>-1	
 hv& .Q  ) 5? X / s   5-H6H!!	H-,H-)r:   r;   r<   r=   r$   r   __annotations__r   r   r   r   r   r   r   r   r   r   r   r   r   
NameObjectr   r(   r   r   r   r   r  rA   rB   rC   r"   r"     s    %;1$=E!= 26HhtD,,-.5 '+J#*
 15GXd4++,-4 #Hhsm" $,J#7Hg  7
 26Ix_-.5 ; ;z.`\  \ ".1\rB   r"   c                   @    e Zd ZdZ ed      Z ed      Z ed      Zy)r%   z=
    Enum declaring all supported ``/SubFilter`` values.
    z/adbe.pkcs7.detachedz/ETSI.CAdES.detachedz/ETSI.RFC3161N)r:   r;   r<   r=   r   ADOBE_PKCS7_DETACHEDPADESETSI_RFC3161rA   rB   rC   r%   r%     s*     $$:;+,EO,LrB   r%   c                   @    e Zd ZdZ ed      Z ed      Z ed      Zy)SigAuthTypezA
    Enum declaring all supported ``/Prop_AuthType`` values.
    PINPasswordFingerprintN)r:   r;   r<   r=   r   r  PASSWORDFINGERPRINTrA   rB   rC   r  r    s'     U
C*%H]+KrB   r  c                        e Zd ZdZdZ	 dZ	 dZy)r&   zU
    Specify the minimal compliance level for a seed value dictionary processor.
    r7   r8   r9   N)r:   r;   r<   r=   PDF_1_5PDF_1_7PDF_2_0rA   rB   rC   r&   r&     s+     G G GrB   r&   c                   D    e Zd ZdZ ed      Z	  ed      Z	  ed      Zy)r'   z
    Provides a recommendation to the signer as to whether the document should
    be locked after signing.
    The corresponding flag in :attr:`.SigSeedValueSpec.flags` determines whether
    this constraint is a required constraint.
    z/truez/falsez/autoN)r:   r;   r<   r=   r   LOCKDO_NOT_LOCKSIGNER_DISCRETIONrA   rB   rC   r'   r'     s;     GD 8$K !)rB   r'   c                   j   e Zd ZU dZ ed      Zeed<   	 dZee	e
      ed<   	 dZee
   ed<   	 dZeed<   	 dZee   ed	<   	 dZee	e      ed
<   	 dZee	e
      ed<   	 dZee   ed<   	 dZee   ed<   	 dZeeedf   ed<   	 dZee	e
      ed<   	 dZee   ed<   	 dZee
   ed<   	 d Zed        Z d Z!y)r#   z?
    Python representation of a PDF seed value dictionary.
    r   r   Nreasonstimestamp_server_urlFtimestamp_requiredr   
subfiltersdigest_methodsadd_rev_infoseed_signature_typesv_dict_versionlegal_attestationslock_document
appearancec                    t         j                  }t        j                  t	        d      t	        d      t	        d      t        j
                  | j                  j                        i      }| j                  2t        j                  d | j                  D              |t	        d      <   | j                  ;t         j                  }t        j                  | j                        |t	        d      <   | j                  It         j                  }t        j                  t        t        | j                              |t	        d      <   | j                   2t        j                  d | j                   D              |t	        d	      <   | j"                  {t         j                  }t        j                  t	        d
      t        | j"                        t	        d      t        j
                  | j$                  rdnd      i      |t	        d      <   | j&                  &| j&                  j)                         |t	        d      <   | j*                  c| j*                  j,                  }t        j                  t	        d      t        j
                  ||j                  nd      i      |t	        d      <   | j.                  2t        j                  d | j.                  D              |t	        d      <   | j0                  2t         j2                  }| j0                  j                  |t	        d      <   | j4                  !t        | j4                        |t	        d      <   | j6                  }|?t        j
                  t9        |t               r|j                  n|      |t	        d      <   |S t        j
                  |j                        |t	        d      <   |S )z
        Render this :class:`.SigSeedValueSpec` object to a PDF dictionary.

        :return:
            A :class:`~.generic.DictionaryObject`.
        r   /SVr   c              3   4   K   | ]  }|j                     y wrH   )r   )r   sfs     rC   r   z1SigSeedValueSpec.as_pdf_object.<locals>.<genexpr>r  s      AAr   
/SubFilter/AddRevInfo/DigestMethodc              3   2   K   | ]  }t        |        y wrH   r   )r   reasons     rC   r   z1SigSeedValueSpec.as_pdf_object.<locals>.<genexpr>  s      ?'-
6"?   /Reasonsr   r7   r   
/TimeStamp/Cert/P/MDPc              3   2   K   | ]  }t        |        y wrH   r0  )r   atts     rC   r   z1SigSeedValueSpec.as_pdf_object.<locals>.<genexpr>  s      H$'
3Hr2  /LegalAttestation/LockDocument/AppearanceFilter/V)r&   r  r   r   r   r   r   r   r   r   r"  r  BooleanObjectr!  mapr   r  r  r  r   r   r#  rF   r%  r&  r  r'  r$  rM   )rJ   min_versionr   rF   specified_versions        rC   r   zSigSeedValueSpec.as_pdf_objectb  s:    +22))!8E?!5!5djj6F6F!G
 ??&-4-@-@ A#'??A .F8L)* (.66K.5.C.C!!/F8M*+ *.66K070C0CJ 3 341F8O,- <<#+2+>+> ?15? ,F8J'( $$0.66K-4-E-EV$j1J1J&KUOW%9%9!44!&.F8L)* 99 (,		(?(?(AF8G$%##///88H'.'?'?TNG$8$8*2*>A%(F8F#$ "".4;4G4G H+/+B+BH 5F8/01 ).66K040B0B0H0HF8O,-??&4>t4OF8/01 00(%,%9%9/1EF "''&&F8D>"  &-%9%9+:K:K%LF8D>"rB   c                    t        |t        j                        r|j                         }	 |d   dk7  rt	        d      	 t        |j                  dd            }	 |d   }|t        j                  z  r|dk7  rt        d|z        	 |d	   }t        j                  j                  }|t        j                  z  r||kD  rt        d
|z        t        |      }	 t        |d         }|j                  dd      d}fd}t         |             }	 |d   D 	cg c]  }	|	j!                          }
}	t#        |dt              }t#        |dt              }d }t#        |d|      }d }t#        |d|      }|j                  dd      }|j                  di       }|j                  dd      }t        |j                  dd            }|j                  dd      }|t$        j'                  |      } | ||||||
|||||||      S # t
        $ r Y w xY w# t
        $ r Y w xY w# t
        $ r d}Y Zw xY w# t
        $ r d}Y ]w xY wc c}	w # t
        $ r d}
Y (w xY w)z
        Read from a seed value dictionary.

        :param pdf_dict:
            A :class:`~.generic.DictionaryObject`.
        :return:
            A :class:`.SigSeedValueSpec` object.
        r   r)  zObject /Type entry is not /SVr   r   z/Filterz/Adobe.PPKLitezVSignature handler '%s' is not available, only the default /Adobe.PPKLite is supported.r=  z/Seed value dictionary version %s not supported.Nr-  r,  c               3   V   K   D ]  } 	 t        |         y # t        $ r Y w xY wwrH   )r%   
ValueError)r   subfilter_reqss    rC   _subfiltersz5SigSeedValueSpec.from_pdf_object.<locals>._subfilters  s9     ' A.q11 & s   ))	&)&)r.  r3  r:  c                     	 | d   }t        |dk(  rd       S t        |            S # t        t        t        f$ r t        d|  d      w xY w)Nr6  r   z/MDP entry z5 in seed value dictionary is not correctly formatted.)rE   r)   r   	TypeErrorrD  r   )mdpr   s     rC   read_mdp_dictz7SigSeedValueSpec.from_pdf_object.<locals>.read_mdp_dict  sa    $i(LLws|LLi4 "!# '+ + s   & & $A
r7  c                 R    	 t        |       S # t        $ r t        d|  d      w xY w)Nz/LockDocument entry 'z' is invalid.)r'   rD  r   )r   s    rC   read_lock_documentz<SigSeedValueSpec.from_pdf_object.<locals>.read_lock_document  s9    O',, O"%:3%}#MNNOs   
 &r;  r<  r4  r   r5  )r   r  r  r   r   r!  r"  r  r%  r#  r$  r&  r'  )rM   r   r   r   r   r   r!   r   r^   r   r&   r  r   r`   rU   r   lowerr   r"   r   )r   r   r   
sig_filterr@  	supportedr"  r   rF  r   r!  r  r%  rJ  signature_typerL  r&  appearance_filtertimestamp_dictr  r  cert_constraintsrE  s                         @rC   r   z SigSeedValueSpec.from_pdf_object  s    h 6 67**,H	 E)"#BCC *
  UA 67
	!),J.....";=GH 
	"4.K,44::I((([9-D"E!"  /{;K	  78L "lD9
% km,J	"19/1JKAaggiKNK  *d;*85H$O	 'xG	O &o'9
 %LL)<dC!lB7-11&$?!."4"4UA">?#<<6'1AA   !5!!)%11 .''(
 	
i  		  		  	K	
  	 L	 " L 	"!N	"sl   H +H 	AH% H7 I I	2I 	HH	H"!H"%H43H47II	I IIc                 L    ddl m} | j                  r || j                        S y)z
        Return a timestamper object based on the :attr:`timestamp_server_url`
        attribute of this :class:`.SigSeedValueSpec` object.

        :return:
            A :class:`~.pyhanko.sign.timestamps.HTTPTimeStamper`.
        r   )HTTPTimeStamperN)pyhanko.sign.timestampsrU  r  )rJ   rU  s     rC   build_timestamperz"SigSeedValueSpec.build_timestamper   s&     	<$$"4#<#<== %rB   )"r:   r;   r<   r=   r!   r   r  r  r   r   r   r  r  rU   r   r"   r   r%   r!  r"  r#  rE   r$  r   r&   r   r%  r&  r'   r'  r   r   r   rW  rA   rB   rC   r#   r#     sb    -Q/E?/ $(GXd3i ' +/(3-.  %$
 *.D(%
&- 48J./07 +/NHT#Y'. $(L(4.'
 8<"34;	 ?COU/d:;B /3c+2& 15M8,-4 !%J$
IV p
 p
d>rB   r#   c                   D    e Zd ZdZ ed      Z	  ed      Z	  ed      Zy)r*   z9
    Marker for the scope of a ``/FieldMDP`` policy.
    z/Allz/Includez/ExcludeN)r:   r;   r<   r=   r   ALLINCLUDEEXCLUDErA   rB   rC   r*   r*   .  s:     6
C z"G z"GrB   r*   c                       e Zd ZU dZeed<   	 dZeee	      ed<   	 de
j                  fdZde
j                  fdZde
j                  fdZedd	       Zd
e	defdZy)r+   z``/FieldMDP`` policy description.

    This class models both field lock dictionaries and ``/FieldMDP``
    transformation parameters.
    actionNfieldsrQ   c                    t        j                  t        d      | j                  j                  i      }| j                  t
        j                  k7  r4t        j                  t        t        | j                  xs d            |d<   |S )z
        Render this ``/FieldMDP`` policy description as a PDF dictionary.

        :return:
            A :class:`~.generic.DictionaryObject`.
        /ActionrA   /Fields)r   r   r   r]  r   r*   rY  r   r?  r   r^  rJ   r   s     rC   r   zFieldMDPSpec.as_pdf_objectW  sp     ))#T[[%6%6

 ;;.,,, ' 3 3J 1r2!F9 rB   c                 ^    | j                         }t        d      |d<   t        d      |d<   |S )a"  
        Render this ``/FieldMDP`` policy description as a PDF dictionary,
        ready for inclusion into the ``/TransformParams`` entry of a
        ``/FieldMDP`` dictionary associated with a signature object.

        :return:
            A :class:`~.generic.DictionaryObject`.
        z/TransformParamsr   z/1.2r=  r   r   rb  s     rC   as_transform_paramsz FieldMDPSpec.as_transform_paramsi  s4     ##%"#56w'trB   c                 B    | j                         }t        d      |d<   |S )z
        Render this ``/FieldMDP`` policy description as a PDF dictionary,
        ready for inclusion into the ``/Lock`` dictionary of a signature field.

        :return:
            A :class:`~.generic.DictionaryObject`.
        z/SigFieldLockr   rd  rb  s     rC   as_sig_field_lockzFieldMDPSpec.as_sig_field_lockx  s%     ##%"?3wrB   c                     	 t        |d         }|t         j                  k7  r	 |d   }nd} | ||      S # t        $ r t        d      w xY w# t        $ r t        d      w xY w)z
        Read a PDF dictionary into a :class:`.FieldMDPSpec` object.

        :param pdf_dict:
            A :class:`~.generic.DictionaryObject`.
        :return:
            A :class:`.FieldMDPSpec` object.
        r`  z/Action is required.ra  z,/Fields is required when /Action is not /AllN)r]  r^  )r*   r   r   rY  )r   r   r]  r^  s       rC   r   zFieldMDPSpec.from_pdf_object  s    	7#HY$78F ^'''!), F&00  	7566	7  "B s   6 A AA#
field_namec                     | j                   t        j                  k(  ry| j                   t        j                  k(  }| j                  xs dD ]  }|j                  |      s|c S  | S )a   
        Adjudicate whether a field should be locked by the policy described by
        this :class:`.FieldMDPSpec` object.

        :param field_name:
            The name of a form field.
        :return:
            ``True`` if the field should be locked, ``False`` otherwise.
        TrA   )r]  r*   rY  rZ  r^  
startswith)rJ   ri  lock_resultscoped_field_names       rC   	is_lockedzFieldMDPSpec.is_locked  sg     ;;.,,,kk^%;%;;!%!2 	# $$%67""		#
 rB   )rQ   r+   )r:   r;   r<   r=   r*   r  r^  r   r   r   r   r   r   re  rg  r   r   rU   rn  rA   rB   rC   r+   r+   D  s      #'FHT#Y&
w77 $W%=%= 7#;#;  1 12C D rB   r+   c                   @    e Zd ZU dZdZeed<   	 dZeed<   	 dZeed<   y)r-   a  
    Invisible signature widget generation settings.

    These settings exist because there is no real way of including an untagged
    invisible signature in a document that complies with the requirements
    of both PDF/A-2 (or -3) and PDF/UA-1.

    Compatibility with PDF/A (the default) requires the print flag to be set.
    Compatibility with PDF/UA requires the hidden flag to be set (which is
    banned in PDF/A) or the box to be outside the crop box.
    Tset_print_flagFset_hidden_flagbox_out_of_boundsN)	r:   r;   r<   r=   rp  rU   r  rq  rr  rA   rB   rC   r-   r-     s;    
  ND "OT! $t#rB   r-   c                   @    e Zd ZU dZdZeed<   	 dZeed<   	 dZeed<   y)r.   zh
    .. versionadded:: 0.14.0

    Additional flags used when setting up visible signature widgets.
    Trotate_with_pagescale_with_page_zoomprint_signatureN)	r:   r;   r<   r=   rt  rU   r  ru  rv  rA   rB   rC   r.   r.     s<     "d! "&$% !OT rB   r.   c                   $   e Zd ZU dZeed<   	 dZeed<   	 dZe	e
eeeef      ed<   	 dZe	e   ed<   	 dZe	e   ed<   	 dZe	e   ed	<   	 d
Zeed<   	 dZeed<   	  e       Zeed<   	 dZe	e   ed<   	  e       Zeed<   	 de	ej4                     fdZy)r    z/Description of a signature field to be created.sig_field_namer   on_pageNboxseed_value_dictfield_mdp_specdoc_mdp_update_valueTcombine_annotationFempty_field_appearanceinvis_sig_settingsreadable_field_namevisible_sig_settingsrQ   c                     | j                   y | j                   j                         }| j                  ,t        j                  | j                  j
                        |d<   |S )Nr6  )r|  rg  r}  r   r   r   rb  s     rC   format_lock_dictionaryz#SigFieldSpec.format_lock_dictionaryZ  sX    &$$668 $$0"//0I0I0O0OPF4LrB   )r:   r;   r<   r=   r   r  ry  r   rz  r   r
   r{  r#   r|  r+   r}  r)   r~  rU   r  r-   r  r  r.   r  r   r   r  rA   rB   rC   r    r      s   9 GS	 04C%S#s*+	,3 37OX./6 .2NH\*1 /3(7+2  $#
 $)D( ,<+=(= *.#- 0B/C,C1I1I(J rB   r    writerc                 $   |d   |dd  }}|D ]E  }t        |t        j                        sJ |j                         }	|	j	                  dd       |k(  sE nf ||s|}	nt        j
                         }	t        |      |	d<   |||	d<   | j                  |	      }|j                  |       | j                  |       d}|s||fS 	 |	d   }
t        | |
||||      S # t        $ r/ t        j                         x}
|	d<   | j                  |	       d}Y Hw xY w)Nr   r7   /Tz/ParentT/Kids)
parent_refmodified	field_obj)rM   r   r   r   r   r   r   
add_objectappendupdate_containerr   r   _insert_or_get_field_at)r  r^  pathr  r  r  current_partialtail	field_reffieldkidss              rC   r  r  e  sD    !GT!"XTO 	)W%;%;<<<$$&99T4 O3	  E ,,.E 1d!)E)%%e,	i '""W~ #    ' 3 3 55uW~&s   C 5DDlock_sig_flagsc                    | j                   d   }|rB|j                  dd      }t        j                  d      |d<   |dk7  r| j	                  |       yy|j                  t        d      t        j                  d             y)z
    Ensure the SigFlags setting is present in the AcroForm dictionary.

    :param writer:
        A PDF writer.
    :param lock_sig_flags:
        Whether to flag the document as append-only.
    	/AcroFormz	/SigFlagsNr9   r7   )rootr   r   r   r  
setdefaultr   )r  r  formorig_sig_flagss       rC   r1   r1     su     ;;{#D+t4#003[Q##D)  	-w/C/CA/FGrB   update_writerc                 2   	 |d   }	 |d   }t        || t	                     }d}	 t        |      \  }	}
}|
t        d| z        	 d}|d|fS |j                  d
      d
   }d|i} |j                  di | t        | fi |}t        ||| j!                  d      |      \  }}|j#                  ||       |s|j%                  |       d	|fS # t         $ r t        j                         x}|d<   Y w xY w# t        $ r |rt        d| z        Y w xY w# t         $ rx |rt        d      t        j                         }|j                  |      |t        d      <   t        j                         }||t        d      <   |j                          d	}d}Y Mw xY w)z
    Returns a tuple of a boolean and a reference to a signature field.
    The boolean is ``True`` if the field was created, and ``False`` otherwise.

    .. danger::
        This function is internal API.
    r  ra  )	with_name	refs_seenNz:Signature field with name %s appears to be filled already.z,No empty signature field with name %s found.Fz"This file does not contain a form.Tr   include_on_page.)r  r  rA   )r   r   r   enumerate_sig_fields_inrt   nextr   StopIterationr   r  r   update_rootfind_page_for_modificationupdater,   r  splitregister_widget_annotationr  )rx  r  r  existing_fields_onlyr   r  r^  
candidatessig_field_refri  r   form_createdpage_refsig_form_kwargs	sig_fieldcreateds                   rC   r2   r2     s   &K 	=)_F -n

 	/3J/?,J} "P$%  !   m## 77:1=H((3OO$V$">E_EI4!!#&	G] ((F &&v.o  	='.':':'<<FT)_	=  	#"B$%  $	  CDD'')&3&>&>t&DXk"#$$&$*Xi !!!#sW   D C D C6 D "C30D 2C33D 6DD DD A=FFr  rQ   c                     	 | d   \  }|j                         }|S # t        t        f$ r t        d      t        $ r | }Y |S w xY w)z
    Internal function to get the annotation of a signature field.

    :param sig_field:
        A signature field dictionary.
    :return:
        The dictionary of the corresponding annotation.
    r  zFailed to access signature field's annotation. Signature field must have exactly one child annotation, or it must be combined with its annotation.)r   rD  rH  r   r   )r  	sig_annots     rC   r5   r5     sf    
 )((*	  	" 
:
 	

  	s    $AA
annot_dictc                 v    	 | d   \  }}}}t        ||z
        }t        ||z
        }||fS # t         $ r Y yw xY w)z
    Internal function to compute the width and height of an annotation.

    :param annot_dict:
        Annotation dictionary.
    :return:
        a (width, height) tuple
    /Rect)r   r   )r   abs)r  x1y1x2y2whs          rC   r4   r4     sR    #G,BB 	BGABGAa4K	  s   
, 	88handlerfilled_statusr  c              #      K   	 | j                   d   d   }t        |||t                     E d{    y# t        $ r Y yw xY w7 w)a  
    Enumerate signature fields.

    :param handler:
        The :class:`~.rw_common.PdfHandler` to operate on.
    :param filled_status:
        Optional boolean. If ``True`` (resp. ``False``) then all filled
        (resp. empty) fields are returned. If left ``None`` (the default), then
        all fields are returned.
    :param with_name:
        If not ``None``, only look for fields with the specified name.
    :return:
        A generator producing signature fields.
    r  ra  N)r  r  r  )r  r   r  rt   )r  r  r  r^  s       rC   r/   r/   *  sY     (k*95 '#%	    s.   A6 AAA	AAAAc          
   #     K   t        | t        j                        s#t        j	                  dt        |        d       y |xs d}| D ]d  }t        |t        j                        st        j	                  d       4|j                  |v rt        d      |j                         }t        |t        j                        s#t        j	                  dt        |       d       	 |d   }|s|n|d	|}	|d uxr |	|k(  }
|
xs |d uxr |j                  |	      }|f|z   }|D ]	  }	 |d
   } n d }|dk(  r4|j                  d      }|d u}|d u xs ||k(  }|d u xs |
}|r|r|	||f n|
rt        d|	z        ||s6|
r:	 t        |d   |	|||||j                  hz        E d {    g y # t        $ r Y uw xY w# t        $ r Y w xY w7 '# t        $ r Y w xY ww)NzValues of type zA are not valid as field lists, must be array objects -- skipping.rA   z>Entries in field list must be indirect references -- skipping.zCircular reference in form treez6Entries in field list must be dictionary objects, not z -- skipping.r  r  /FT/Sigr=  z6Field with name %s exists but is not a signature fieldr  )parent_nameparentsr  r  r  )rM   r   r   loggerwarningr   r   	referencer   r   r   r   rk  r   r   r  )
field_listr  r  r  r  r  r  r  ri  fq_nameexplicitly_requestedchild_requestedcurrent_pathparent_field
field_typefield_valuefilledstatus_check
name_checks                      rC   r  r  K  si     j'"5"56d:./ 08 9	
 	mG D	)W%;%;<NNP )+@AA$$&%!9!9:NNH;-}. 	tJ
  (*5 	
  )4MI9M. 
T!Ci&:&:7&C 	 x')( 	L)%0
	 J))D/K ,F(D0KFm4KL"d*B.BJ
{I55!H  9M
2'N '('"/'9+>+>*??  wD(  		"  ,  s   C G"#F1(<G"%G*AG">G"%G(G)G-G"1	F>:G"=F>>G"	G
G"GG"G	GG"GG"pdf_outsig_field_specc                 b   | j                   }| j                  |j                        d   }t        |j                  || d|j
                  ||j                  |j                  |j                  	      \  }}t        | d       |st        d|j                  z        |j                         }t        | ||       |j
                  |j
                  \  }}}	}
t        |	|z
        }t        |
|z
        }|r|rt        j                         x|t!        d      <   }|j"                  rFd	d
||fz  d||fz  dg}t%        dj'                  |      t)        ||            j+                         }n&t%        dt)        ||            j+                         }| j-                  |      |t!        d      <   yyyy)z
    Append signature fields to a PDF file.

    :param pdf_out:
        Incremental writer to house the objects.
    :param sig_field_spec:
        A :class:`.SigFieldSpec` object describing the signature field
        to add.
    r   F)r  r  rz  r  r~  invis_settingsvisible_settings)r  r  z,Signature field with name %s already exists.)r  r  Nz/AP   qs$   q 0.95 0.95 0.95 rg 0 0 %g %g re f Qs   0.5 w 0 0 %g %g re S   Q    )widthheight)rz  rB   z/N)r  r  ry  r2   rx  rz  r~  r  r  r1   r   r   r3   r  r   r   r   r  r   r   r   as_form_xobjectr  )r  r  r  r  field_createdr  r  llxllyurxuryr  r  ap_dictappearance_cmds	ap_streams                   rC   r0   r0     s    <<D11.2H2HI!LH#4%%" )<<%88'<<
$ M= GE::++,
 	

 ((*I#9^ %+//S#sc	Nc	N3:3K3K3MMIhuo&44 ;q!fD+q!f4# 'IIo.&Qq9 "/# 
 '^!A>!/#  '.&8&8&CGHTN#) 1	 &rB   c                 X   |j                   +t        j                  |j                         |t        d      <   |j                  7| j                  |j                  j                               }||t        d      <   |j                         }|| j                  |      |t        d      <   yy)zT
    Internal function to apply field spec properties to a newly created field.
    Nz/TUr)  z/Lock)r  r   TextStringObjectr   r{  r  r   r  )r  r  r  sv_reflocks        rC   r3   r3     s     ))5%,%=%=..&
	(5/" %%1##**88:
 &,	(5/"002D'.'9'9$'?	(7#$ rB   c                   X     e Zd Zddd e        e       dddedef fdZdefdZ xZS )	r,   NT)rz  r  r~  r  r  annot_flagsr  r  c                @   |W|D cg c]   }t        j                  t        |            " }	}t        |d   |d   z
        xr t        |d   |d   z
         }
n+|j                  rdnd}t        j                  |      gdz  }	d}
t
        |   t        d      t        d	      t        d
      t        |      i       || _	        |r| }nt        j                         }t        d      |d<   t        d      |d<   |Zd}|
r#|j                  r|dz  }|j                  r9|dz  }n3|j                  r|dz  }|j                  s|dz  }|j                  s|dz  }t        j                   |      |d<   t        j"                  |	      |d<   || _        |||d<   || _        y c c}w )Nr   r8   r7   r9   irW   Tr  r  r  z/Annotr   z/Widgetz/Subtyper\   rX   rY   z/Fr  r6  )r   FloatObjectr   r  rr  superrK   r   r   r~  r   rq  rp  rv  ru  rt  r   r   r  r  )rJ   ri  rz  r  r~  r  r  r  xrect	invisiblecoordr  	__class__s                rC   rK   zSignatureFormField.__init__  s    ?8;<1G''1.<D< Q#a&1Jc#a&3q6/6JKI+==E1E''./!3DI &!1
: 6	
 #5J 113J 'x0
7!))!4
:$K!114'K!005(K#335(K'<<6)K'887*K"//<
4%11$7
7'&.Jt$c =s   %Fr  c                     | j                   }| j                  s+|j                  |      }t        j                  |g      | d<   n|}|j                  | j                  |       y )Nr  )r  r~  r  r   r   register_annotationr  )rJ   r  r  r  	annot_refs        rC   r  z-SignatureFormField.register_widget_annotation=  sU     __
&&))*5I#//<DM%I""4==)<rB   )	r:   r;   r<   r-   r.   rK   r   r  __classcell__)r  s   @rC   r,   r,     sD    
 +;+=/A/C=% )=% -=%~	='	=rB   r,   )F)NFN)Tr   )NNr}   N)Vr=   loggingdataclassesr   enumr   r   r   typingr   r   r	   r
   r   
asn1cryptor   asn1crypto.x509r   pyhanko_certvalidator.authorityr   pyhanko_certvalidator.errorsr   pyhanko_certvalidator.pathr   pyhanko.pdf_utilsr   pyhanko.pdf_utils.contentr   pyhanko.pdf_utils.genericr   r   pyhanko.pdf_utils.layoutr   pyhanko.pdf_utils.miscr   r   r   r   r   r   pyhanko.pdf_utils.rw_commonr   pyhanko.pdf_utils.writerr   pyhanko.sign.generalr   r   __all__	getLoggerr:   r  r)   rE   r!   r$   r(   r   r   r   r   r   r"   r%   r  r&   r'   r#   r*   r+   r-   r.   r    r  rU   r1   r2   r   r5   floatr4   r   r/   r  r0   r3   r,   )kvs   00rC   <module>r     sg    ! # # 4 4  $ = @ 5 % 0 : 3  3 6 F2 
		8	$k <) )8Kd K\5T 5py
 y
z   +<*A*A*CD$!QAD $ $" $A A AH -t - - ,$ , , ;  * t  6 $C> C> C>L
T , $m m m` $     F $  D $e e eX 00fH. H H6 	K %K\''2((
5%<, %)#D> }F Up>D>D0<>DB@@''@ !@2I=11 I=o+ Es   )I5