
    k7iKw                        S SK Jr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SK	J
r
  S SK	Jr  S S	K	Jr  S S
K	Jr  S SK	Jr  S SK	Jr  S SK	Jr  S SK	Jr  S SK	Jr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr  S SKJr   " S S5      rS rg)    )OrderedDict)deepcopy)json_b64encode)to_bytes)
to_unicode)urlsafe_b64encode)DecodeError))InvalidAlgorithmForMultipleRecipientsMode)InvalidHeaderParameterNameError)KeyMismatchError)MissingAlgorithmError)MissingEncryptionAlgorithmError)UnsupportedAlgorithmError)$UnsupportedCompressionAlgorithmError)#UnsupportedEncryptionAlgorithmError)$JWEAlgorithmWithTagAwareKeyAgreement)	JWEHeader)JWESharedHeaderensure_dict)extract_header)extract_segmentc                       \ rS rSr\" / SQ5      r0 r0 r0 rSS jr	\
S 5       rSS jrSS jrSS jrSS	 jrSS
 jrSS jr\S 5       rS rS rS rS rS rSrg)JsonWebEncryption   )algenczipjkujwkkidx5ux5cx5tzx5t#S256typctycritNc                     Xl         X l        g N_algorithms_private_headers)self
algorithmsprivate_headerss      R/home/james-whalen/.local/lib/python3.13/site-packages/authlib/jose/rfc7516/jwe.py__init__JsonWebEncryption.__init__1   s    % /    c                 F   U(       a  UR                   S:w  a  [        SU< 35      eUR                  S:X  a  XR                  UR                  '   gUR                  S:X  a  XR
                  UR                  '   gUR                  S:X  a  XR                  UR                  '   gg)z?Register an algorithm for ``alg`` or ``enc`` or ``zip`` of JWE.JWEzInvalid algorithm for JWE, r   r   r   N)algorithm_type
