o
    i&                     @  s   d dl mZ d dlZd dlmZmZ d dlmZ d dl	m
Z
mZ d dlmZ ddlmZ d	d
lmZ e
rMd dlma d dlma d dlma d dlmZ ndadadadddZG dd deeedB f ZG dd deZddgZdS )    )annotationsN)IteratorMapping)cached_property)TYPE_CHECKINGAny)	FieldInfo   )SecretVersion   )EnvSettingsSourcedefaultCredentialsSecretManagerServiceClient)BaseSettingsreturnNonec               
   C  s   z2ddl ma ddlma t  tjdtd ddl	m
a
 W d    W d S 1 s+w   Y  W d S  tyC }  ztd| d } ~ ww )Nr   r   r   ignore)categoryr   zjGCP Secret Manager dependencies are not installed, run `pip install pydantic-settings[gcp-secret-manager]`)google.authr   google_auth_defaultgoogle.auth.credentialsr   warningscatch_warningsfilterwarningsFutureWarninggoogle.cloud.secretmanagerr   ImportError)e r"   ^/home/app/Keep/.python/lib/python3.10/site-packages/pydantic_settings/sources/providers/gcp.pyimport_gcp_secret_manager   s   
&r$   c                   @  s   e Zd ZU ded< ded< d,ddZed-ddZd.ddZed/ddZ	ed0ddZ
d1d2ddZd1d3d!d"Zd4d#d$Zd5d&d'Zd6d)d*Zd+S )7GoogleSecretManagerMappingzdict[str, str | None]_loaded_secretsr   _secret_clientsecret_client
project_idstrcase_sensitiveboolr   r   c                 C  s   i | _ || _|| _|| _d S N)r&   r'   _project_id_case_sensitive)selfr(   r)   r+   r"   r"   r#   __init__/   s   
z#GoogleSecretManagerMapping.__init__c                 C  s   | j | jS r-   )r'   Zcommon_project_pathr.   r0   r"   r"   r#   _gcp_project_path5      z,GoogleSecretManagerMapping._gcp_project_path
lower_name
candidates	list[str]c                 C  sL   t |dkr
|d S |  |d }tjd| d| d| dtdd	 |S )
Nr   r   z)Secret collision: Found multiple secrets z normalizing to 'z
'. Using 'z' for case-insensitive lookup.r	   )
stacklevel)lensortr   warnUserWarning)r0   r5   r6   winnerr"   r"   r#   _select_case_insensitive_secret9   s   z:GoogleSecretManagerMapping._select_case_insensitive_secretdict[str, str]c                 C  s   i }i }| j j| jd}|D ]'}| j |jdd}|||< | js5| }||vr.g ||< || | q| jsJ|	 D ]\}}| 
||||< q=|S )N)parentsecret )r'   Zlist_secretsr3   Zparse_secret_pathnamegetr/   lowerappenditemsr?   )r0   mappingZnormalized_groupsZsecretsrB   rD   r5   r6   r"   r"   r#   _secret_name_mapH   s    z+GoogleSecretManagerMapping._secret_name_mapc                 C  s   t | j S r-   )listrJ   keysr2   r"   r"   r#   _secret_names_   r4   z(GoogleSecretManagerMapping._secret_nameslatestkeyversionc                 C  s   | j | j||S r-   )r'   Zsecret_version_pathr.   )r0   rO   rP   r"   r"   r#   _secret_version_pathc   s   z/GoogleSecretManagerMapping._secret_version_pathgcp_secret_name
str | Nonec                 C  s8   z| j j| ||djjdW S  ty   Y d S w )N)rD   zUTF-8)r'   Zaccess_secret_versionrQ   payloaddatadecode	Exception)r0   rR   rP   r"   r"   r#   _get_secret_valuef   s   

z,GoogleSecretManagerMapping._get_secret_valuec                 C  sf   || j v r
| j | S | j|}|d u r| js| j| }|r*| || j |< nt|| j | S r-   )r&   rJ   rE   r/   rF   rX   KeyError)r0   rO   rR   r"   r"   r#   __getitem__n   s   


z&GoogleSecretManagerMapping.__getitem__intc                 C  
   t | jS r-   )r:   rM   r2   r"   r"   r#   __len__}      
