
    6IiF                        S SK r S SKrS SKJr  S SKJrJrJrJr  S SK	J
r
JrJrJr  S SKJr  S SKJr  S SKJrJr  S SKJr  S S	KJr  S S
KJr  S SKJr  \
" SSSS9r\" SS9r\" SSS9r\ " 5       r!S\"\#   4S jr$ " S S5      r%g)    N)Optional)DependsHTTPExceptionRequestSecurity)APIKeyHeaderHTTPAuthorizationCredentials	HTTPBasicOAuth2PasswordBearer)FormData)config)get_api_keyupdate_key_last_used)extract_generic_body)AuthenticatedEntity)Admin)get_role_by_role_namez	X-API-KEYzAPI KeyF)namescheme_name
auto_error)r   token)tokenUrlr   returnc                  b    / n [          H"  nS H  nU R                  U SU 35        M     M$     U $ )z8
Get all scopes

Returns:
    list: The list of scopes.
)readwritedeleteupdate:)ALL_RESOURCESappend)scopesresourceactions      K/venv/lib/python3.13/site-packages/keep/identitymanager/authverifierbase.pyget_all_scopesr&      s;     F!;FMMVHAhZ01 < " M    c                      \ rS rSrSr/ 4S\\   SS4S jjr\" \	5      \" \
5      \" \5      \" \5      4S\S\\   S	\\   S
\\   S\\-  \-  S\4S jjr SS\S\\   S	\\   S
\\   S\\\-  \-     S\4S jjrS\SS4S jrS\SS4S jrS\S\S	\S\4S jr\" \	5      \" \
5      4S\S\S	\S\4S jjrS rS
\S\4S jrSrg)AuthVerifierBase+   a  
Base class for authentication and authorization verification.

This class provides a framework for implementing authentication and authorization
in FastAPI applications. It supports multiple authentication methods including
API keys, HTTP Basic Auth, and OAuth2 bearer tokens.

Subclasses can override the following methods to customize the authentication
and authorization process:
- _verify_bearer_token: Implement token-based authentication
- _verify_api_key: Customize API key verification
- _authorize: Implement custom authorization logic

The main entry point is the __call__ method, which handles the entire
authentication and authorization flow.

Attributes:
    scopes (list[str]): A list of required scopes for authorization.
    logger (logging.Logger): Logger for this class.