ValueErroralgorithm_locationALG_REGISTRYnameENC_REGISTRYZIP_REGISTRY)cls	algorithms     r0   register_algorithm$JsonWebEncryption.register_algorithm5   s     I44=:9-HII''50/8Y^^,))U2/8Y^^,))U2/8Y^^, 3r3   c           	         U R                  U5      nU R                  U5      nU R                  U5      nU R                  XE5        U R	                  X5        [        XQU5      nUb  UR                  U5      n[        U[        5      (       a>  UR                  b1  UR                  XcU5      nUS   n	US   n
UR                  US   5        O^[        U[        5      (       a  UR                  XaX45      nOUR                  XaU5      nUS   n
US   nSU;   a  UR                  US   5        UR                  5       n[        U5      n[        US5      nU(       a  UR                  [        U5      5      nO[        U5      nUR!                  UXU
5      u  nn[        U[        5      (       a'  UR                  b  UR#                  XaX4W	U
U5      nUS   nSR%                  U['        W5      ['        U5      ['        U5      ['        U5      /5      $ )a^  Generate a JWE Compact Serialization.

The JWE Compact Serialization represents encrypted content as a compact,
URL-safe string. This string is::

    BASE64URL(UTF8(JWE Protected Header)) || '.' ||
    BASE64URL(JWE Encrypted Key) || '.' ||
    BASE64URL(JWE Initialization Vector) || '.' ||
    BASE64URL(JWE Ciphertext) || '.' ||
    BASE64URL(JWE Authentication Tag)

Only one recipient is supported by the JWE Compact Serialization and
it provides no syntax to represent JWE Shared Unprotected Header, JWE
Per-Recipient Unprotected Header, or JWE AAD values.

:param protected: A dict of protected header
:param payload: Payload (bytes or a value convertible to bytes)
:param key: Public key used to encrypt payload
:param sender_key: Sender's private key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: JWE compact serialization as bytes
epkcekheaderekascii   .)get_header_algget_header_encget_header_zip_validate_sender_key_validate_private_headersprepare_key
isinstancer   key_size!generate_keys_and_prepare_headersupdatewrapgenerate_ivr   r   compressencryptagree_upon_key_and_wrap_cekjoinr   )r-   	protectedpayloadkey
sender_keyr   r   zip_algpreprB   rC   wrappedrE   ivprotected_segmentaadmsg
ciphertexttags                      r0   serialize_compact#JsonWebEncryption.serialize_compactB   s    0 !!),!!),%%i0!!*2&&y6##.!4J s@AA( 88:NDu+Cu+CT(^, #CDD((33C((337%.CB7"  !23 __ +95('2 ""8G#45C7#C ++c3C8
C s@AA(
 55c3G B yy!!"%!"%!*-!#&
 	
r3   c           
      
   [        U[        5      (       d  U/nU(       d  [        S5      e[        U5      n[        R
                  " U5      nUR                  S5      nUc  U Vs/ s H  n0 PM     nn[        [        U5      5       H  nXh   c  0 Xh'   SXh   ;  d  M  0 Xh   S'   M     UR                  S5      n	[        U5      [        U5      :w  a#  [        S[        U5       S[        U5       35      eU R                  U5      n
U R                  U5      nU R                  U5      nU R                  XJ5        U R                  XZ5        U H  nU R                  US   U
5        M     [        [        U5      5       H  n[        XU   S   X8   5      X8'   M     Ub  U
R                  U5      nU
R                  XS   5      nS	U;   a  US	   nOSn[        U5      S
:  a  Uc  [!        U
R"                  5      eSU;   a  UR%                  US   5        [        U
[&        5      (       au  U
R(                  bh  / n[        [        U5      5       HM  nU
R+                  XU   XN5      nUc  US	   nUR-                  US   5        Xh   S   R/                  US   5        MO     O[        [        U5      5       Hv  n[        U
[&        5      (       a  U
R1                  XX8   XN5      nOU
R1                  XX8   U5      nUc  US	   nUS   Xh   S'   SU;   d  M]  Xh   S   R/                  US   5        Mx     UR3                  5       nUR4                  (       a  [7        UR4                  5      OSnU	b  US[9        U	5      -   -  n[;        US5      nU(       a  UR=                  [;        U5      5      nO[;        U5      nUR?                  UUUU5      u  nn[        U
[&        5      (       aM  U
R(                  b@  [        [        U5      5       H(  nU
RA                  XX8   UWU   UU5      nUS   Xh   S'   M*     [C        5       nUR4                  (       a!  [E        [7        UR4                  5      5      US'   URF                  (       a  URF                  US'   U HU  nUS   (       d  US	 [E        [9        US   5      5      US'   [I        URK                  5       5       H  nUS;  d  M  UU	 M     MW     UUS'   U	b  [E        [9        U	5      5      US'   [E        [9        U5      5      US'   [E        [9        U5      5      US'   [E        [9        U5      5      US'   U$ s  snf )a   Generate a JWE JSON Serialization (in fully general syntax).

The JWE JSON Serialization represents encrypted content as a JSON
object.  This representation is neither optimized for compactness nor
URL safe.

The following members are defined for use in top-level JSON objects
used for the fully general JWE JSON Serialization syntax:

protected
    The "protected" member MUST be present and contain the value
    BASE64URL(UTF8(JWE Protected Header)) when the JWE Protected
    Header value is non-empty; otherwise, it MUST be absent.  These
    Header Parameter values are integrity protected.

unprotected
    The "unprotected" member MUST be present and contain the value JWE
    Shared Unprotected Header when the JWE Shared Unprotected Header
    value is non-empty; otherwise, it MUST be absent.  This value is
    represented as an unencoded JSON object, rather than as a string.
    These Header Parameter values are not integrity protected.

iv
    The "iv" member MUST be present and contain the value
    BASE64URL(JWE Initialization Vector) when the JWE Initialization
    Vector value is non-empty; otherwise, it MUST be absent.

aad
    The "aad" member MUST be present and contain the value
    BASE64URL(JWE AAD)) when the JWE AAD value is non-empty;
    otherwise, it MUST be absent.  A JWE AAD value can be included to
    supply a base64url-encoded value to be integrity protected but not
    encrypted.

ciphertext
    The "ciphertext" member MUST be present and contain the value
    BASE64URL(JWE Ciphertext).

tag
    The "tag" member MUST be present and contain the value
    BASE64URL(JWE Authentication Tag) when the JWE Authentication Tag
    value is non-empty; otherwise, it MUST be absent.

recipients
    The "recipients" member value MUST be an array of JSON objects.
    Each object contains information specific to a single recipient.
    This member MUST be present with exactly one array element per
    recipient, even if some or all of the array element values are the
    empty JSON object "{}" (which can happen when all Header Parameter
    values are shared between all recipients and when no encrypted key
    is used, such as when doing Direct Encryption).

The following members are defined for use in the JSON objects that
are elements of the "recipients" array:

header
    The "header" member MUST be present and contain the value JWE Per-
    Recipient Unprotected Header when the JWE Per-Recipient
    Unprotected Header value is non-empty; otherwise, it MUST be
    absent.  This value is represented as an unencoded JSON object,
    rather than as a string.  These Header Parameter values are not
    integrity protected.

encrypted_key
    The "encrypted_key" member MUST be present and contain the value
    BASE64URL(JWE Encrypted Key) when the JWE Encrypted Key value is
    non-empty; otherwise, it MUST be absent.

This implementation assumes that "alg" and "enc" header fields are
contained in the protected or shared unprotected header.

:param header_obj: A dict of headers (in addition optionally contains JWE AAD)
:param payload: Payload (bytes or a value convertible to bytes)
:param keys: Public keys (or a single public key) used to encrypt payload
:param sender_key: Sender's private key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: JWE JSON serialization (in fully general syntax) as dict

Example of `header_obj`::

    {
        "protected": {
            "alg": "ECDH-1PU+A128KW",
            "enc": "A256CBC-HS512",
            "apu": "QWxpY2U",
            "apv": "Qm9iIGFuZCBDaGFybGll",
        },
        "unprotected": {"jku": "https://alice.example.com/keys.jwks"},
        "recipients": [
            {"header": {"kid": "bob-key-2"}},
            {"header": {"kid": "2021-05-06"}},
        ],
        "aad": b"Authenticate me too.",
    }
zNo keys have been provided
recipientsNrD   ra   zCount of recipient keys z' does not equal to count of recipients r   rC      rB   rE   encrypted_keyr3   rG   rF   rX   unprotected>   rD   rj   r_   rc   rd   )&rN   listr7   r   r   	from_dictgetrangelenrH   rI   rJ   rK   rL   rM   generate_presetr
   r:   update_protectedr   rO   rP   appendrQ   rR   rS   rX   r   r   r   rT   rU   rV   r   r   rk   setkeys)r-   
header_objrY   ru   r[   shared_headerrh   _ijwe_aadr   r   r\   	recipientpresetrC   epksr]   r^   r_   ra   rb   rc   rd   objmembers                             r0   serialize_json JsonWebEncryption.serialize_json   s   @ $%%6D9::j)
'11*=^^L1
&*+d"dJ+s:'A}$ "
z},*,
h'	 ( ..'t9J'*3t9+5\]`ak]l\mn 
 !!-0!!-0%%m4!!*2&&}:#I**9X+>D $ s4y!A!#!}X'>HDG "!4J $$Sq'2F?-CCt9q=S[;CHHEEv**6(+;< s@AA(
 D3t9%<<a* ;u+CDK(h'..tH~> & 3t9%c#GHH!hhs47JWG!hhs47FKG;!%.C18
o.w&M(+22783DE & __ 8E7N7NN=223TW 	 4+G444CsG$ ""8G#45C7#C ++c3C8
C s@AA(
 3t9%99T!Wc3 29
o.	 & m"").9P9P*QRC$$!.!:!:C#IX&h')3!)O"<=*Io& inn./!<<!&) 0 $ 'L#$5g$>?CJ045D	&'8'DEL 1# 67E

a ,s   $Uc                 n    SU;   d  SU;   d  SU;   a  U R                  XX45      $ U R                  XX45      $ )ab  Generate a JWE Serialization.

It will automatically generate a compact or JSON serialization depending
on `header` argument. If `header` is a dict with "protected",
"unprotected" and/or "recipients" keys, it will call `serialize_json`,
otherwise it will call `serialize_compact`.

:param header: A dict of header(s)
:param payload: Payload (bytes or a value convertible to bytes)
:param key: Public key(s) used to encrypt payload
:param sender_key: Sender's private key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: JWE compact serialization as bytes or
    JWE JSON serialization as dict
rX   rk   rh   )r   re   )r-   rD   rY   rZ   r[   s        r0   	serializeJsonWebEncryption.serialize  s@      & MV$;|v?U&&vHH%%fsGGr3   c                     [        U5      nUR                  S5      u  pVpxn	[	        U[        5      n[        U[        S5      n[        U[        S5      n[        U[        S5      n[        U	[        S5      nU R                  U5      nU R                  U5      nU R                  U5      nU R                  UU5        U R                  UU5        [        U[        5      (       a  [        U5      S:X  a  US	   n[        UX5      nUb  UR                  U5      n[        U[        5      (       a6  UR                   b  UR#                  UXX$U5      nO'UR#                  UXX$5      nOUR#                  UXU5      n[        US
5      nUR%                  UUXU5      nU(       a  UR'                  [        U5      5      nOUnU(       a  U" U5      nUUS.$ ! [         a  n
[        S5      U
eSn
A
ff = f)a  Extract JWE Compact Serialization.

:param s: JWE Compact Serialization as bytes
:param key: Private key used to decrypt payload
    (optionally can be a tuple of kid and essentially key)
:param decode: Function to decode payload data
:param sender_key: Sender's public key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: dict with `header` and `payload` keys where `header` value is
    a dict containing protected header fields
rG   zNot enough segmentsNzencryption keyinitialization vectorrc   authentication tag   ri   rF   rD   rY   )r   rsplitr7   r	   r   r   rH   rI   rJ   rK   rL   rN   tuplerp   rM   r   rO   unwrapdecrypt
decompress)r-   srZ   decoder[   protected_sek_siv_sciphertext_stag_sexcrX   rE   r_   rc   rd   r   r   r\   rC   ra   rb   rY   s                          r0   deserialize_compact%JsonWebEncryption.deserialize_compact  s   	>A;<88D>8Kt5 #;<	T;0@AT;0GH$\;M
e[2FG!!),!!),%%i0!!*c2&&y#6c5!!c#h!ma&C#y.!4Jc?@@||' jjbScJ jjbSE **S"5C{G,kk*c2C8((#7GGWoG#88c  	>34#=	>s    G 
G'G""G'c                   ^^^^^^^^^ [        US5      n[        U5      nSU;   a  [        [        US   5      [        5      mOSmUR                  S5      mUS   mT H.  nSU;  a  0 US'   [        [        US   5      [        S5      US'   M0     S	U;   a  [        [        US	   5      [        S
5      nOSn[        [        US   5      [        S5      n[        [        US   5      [        S5      n[        [        US   5      [        S5      m[        TT5      n	U R                  U	5      mU R                  U	5      mU R                  U	5      n
U R                  TT5        U R                  U	T5        T H  nU R                  US   T5        M     Sm[        T[        5      (       a  [        T5      S:X  a
  TS   mTS   mTR!                  T5      mTc  TR"                  mTb  TR!                  T5      mUUUUU4S jnUUUU4S jnUUU4S jnUUUU4S jn[        T[$        5      (       a  TR&                  b	  U" U5      nOU" U5      nOU" U5      n[        UR                  SS5      5      nS	U;   a  US[        US	   5      -   -  n[        US5      nTR)                  UUUTU5      nU
(       a  U
R+                  [        U5      5      nOUnU(       a  U" U5      nT H;  nUS   (       d  US	 [-        UR/                  5       5       H  nUS:w  d  M  UU	 M     M=     0 nT(       a  TUS'   T(       a  TUS'   TUS'   Ub  UUS	'   UUS.$ )a  Extract JWE JSON Serialization.

:param obj: JWE JSON Serialization as dict or str
:param key: Private key used to decrypt payload
    (optionally can be a tuple of kid and essentially key)
:param decode: Function to decode payload data
:param sender_key: Sender's public key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: dict with `header` and `payload` keys where `header` value is
    a dict containing `protected`, `unprotected`, `recipients` and/or
    `aad` keys
r5   rX   Nrk   rh   rD   rj   zencrypted keyra   zJWE AADr_   r   rc   rd   r   r   r   ri   c                 .   > TR                  TXTTT5      $ r)   r   )rE   rD   r   r   rZ   r[   rd   s     r0   _unwrap_with_sender_key_and_tagKJsonWebEncryption.deserialize_json.<locals>._unwrap_with_sender_key_and_tagG  s    ::c2sJDDr3   c                 ,   > TR                  TXTT5      $ r)   r   )rE   rD   r   r   rZ   r[   s     r0   '_unwrap_with_sender_key_and_without_tagSJsonWebEncryption.deserialize_json.<locals>._unwrap_with_sender_key_and_without_tagJ  s    ::c2sJ??r3   c                 *   > TR                  TXT5      $ r)   r   )rE   rD   r   r   rZ   s     r0   "_unwrap_without_sender_key_and_tagNJsonWebEncryption.deserialize_json.<locals>._unwrap_without_sender_key_and_tagM  s    ::c2s33r3   c                 *  > Tb?  T H9  nUS   R                  S5      T:X  d  M  [        TTUS   5      nU " US   U5      s  $    S nT H   n[        TTUS   5      n U " US   U5      s  $    Uc
  [        5       eUe! [         a  nUn S nAME  S nAff = f)NrD   r!   rj   )rn   r   	Exceptionr   )	unwrap_funcr{   rD   errorer!   rX   rh   rk   s	        r0   _unwrap_for_matching_recipientJJsonWebEncryption.deserialize_json.<locals>._unwrap_for_matching_recipientP  s    !+I *..u5<!*9k9XCV!W*9_+EvNN ", E'	"9k9X;NO&y'A6JJ ( =*,,K ! Es   A;;
BBB rG   rF   r   )r   r   r   r   r	   rn   r   r   rH   rI   rJ   rK   rL   rN   r   rp   rM   r!   r   rO   r   r   rt   ru   )r-   r~   rZ   r   r[   r{   rz   r_   rc   rw   r\   r   r   r   r   rC   ra   rb   rY   r   rD   r   r   r!   rX   rh   rd   rk   s     ` `                @@@@@@@r0   deserialize_json"JsonWebEncryption.deserialize_json  sL    #u%sm#&xK0@'A;OIIggm,&
#Iy(&(	(#)8?34k?*Io& $ C<%hs5z&:KSGGXc$i0+?VW$S&'l

 hs5z2KAUV'	;?!!-0!!-0%%m4!!*c2&&}c:#I**9X+>D $ c5!!c#h!ma&Ca&Cooc";''C!4J	E 	E	@ 	@	4	  	 * c?@@||' 55TU 5; 11STCsww{B/0C<4(3u:...CsG$kk*c2sC8((#7GGWoG#IX&h'inn./X%!&) 0 $ "+F;$/F=!)|#F5M W55r3   c                    [        U[        5      (       a  U R                  XX45      $ [        U5      nUR	                  S5      (       a(  UR                  S5      (       a  U R                  XX45      $ U R                  XX45      $ )a  Extract a JWE Serialization.

It supports both compact and JSON serialization.

:param obj: JWE compact serialization as bytes or
    JWE JSON serialization as dict or str
:param key: Private key used to decrypt payload
    (optionally can be a tuple of kid and essentially key)
:param decode: Function to decode payload data
:param sender_key: Sender's public key in case
    JWEAlgorithmWithTagAwareKeyAgreement is used
:return: dict with `header` and `payload` keys
   {   })rN   dictr   r   
startswithendswithr   )r-   r~   rZ   r   r[   s        r0   deserializeJsonWebEncryption.deserialize  sp     c4  ((6FFsm>>$CLL$6$6((6FF''&EEr3   c                     [        U S5      $ )zParse JWE JSON Serialization.

:param obj: JWE JSON Serialization as str or dict
:return: Parsed JWE JSON Serialization as dict if `obj` is an str,
    or `obj` as is if `obj` is already a dict
r5   r   )r~   s    r0   
parse_jsonJsonWebEncryption.parse_json  s     3&&r3   c                     SU;  a
  [        5       eUS   nU R                  b  X R                  ;  a
  [        5       eX R                  ;  a
  [        5       eU R                  U   $ )Nr   )r   r+   r   r9   )r-   rD   r   s      r0   rH    JsonWebEncryption.get_header_alg  sb    '))Um'C7G7G,G+--'''+--  %%r3   c                     SU;  a
  [        5       eUS   nU R                  b  X R                  ;  a
  [        5       eX R                  ;  a
  [        5       eU R                  U   $ )Nr   )r   r+   r   r;   )r-   rD   r   s      r0   rI    JsonWebEncryption.get_header_enc  sb    133Um'C7G7G,G577'''577  %%r3   c                     SU;   aS  US   nU R                   b  X R                   ;  a
  [        5       eX R                  ;  a
  [        5       eU R                  U   $ g )Nr   )r+   r   r<   )r-   rD   zs      r0   rJ    JsonWebEncryption.get_header_zip  s]    F?uA+9I9I0I:<<))):<<$$Q'' r3   c                     [        U[        5      (       a  Uc  [        UR                   S35      eg Ub  [        UR                   S35      eg )NzB algorithm requires sender_key but passed sender_key value is NonezJ algorithm does not use sender_key but passed sender_key value is not None)rN   r   r7   r:   )r-   r[   r   s      r0   rK   &JsonWebEncryption._validate_sender_key  s`    c?@@! xxj bc  "
 % xxj jk  &r3   c                    U R                   c  g U R                  R                  5       nUR                  U R                   5      nUR                  (       a  UR                  UR                  5      nU H  nXC;  d  M
  [        U5      e   g r)   )r,   !REGISTERED_HEADER_PARAMETER_NAMEScopyunionEXTRA_HEADERSr   )r-   rD   r   namesks        r0   rL   +JsonWebEncryption._validate_private_headers  sr       (66;;=D112KK 1 12EA~5a88 r3   r*   )NNr)   )__name__
__module____qualname____firstlineno__	frozensetr   r9   r;   r<   r1   classmethodr?   re   r   r   r   r   r   staticmethodr   rH   rI   rJ   rK   rL   __static_attributes__ r3   r0   r   r      s    (1	
)%$ LLL0 
9 
9h
T||H*@9DS6jF. ' '	&&(
9r3   r   c                 t    [        U5      (       a
  U" US 5      nOUc  SU;   a  US   nU R                  U5      $ )Nr    )callablerM   )r   rD   rZ   s      r0   rM   rM     s:    }}&$	&Um??3r3   N)collectionsr   r   r   authlib.common.encodingr   r   r   r   authlib.jose.errorsr	   r
   r   r   r   r   r   r   r   authlib.jose.rfc7516.modelsr   r   r   authlib.jose.utilr   r   r   r   rM   r   r3   r0   <module>r      sV    #  2 , . 5 + I ? 0 5 ? 9 D C L 1 7 ) , -V9 V9r r3   