z"GoogleSecretManagerMapping.__len__Iterator[str]c                 C  r\   r-   )iterrM   r2   r"   r"   r#   __iter__   r^   z#GoogleSecretManagerMapping.__iter__N)r(   r   r)   r*   r+   r,   r   r   r   r*   )r5   r*   r6   r7   r   r*   )r   r@   )r   r7   )rN   )rO   r*   rP   r*   r   r*   )rR   r*   rP   r*   r   rS   )rO   r*   r   rS   )r   r[   )r   r_   )__name__
__module____qualname____annotations__r1   propertyr3   r?   r   rJ   rM   rQ   rX   rZ   r]   ra   r"   r"   r"   r#   r%   +   s    
 



r%   c                      sj   e Zd ZU ded< ded< ded< 							d%d& fddZd' fddZd(d!d"Zd)d#d$Z  ZS )*!GoogleSecretManagerSettingsSourcer   _credentialsr   r'   r*   r.   NTsettings_clstype[BaseSettings]credentialsCredentials | Noner)   rS   
env_prefixenv_parse_none_strenv_parse_enumsbool | Noner(   !SecretManagerServiceClient | Noner+   r   r   c	                   s   t d u std u std u rt  |r|st \}	}
|d u r|	}|d u r.t|
tr*|
}ntd|| _|| _|r:|| _	nt | jd| _	t
 j|||d||d d S )Nzproject_id is required to be specified either as an argument or from the google.auth.default. See https://google-auth.readthedocs.io/en/master/reference/google.auth.html#google.auth.default)rl   F)r+   rn   Zenv_ignore_emptyro   rp   )r   r   r   r$   
isinstancer*   AttributeErrorri   r.   r'   superr1   )r0   rj   rl   r)   rn   ro   rp   r(   r+   Z_credsr.   	__class__r"   r#   r1      s2   


z*GoogleSecretManagerSettingsSource.__init__fieldr   
field_nametuple[Any, str, bool]c                   s   t dd |jD d}|r]t| jtr]| ||D ]>\}}}| jj|}|du r5| js5| jj|	 }|rW| j
||}|durW| jjdrP|||f  S |||f  S qd|dfS t ||\}	}
}| jjdrw|	durw|	||fS |	|
|fS )a  Override get_field_value to get the secret value from GCP Secret Manager.
        Look for a SecretVersion metadata field to specify a particular SecretVersion.

        Args:
            field: The field to get the value for
            field_name: The declared name of the field

        Returns:
            A tuple of (value, key, value_is_complex), where `key` is the identifier used
            to populate the model (either the field name or an alias, depending on
            configuration).
        c                 s  s     | ]}t |tr|jV  qd S r-   )rs   r
   rP   ).0mr"   r"   r#   	<genexpr>   s    zDGoogleSecretManagerSettingsSource.get_field_value.<locals>.<genexpr>NZpopulate_by_nameF)nextmetadatars   Zenv_varsr%   Z_extract_field_inforJ   rE   r+   rF   rX   rj   Zmodel_configru   get_field_value)r0   rx   ry   Zsecret_versionZ	field_keyenv_nameZvalue_is_complexrR   Zenv_valvalrO   Z
is_complexrv   r"   r#   r      s$   


z1GoogleSecretManagerSettingsSource.get_field_valueMapping[str, str | None]c                 C  s   t | j| j| jdS )N)r)   r+   )r%   r'   r.   r+   r2   r"   r"   r#   _load_env_vars   s   z0GoogleSecretManagerSettingsSource._load_env_varsc                 C  s   | j j d| jd| jdS )Nz(project_id=z, env_nested_delimiter=))rw   rc   r.   Zenv_nested_delimiterr2   r"   r"   r#   __repr__   s   z*GoogleSecretManagerSettingsSource.__repr__)NNNNNNT)rj   rk   rl   rm   r)   rS   rn   rS   ro   rS   rp   rq   r(   rr   r+   rq   r   r   )rx   r   ry   r*   r   rz   )r   r   rb   )	rc   rd   re   rf   r1   r   r   r   __classcell__r"   r"   rv   r#   rh      s   
 1
.rh   )r   r   ) 
__future__r   Z_annotationsr   collections.abcr   r   	functoolsr   typingr   r   Zpydantic.fieldsr   typesr
   envr   r   r   r   r   r   r   r   Zpydantic_settings.mainr   r$   r*   r%   rh   __all__r"   r"   r"   r#   <module>   s(    
Ym