r"   r   Nc                 T   [         R                  U Vs/ s H  o"R                  S5      S   PM     sn5        Xl        [        R
                  " [        5      U l        [        SSS9S:H  U l	        [        SSS9U l
        [        S	S
S9U l        [        SSS9S:H  U l        [        SSS9U l        0 U l        [        SSS9S:H  U l        [        SSS9U l        U R                   R                  S5      U l        U R                  (       a  U R                   (       d  [#        S5      eg g s  snf )Nr      KEEP_IMPERSONATION_ENABLEDfalsedefaulttrueKEEP_IMPERSONATION_USER_HEADERzX-KEEP-USERKEEP_IMPERSONATION_ROLE_HEADERzX-KEEP-ROLE!KEEP_IMPERSONATION_AUTO_PROVISIONKEEP_UPDATE_KEY_INTERVAL<   KEEP_READ_ONLYKEEP_READ_ONLY_BYPASS_KEY ,zBKEEP_READ_ONLY_BYPASS_KEY must be set if KEEP_READ_ONLY is enabled)r    r   splitr"   logging	getLogger__name__loggerr   impersonation_enabledimpersonation_user_headerimpersonation_role_headerimpersonation_auto_provisionupdate_key_intervalkey_last_used_updates	read_onlyread_only_bypass_keys
ValueError)selfr"   scopes      r%   __init__AuthVerifierBase.__init__B   s    vFvekk#.q1vFG''1/AVK 	" *0,m*
& *0,m*
& 6HFR 	)
 $**Db#Q %'" 0'BfL%+,GQS%T"%)%?%?%E%Ec%J">>$"<"<T  #=>1 Gs   D%requestapi_keyauthorizationr   bodyc                 >   U R                   R                  S5        U R                  (       as  X R                  ;  ad  [	        U R
                   Vs/ s H  ofR                  S5      S   S:g  PM     sn5      (       a%  U R                   R                  S5        [        SSS9eU R                  XX4U5      nU R                   R                  SU 35        U R                   R                  S	5        U R                  U5        U R                   R                  S
5        U$ s  snf )a  
Main entry point for authentication and authorization.

Args:
    request (Request): The incoming request.
    api_key (Optional[str]): The API key from the header.
    authorization (Optional[HTTPAuthorizationCredentials]): The HTTP basic auth credentials.
    token (Optional[str]): The OAuth2 token.

Returns:
    AuthenticatedEntity: The authenticated entity.

Raises:
    HTTPException: If authentication or authorization fails.
zStarting authentication processr   r   r   z1Read only instance, but non-read scopes requested  status_codedetailz&Authentication successful for entity: zStarting authorization processzAuthorization successful)r?   debugrF   rG   anyr"   r;   errorr   authenticate	authorize)rI   rM   rN   rO   r   rP   rJ   authenticated_entitys           r%   __call__AuthVerifierBase.__call__`   s    . 	;<>>g-G-GGt{{K{eKK$Q'61{KLL!!"UV# #N 
  $00=Y]^45I4JK	
 	:;+,45##! Ls    Dc                    U R                   R                  S5        U(       a-  U R                   R                  S5         U R                  U5      $ U R                  XU5      n[        U[        5      (       a  U$ U(       a.  U R                   R                  S5         U R                  XU5      $ U R                   R                  S	UR                  US
.S9  [        SSS9e! [         a    e [         a&    U R                   R                  S5        [        SSS9ef = f! [         a    e [         a&    U R                   R                  S5        [        SSS9ef = f)a  
Authenticate the request using either token, API key, or HTTP basic auth.

Args:
    request (Request): The incoming request.
    api_key (Optional[str]): The API key from the header.
    authorization (Optional[HTTPAuthorizationCredentials]): The HTTP basic auth credentials.
    token (Optional[str]): The OAuth2 token.
    body (Optional[dict | bytes | FormData]): incoming request body got logs

Returns:
    AuthenticatedEntity: The authenticated entity.

Raises:
    HTTPException: If authentication fails.
zAttempting authenticationz,Attempting to authenticate with bearer tokenzFailed to validate token  z"Invalid authentication credentialsrS   z'Attempting to authenticate with API keyzFailed to validate API Keyz$No valid authentication method found)headersrP   extraz"Missing authentication credentials)r?   rV   _verify_bearer_tokenr   	Exception	exception_extract_api_key
isinstancer   _verify_api_keyrX   r`   )rI   rM   rN   rO   r   rP   s         r%   rY   AuthVerifierBase.authenticate   s[   0 	56KKLM0077 ''-Hg233NKKGH++GmLL 	2"?? 	 	
 $H
 	
? !  %%&@A# #,P  !  %%&BC# #,P s   C D :D:Er[   c                 b    U R                   R                  SU 35        U R                  U5        g)z
Authorize the authenticated entity.

Args:
    authenticated_entity (AuthenticatedEntity): The authenticated entity to authorize.

Raises:
    HTTPException: If authorization fails.
zAuthorizing entity: N)r?   rV   
_authorize)rI   r[   s     r%   rZ   AuthVerifierBase.authorize   s-     	01E0FGH,-r'   c                 *   [        UR                  5      nU R                  R                  SU 35        UR	                  U R
                  5      (       d@  U R                  R                  SU R
                   35        [        SSU R
                   S3S9eg)z
Internal method to perform authorization.

Args:
    authenticated_entity (AuthenticatedEntity): The authenticated entity to authorize.

Raises:
    HTTPException: If the entity doesn't have the required scopes.
zChecking scopes for role: z'Authorization failed. Required scopes: rR   zMYou don't have the required scopes to access this resource [required scopes: ]rS   N)r   roler?   rV   
has_scopesr"   warningr   )rI   r[   ro   s      r%   rk   AuthVerifierBase._authorize   s     %%9%>%>?6tf=>t{{++KK"I$++ WXfgkgrgrfsstu  ,r'   c                    U R                   R                  S5        U=(       d    UR                  R                  SS5      nU(       Gd  U(       d  SUR                  R                  SS5      ;   a  U R                   R                  S5        [        SS	S
9nU(       aq  UR                  R                  R                  S5      (       aG  UR                  R                  SS5      nU R                   R                  SU S35        [        USSSS9$ [        SSS0SS9eUR                  R                  S5      n UR                  S5      u  pxn	UR#                  5       S:X  a  UR$                  nOkUR#                  5       S:X  a/  U	(       d%  U R                   R                  S 5        [        S!S S9eU	nO(U R                   R                  S"U 35        [        SSS9eU R                   R                  S#5        U$ ! [         aT    U R                   R                  S[!        UR                  5      UR                  R                  S5      S.S9  [        SSS9ef = f)$aU  
Extract the API key from various sources in the request.

Args:
    request (Request): The incoming request.
    api_key (str): The API key from the header.
    authorization (HTTPAuthorizationCredentials): The HTTP basic auth credentials.

Returns:
    str: The extracted API key.

Raises:
    HTTPException: If no valid API key is found.
zExtracting API keyrN   Nz(Amazon Simple Notification Service Agent
user-agentr9   z#Got an SNS request without any authKEEP_CLOUDWATCH_DISABLE_API_KEYFr/   z/alerts/event/cloudwatch	tenant_idkeepz,Allowing unauthenticated access for tenant: z for CloudWatchsystemwebhookrv   emailapi_key_namero   r_   zWWW-AuthenticateBasiczMissing API Key)rT   r`   rU   Authorization z$Failed to parse Authorization header)urlrt   ra   rS   basicdigestzInvalid Digest credentialsrR   z#Unsupported authentication scheme: zAPI key extracted successfully)r?   rV   query_paramsgetr`   rq   r   r   pathendswithinfor   r   	partitionrd   rX   strlowerpassword)
rI   rM   rN   rO   allow_unauthrv   auth_headerscheme_credentialss
             r%   rf   !AuthVerifierBase._extract_api_key   s8   ( 	./FW1155iF ">??&&|R89 ##$IJ%&GQVWGKK$4$4$=$=.% % !( 4 4 8 8f MIKK$$FykQ`a /"+&%.&	  $ #/9,  "//--o>K
O)4)>)>s)C&; ||~('008+"KK%%&BC'$'0L  *G!!$Gx"PQ#<MNN:;/  O!!:"7;;/&-oo&9&9,&G "  $<MNNOs   6G3 3AIc                    U R                   R                  S5        [        U5      nU(       d%  U R                   R                  S5        [	        SSS9e U R                   R                  S5        UR
                   SUR                   3U R                  ;   a  U R                  UR
                   SUR                   3   [        R                  R                  5       [        R                  " U R                  S9-
  :  a)  U R                   R                  SU R                   S	35        Ob[        UR
                  UR                  S
9  [        R                  R                  5       U R                  UR
                   SUR                   3'   U R                   R                  S5        UR
                  UR                  l        U R                   R                  SUR
                   35        U R                   (       d6  [#        UR
                  UR$                  UR                  UR&                  5      $ UR(                  R+                  U R,                  5      nUR(                  R+                  U R.                  5      nU(       a  U(       d6  [#        UR
                  UR$                  UR                  UR&                  5      $ U R                   R1                  S5        UR(                  R+                  U R,                  5      nUR(                  R+                  U R.                  5      nU(       a  U(       d
  [	        SSS9eUR&                  [2        R4                  " 5       :w  a%  U R                   R7                  S5        [	        SSS9eU R8                  (       aY  U R                   R1                  SU 35        U R;                  UR
                  XV5        U R                   R1                  SU S35        U R                   R1                  S5        [#        UR
                  USUS9$ ! [         a    U R                   R                  S5         GNf = f)a]  
Verify the API key and return an authenticated entity.

Args:
    request (Request): The incoming request.
    api_key (str): The API key to verify.
    authorization (HTTPAuthorizationCredentials): The HTTP basic auth credentials.

Returns:
    AuthenticatedEntity: The authenticated entity.

Raises:
    HTTPException: If the API key is invalid.
zVerifying API keyzInvalid API Keyr_   rS   zUpdating API Key last usedr   )secondsz&API Key last used updated in the last z seconds)reference_idz&Successfully updated API Key last usedz"Failed to update API Key last usedzAPI key verified for tenant: zImpersonating userzImpersonation headers missingz-Impersonation not allowed for non-admin userszAuto provisioning user: zUser z provisioned successfullyzUser impersonated successfullyNrz   )r?   rV   r   rq   r   rv   r   rE   datetimenow	timedeltarD   r   rd   re   stater@   r   
created_byro   r`   r   rA   rB   r   	AdminRoleget_namerX   rC   _provision_user)rI   rM   rN   rO   tenant_api_key	user_namero   s          r%   rh    AuthVerifierBase._verify_api_key;  s   ( 	-.$W-KK 12C8IJJ	HKK:; "++,An.I.I-JK--. --%//0.2M2M1NO %%))+((1I1IJK KK%%@AYAY@ZZbc
 %",,>;V;V
 %%))+ **%//0.2M2M1NO KKFG #1":":9.:R:R9STU))&(())++##	  OO''(F(FG	""4#A#AB&(())++##	  	-.OO''(F(FG	""4#A#ABC8WXX )"4"4"66KKMN(W 
 ,,KK7	{CD  !9!99KKKuYK/HIJ9:"$..	
 	
]  	HKK!!"FG	Hs   EP %QQc                 ^    [        SR                  U R                  R                  5      5      e)z
Create a user for impersonation.

Args:
    tenant_api_key: The API key used for impersonation.
    user_name: The name of the user to create.
    role: The role of the user to create.
z(User provisioning not implemented for {})NotImplementedErrorformat	__class__r>   )rI   r   r   ro   s       r%   r    AuthVerifierBase._provision_user  s*     "fT^^445
 	
r'   c                     U R                   R                  S5        [        SR                  U R                  R
                  5      5      e)a  
Verify the bearer token and return an authenticated entity.

Args:
    token (str): The bearer token to verify.

Returns:
    AuthenticatedEntity: The authenticated entity.

Raises:
    NotImplementedError: This method needs to be implemented in subclasses.
z-_verify_bearer_token() method not implementedz4_verify_bearer_token() method not implemented for {})r?   rX   r   r   r   r>   )rI   r   s     r%   rc   %AuthVerifierBase._verify_bearer_token  s=     	IJ!fT^^445
 	
r'   )
rC   r@   rB   rA   rE   r?   rF   rG   r"   rD   )N)r>   
__module____qualname____firstlineno____doc__listr   rK   r   r   
http_basicr   oauth2_schemer   r   r   r	   dictbytesr   r   r\   rY   rZ   rk   rf   rh   r   rc   __static_attributes__ r'   r%   r)   r)   +   s   , ,. tCy $ B "*+!6@H@T&}5(/0D(E*$*$ #*$   <=	*$
 }*$ UlX%*$ 
*$d 37>
>
 #>
   <=	>

 }>
 te|h./>
 
>
@..A .d ./B t &MM M 4	M
 
Md  ,6>z6J	g
g
 g
 4	g

 
g
R

# 
2E 
r'   r)   )&r   r<   typingr   fastapir   r   r   r   fastapi.securityr   r	   r
   r   starlette.datastructuresr   keep.api.core.configr   keep.api.core.dbr   r   keep.api.core.dependenciesr   (keep.identitymanager.authenticatedentityr   keep.identitymanager.rbacr   r   r   r   r   r   setr    r   r   r&   r)   r   r'   r%   <module>r      s|       = =  . ' > ; H 8 ;uU%(
$g%HS	 X
 X
r'   