Ë
    tPêjT@  ã                   ó   — U d Z ddlZddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 ddlmZ 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mZ dZe
ed<   dZe
ed<    eeddœ«      Ze
eeef      ed<    G d„ de«      Zy)aU  
Azure Sentinel Integration - sends logs to Azure Log Analytics using Logs Ingestion API

Azure Sentinel uses Log Analytics workspaces for data storage. This integration sends
LiteLLM logs to the Log Analytics workspace using the Azure Monitor Logs Ingestion API.

Reference API: https://learn.microsoft.com/en-us/azure/azure-monitor/logs/logs-ingestion-api-overview

`async_log_success_event` - used by litellm proxy to send logs to Azure Sentinel
`async_log_failure_event` - used by litellm proxy to send failure logs to Azure Sentinel

For batching specific details see CustomBatchLogger class
é    N)ÚMapping)ÚMappingProxyType)ÚFinal)Úurlparse)Úverbose_logger)ÚCustomBatchLogger)Ú
safe_dumps)Úget_async_httpx_clientÚhttpxSpecialProvider)ÚStandardAuditLogPayloadÚStandardLoggingPayloadz!https://login.microsoftonline.comÚDEFAULT_AZURE_AUTHORITY_HOSTz"https://monitor.azure.com/.defaultÚDEFAULT_AZURE_MONITOR_SCOPEz!https://monitor.azure.us/.default)zlogin.microsoftonline.comzlogin.microsoftonline.usÚMONITOR_SCOPE_BY_AUTHORITY_HOSTc                   ó:  ‡ — e Zd ZdZ	 	 	 	 	 	 	 	 ddedz  dedz  dedz  dedz  dedz  dedz  d	edz  d
edz  fˆ fd„Zed
edefd„«       Zed
edefd„«       Zededededefd„«       Z	defd„Z
d„ Zd„ Zdeddfd„Zd„ Zd„ Zdeeez     dededdfd„Zd„ Zˆ xZS )ÚAzureSentinelLoggerz_
    Logger that sends LiteLLM logs to Azure Sentinel via Azure Monitor Logs Ingestion API
    NÚdcr_immutable_idÚstream_nameÚendpointÚ	tenant_idÚ	client_idÚclient_secretÚaudit_stream_nameÚauthority_hostc	                 ó8  •— t        t        j                  ¬«      | _        |xs t	        j
                  d«      }
|xs t	        j
                  d«      xs d}|xs t	        j
                  d«      xs |}|xs t	        j
                  d«      }|xs, t	        j
                  d«      xs t	        j
                  d«      }|xs, t	        j
                  d	«      xs t	        j
                  d
«      }|xs, t	        j
                  d«      xs t	        j
                  d«      }| j                  |xs4 t	        j
                  d«      xs t	        j
                  d«      xs t        «      }|
st        d«      ‚|st        d«      ‚|st        d«      ‚|st        d«      ‚|st        d«      ‚|
| _	        || _
        || _        || _        || _        || _        || _        | j!                  ||
|¬«      | _        | j!                  ||
|¬«      | _        || _        | j)                  |¬«      | _        d| _        d| _        t1        j2                  «       | _        t7        ‰| �p  di |	¤d| j4                  i¤Ž t1        j:                  | j=                  «       «       g | _        g | _         y)aü  
        Initialize Azure Sentinel logger using Logs Ingestion API

        Args:
            dcr_immutable_id (str, optional): Data Collection Rule (DCR) Immutable ID.
                If not provided, will use AZURE_SENTINEL_DCR_IMMUTABLE_ID env var.
            stream_name (str, optional): Stream name from DCR (e.g., "Custom-LiteLLM").
                If not provided, will use AZURE_SENTINEL_STREAM_NAME env var or default to "Custom-LiteLLM".
            endpoint (str, optional): Data Collection Endpoint (DCE) or DCR ingestion endpoint.
                If not provided, will use AZURE_SENTINEL_ENDPOINT env var.
            tenant_id (str, optional): Azure Tenant ID for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID env var.
            client_id (str, optional): Azure Client ID (Application ID) for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID env var.
            client_secret (str, optional): Azure Client Secret for OAuth2 authentication.
                If not provided, will use AZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET env var.
            audit_stream_name (str, optional): Stream name from DCR for audit logs.
                If not provided, will use AZURE_SENTINEL_AUDIT_STREAM_NAME env var or the standard stream name.
            authority_host (str, optional): Microsoft Entra authority host that issues the OAuth2 token,
                e.g. "https://login.microsoftonline.us" for Azure Government. If not provided, will use
                AZURE_SENTINEL_AUTHORITY_HOST or AZURE_AUTHORITY_HOST env vars, or default to the Azure
                Public Cloud authority. The Azure Monitor audience is derived from it.
        )Úllm_providerÚAZURE_SENTINEL_DCR_IMMUTABLE_IDÚAZURE_SENTINEL_STREAM_NAMEzCustom-LiteLLMÚ AZURE_SENTINEL_AUDIT_STREAM_NAMEÚAZURE_SENTINEL_ENDPOINTÚAZURE_SENTINEL_TENANT_IDÚAZURE_TENANT_IDÚAZURE_SENTINEL_CLIENT_IDÚAZURE_CLIENT_IDÚAZURE_SENTINEL_CLIENT_SECRETÚAZURE_CLIENT_SECRETÚAZURE_SENTINEL_AUTHORITY_HOSTÚAZURE_AUTHORITY_HOSTzrAZURE_SENTINEL_DCR_IMMUTABLE_ID is required. Set it as an environment variable or pass dcr_immutable_id parameter.zbAZURE_SENTINEL_ENDPOINT is required. Set it as an environment variable or pass endpoint parameter.zwAZURE_SENTINEL_TENANT_ID or AZURE_TENANT_ID is required. Set it as an environment variable or pass tenant_id parameter.zwAZURE_SENTINEL_CLIENT_ID or AZURE_CLIENT_ID is required. Set it as an environment variable or pass client_id parameter.zƒAZURE_SENTINEL_CLIENT_SECRET or AZURE_CLIENT_SECRET is required. Set it as an environment variable or pass client_secret parameter.©r   r   r   )r   NÚ
flush_lock© )!r
   r   ÚLoggingCallbackÚasync_httpx_clientÚosÚgetenvÚ_normalize_authority_hostr   Ú
ValueErrorr   r   r   r   r   r   r   Ú_build_api_endpointÚapi_endpointÚaudit_api_endpointr   Ú_resolve_oauth_scopeÚoauth_scopeÚoauth_tokenÚoauth_token_expires_atÚasyncioÚLockr*   ÚsuperÚ__init__Úcreate_taskÚperiodic_flushÚ	log_queueÚaudit_log_queue)Úselfr   r   r   r   r   r   r   r   ÚkwargsÚresolved_dcr_immutable_idÚresolved_stream_nameÚresolved_audit_stream_nameÚresolved_endpointÚresolved_tenant_idÚresolved_client_idÚresolved_client_secretÚresolved_authority_hostÚ	__class__s                     €úw/home/oem/CyberBrain26-unified/.venv/lib/python3.12/site-packages/litellm/integrations/azure_sentinel/azure_sentinel.pyr<   zAzureSentinelLogger.__init__1   s¥  ø€ ôF #9ÔFZ×FjÑFjÔ"kˆÔà+;Ò+k¼r¿y¹yÐIjÓ?kÐ!Ø&1Ò&p´R·Y±YÐ?[Ó5\Ò&pÐ`pÐàÒf¤§¡Ð+MÓ!NÒfÐRfð 	#ð $,Ò#S¬r¯y©yÐ9RÓ/SÐØ$-Ò$v´·±Ð;UÓ1VÒ$vÔZ\×ZcÑZcÐduÓZvÐØ$-Ò$v´·±Ð;UÓ1VÒ$vÔZ\×ZcÑZcÐduÓZvÐàÒjœRŸY™YÐ'EÓFÒjÌ"Ï)É)ÐTiÓJjð 	ð *.×)GÑ)GØò ,Ü�y‰yÐ8Ó9ò,ä�y‰yÐ/Ó0ò,ô ,ó	*
Ðñ )Üð Eóð ñ !ÜØtóð ñ "Üð Jóð ñ "Üð Jóð ñ &Üð Vóð ð !:ˆÔØ/ˆÔØ!;ˆÔØ)ˆŒØ+ˆŒØ+ˆŒØ3ˆÔð !×4Ñ4Ø&Ø6Ø,ð 5ó 
ˆÔð
 #'×":Ñ":Ø&Ø6Ø2ð #;ó #
ˆÔð 6ˆÔØ×4Ñ4ÐD[Ð4Ó\ˆÔØ'+ˆÔØ48ˆÔ#ä!Ÿ,™,›.ˆŒÜ‰ÑÑ>˜6Ñ>¨d¯o©oÓ>Ü×Ñ˜D×/Ñ/Ó1Ô2Ø79ˆŒØ>@ˆÕó    Úreturnc                 óV   — | j                  «       j                  d«      }d|v r|S d|› �S )a  
        Normalize an authority host into an absolute URL with no trailing slash.

        Accepts the scheme-qualified form litellm documents ("https://login.microsoftonline.us")
        and the bare-host form the azure-identity AzureAuthorityHosts constants use.
        ú/z://zhttps://)ÚstripÚrstrip)r   Ústrippeds     rL   r0   z-AzureSentinelLogger._normalize_authority_host�   s6   € ð )×.Ñ.Ó0×7Ñ7¸Ó<ˆØ  HÑ,ˆxÐG°H¸X¸JÐ2GÐGrM   c                 óh   — t        | «      j                  xs d}t        j                  |t        «      S )zº
        Map an authority host to the Azure Monitor Logs Ingestion audience for the same cloud,
        falling back to the Azure Public Cloud audience for an unrecognized host.
        Ú )r   Úhostnamer   Úgetr   )r   Úhosts     rL   r5   z(AzureSentinelLogger._resolve_oauth_scope¨   s-   € ô ˜~Ó.×7Ñ7Ò=¸2ˆÜ.×2Ñ2°4Ô9TÓUÐUrM   c                 ó6   — | j                  d«      › d|› d|› d�S )NrP   z/dataCollectionRules/z	/streams/z?api-version=2023-01-01)rR   r)   s      rL   r2   z'AzureSentinelLogger._build_api_endpoint±   s+   € à—/‘/ #Ó&Ð'Ð'<Ð=MÐ<NÈiÐXcÐWdÐd{Ð|Ð|rM   c              ƒ   ó8  K  — | j                   r<| j                  r0t        j                  «       | j                  dz
  k  r| j                   S | j                  €J d«       ‚| j                  €J d«       ‚| j
                  €J d«       ‚| j                  › d| j                  › d�}| j                  | j
                  | j                  dd	œ}| j                  j                  ||d
di¬«      ƒ d{  –—† }|j                  dk7  r%t        d|j                  › d|j                  › �«      ‚|j                  «       }|j                  d«      | _         |j                  dd«      }| j                   st        d«      ‚t        j                  «       |z   | _        | j                   S 7 Œ¯­w)z€
        Get OAuth2 Bearer token for Azure Monitor Logs Ingestion API

        Returns:
            Bearer token string
        é<   Nztenant_id is requiredzclient_id is requiredzclient_secret is requiredrP   z/oauth2/v2.0/tokenÚclient_credentials)r   r   ÚscopeÚ
grant_typeúContent-Typez!application/x-www-form-urlencoded©ÚurlÚdataÚheaderséÈ   zFailed to get OAuth2 token: ú - Úaccess_tokenÚ
expires_ini  z2OAuth2 token response did not contain access_token)r7   r8   Útimer   r   r   r   r6   r-   ÚpostÚstatus_codeÚ	ExceptionÚtextÚjsonrW   )rA   Ú	token_urlÚ
token_dataÚresponseÚtoken_responserg   s         rL   Ú_get_oauth_tokenz$AzureSentinelLogger._get_oauth_tokenµ   s›  è ø€ ð ×Ò ×!<Ò!<ÄÇÁÃÈt×OjÑOjÐmoÑOoÒAoà×#Ñ#Ð#ð �~‰~Ð)ÐBÐ+BÓBÐ)Ø�~‰~Ð)ÐBÐ+BÓBÐ)Ø×!Ñ!Ð-ÐJÐ/JÓJÐ-à"×1Ñ1Ð2°!°D·N±NÐ3CÐCUÐVˆ	ð Ÿ™Ø!×/Ñ/Ø×%Ñ%Ø.ñ	
ˆ
ð !%× 7Ñ 7× <Ñ <ØØØ#Ð%HÐIð !=ó !
÷ 
ˆð ×Ñ 3Ò&ÜÐ:¸8×;OÑ;OÐ:PÐPSÐT\×TaÑTaÐSbÐcÓdÐdà (§¡£ˆØ)×-Ñ-¨nÓ=ˆÔØ*×.Ñ.¨|¸TÓBˆ
à×ÒÜÐPÓQÐQä&*§i¡i£k°JÑ&>ˆÔ#à×ÑÐð%
ús   ‚C&FÃ(FÃ)B0Fc              ƒ   ó¼  K  — 	 t        j                  d|«       |j                  dd«      }|€t        j                  d«       y| j                  j                  |«       t        | j                  «      | j                  k\  r| j                  «       ƒ d{  –—†  yy7 Œ# t        $ r3}t        j                  d|t        j                  «       «       Y d}~yd}~ww xY w­w)a"  
        Async Log success events to Azure Sentinel

        - Gets StandardLoggingPayload from kwargs
        - Adds to batch queue
        - Flushes based on CustomBatchLogger settings

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        z>Azure Sentinel: Logging - Enters logging function for model %sÚstandard_logging_objectNú;Azure Sentinel: standard_logging_object not found in kwargsú"Azure Sentinel Layer Error - %s
%s©r   ÚdebugrW   Úwarningr?   ÚappendÚlenÚ
batch_sizeÚasync_send_batchrk   Ú	exceptionÚ	tracebackÚ
format_exc©rA   rB   Úresponse_objÚ
start_timeÚend_timeÚstandard_logging_payloadÚes          rL   Úasync_log_success_eventz+AzureSentinelLogger.async_log_success_eventã   s»   è ø€ ð	gÜ× Ñ Ð!aÐciÔjØ.4¯j©jÐ9RÐTXÓ.YÐ$à'Ð/Ü×&Ñ&Ð'dÔeØà�N‰N×!Ñ!Ð":Ô;ä�4—>‘>Ó" d§o¡oÒ5Ø×+Ñ+Ó-×-Ñ-ð 6Ø-ùäò 	gÜ×$Ñ$Ð%JÈAÌy×OcÑOcÓOe×fÑfûð	güóM   ‚C„?B ÁCÁAB ÂBÂB ÂCÂB Â	CÂ&)CÃCÃCÃCc              ƒ   ó¼  K  — 	 t        j                  d|«       |j                  dd«      }|€t        j                  d«       y| j                  j                  |«       t        | j                  «      | j                  k\  r| j                  «       ƒ d{  –—†  yy7 Œ# t        $ r3}t        j                  d|t        j                  «       «       Y d}~yd}~ww xY w­w)a"  
        Async Log failure events to Azure Sentinel

        - Gets StandardLoggingPayload from kwargs
        - Adds to batch queue
        - Flushes based on CustomBatchLogger settings

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        zFAzure Sentinel: Logging - Enters failure logging function for model %srt   Nru   rv   rw   r�   s          rL   Úasync_log_failure_eventz+AzureSentinelLogger.async_log_failure_eventþ   s¿   è ø€ ð	gÜ× Ñ ØXØôð /5¯j©jÐ9RÐTXÓ.YÐ$à'Ð/Ü×&Ñ&Ð'dÔeØà�N‰N×!Ñ!Ð":Ô;ä�4—>‘>Ó" d§o¡oÒ5Ø×+Ñ+Ó-×-Ñ-ð 6Ø-ùäò 	gÜ×$Ñ$Ð%JÈAÌy×OcÑOcÓOe×fÑfûð	gürˆ   Ú	audit_logc              ƒ   óÆ  K  — 	 t        j                  d|j                  d«      |j                  d«      |j                  d«      «       | j                  j	                  |«       t        | j                  «      | j                  k\  r| j                  «       ƒ d{  –—†  yy7 Œ# t        $ r3}t        j                  d|t        j                  «       «       Y d}~yd}~ww xY w­w)zë
        Async log LiteLLM audit log events to Azure Sentinel.

        Audit logs are queued separately from standard LLM logs so mixed callback
        usage never sends schema-mismatched records in the same ingestion batch.
        z<Azure Sentinel: Logging audit event id=%s action=%s table=%sÚidÚactionÚ
table_nameNz,Azure Sentinel Audit Log Layer Error - %s
%s)r   rx   rW   r@   rz   r{   r|   Úasync_send_audit_batchrk   r~   r   r€   )rA   r‹   r†   s      rL   Úasync_log_audit_log_eventz-AzureSentinelLogger.async_log_audit_log_event  sº   è ø€ ð	qÜ× Ñ ØNØ—‘˜dÓ#Ø—‘˜hÓ'Ø—‘˜lÓ+ô	ð × Ñ ×'Ñ'¨	Ô2ä�4×'Ñ'Ó(¨D¯O©OÒ;Ø×1Ñ1Ó3×3Ñ3ð <Ø3ùäò 	qÜ×$Ñ$Ð%TÐVWÔYb×YmÑYmÓYo×pÑpûð	qüsA   ‚C!„BB" ÂB ÂB" ÂC!Â B" Â"	CÂ+)CÃC!ÃCÃC!c              ƒ   óp   K  — | j                  | j                  | j                  d¬«      ƒ d{  –—†  y7 Œ­w)z¬
        Sends the batch of logs to Azure Monitor Logs Ingestion API

        Raises:
            Raises a NON Blocking verbose_logger.exception if an error occurs
        Úlogs©r?   r3   Úlog_typeN)Ú_async_send_batch_to_apir?   r3   ©rA   s    rL   r}   z$AzureSentinelLogger.async_send_batch3  s8   è ø€ ð ×+Ñ+Ø—n‘nØ×*Ñ*Øð ,ó 
÷ 	
ò 	
úó   ‚,6®4¯6c              ƒ   óp   K  — | j                  | j                  | j                  d¬«      ƒ d{  –—†  y7 Œ­w)zS
        Sends the batch of audit logs to Azure Monitor Logs Ingestion API
        z
audit logsr”   N)r–   r@   r4   r—   s    rL   r�   z*AzureSentinelLogger.async_send_audit_batch@  s:   è ø€ ð ×+Ñ+Ø×*Ñ*Ø×0Ñ0Ø!ð ,ó 
÷ 	
ò 	
úr˜   r?   r3   r•   c              ƒ   ó  K  — 	 |s	 |j                  «        y t        j                  dt        |«      |«       | j	                  «       ƒ d {  –—† }t        |«      }d|› �ddœ}| j                  j                  ||j                  d«      |¬«      ƒ d {  –—† }|j                  dvrPt        j                  d|j                  |j                  «       t        d	|j                  › d
|j                  › �«      ‚t        j                  d|j                  «       |j                  «        y 7 ŒÛ7 Œ•# t        $ r3}t        j                  d|t        j                  «       «       Y d }~ŒLd }~ww xY w# |j                  «        w xY w­w)Nz%Azure Sentinel - about to flush %s %szBearer zapplication/json)ÚAuthorizationr_   zutf-8r`   )rd   éÌ   z5Azure Sentinel API error: status_code=%s, response=%sz'Failed to send logs to Azure Sentinel: re   z1Azure Sentinel: Response from API status_code: %sz.Azure Sentinel Error sending batch API - %s
%s)Úclearr   rx   r{   rr   r	   r-   ri   Úencoderj   Úerrorrl   rk   r~   r   r€   )	rA   r?   r3   r•   Úbearer_tokenÚbodyrc   rp   r†   s	            rL   r–   z,AzureSentinelLogger._async_send_batch_to_apiJ  sl  è ø€ ð&	ÙØðH �O‰OÕôE × Ñ Ð!HÌ#ÈiË.ÐZbÔcð )-×(=Ñ(=Ó(?×"?ˆLô % YÓ/ˆDð $+¨<¨.Ð!9Ø 2ñˆGð "×4Ñ4×9Ñ9¸lÐQU×Q\ÑQ\Ð]dÓQeÐovÐ9Ów×wˆHà×#Ñ#¨:Ñ5Ü×$Ñ$ØKØ×(Ñ(Ø—M‘Môô
  Ð"IÈ(×J^ÑJ^ÐI_Ð_bÐck×cpÑcpÐbqÐ rÓsÐsä× Ñ ØCØ×$Ñ$ôð �O‰OÕð? #@øð xùô ò 	sÜ×$Ñ$Ð%VÐXYÔ[d×[oÑ[oÓ[q×rÑrûð	sûð �O‰OÕüsj   ‚E?„D+ ‡E?˜3D+ ÁD'ÁAD+ ÂD)ÂBD+ ÄE?Ä'D+ Ä)D+ Ä+	E'Ä4)E"ÅE* Å"E'Å'E* Å*E<Å<E?c              ƒ   ól  K  — | j                   €y | j                   4 ƒd {  –—†  | j                  r| j                  «       ƒ d {  –—†  | j                  r| j	                  «       ƒ d {  –—†  t        j
                  «       | _        d d d «      ƒd {  –—†  y 7 Œv7 ŒT7 Œ27 Œ# 1 ƒd {  –—†7  sw Y   y xY w­w)N)r*   r?   r}   r@   r�   rh   Úlast_flush_timer—   s    rL   Úflush_queuezAzureSentinelLogger.flush_queuex  s“   è ø€ Ø�?‰?Ð"Øà—?‘?÷ 	/ñ 	/Ø�~Š~Ø×+Ñ+Ó-×-Ð-Ø×#Ò#Ø×1Ñ1Ó3×3Ð3Ü#'§9¡9£;ˆDÔ ÷	/÷ 	/ñ 	/øà-øà3øð		/ø÷ 	/÷ 	/ñ 	/üsh   ‚B4 B¡B4¤ BÁBÁ#BÁ(BÁ)BÂB4ÂBÂB4ÂBÂBÂB4ÂB1Â%B(Â&B1Â-B4)NNNNNNNN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ústrr<   Ústaticmethodr0   r5   r2   rr   r‡   rŠ   r   r‘   r}   r�   Úlistr   r–   r¤   Ú__classcell__)rK   s   @rL   r   r   ,   s£  ø„ ñð (,Ø"&Ø#Ø $Ø $Ø$(Ø(,Ø%)ñjAà ™*ðjAð ˜4‘ZðjAð ˜‘*ð	jAð
 ˜‘:ðjAð ˜‘:ðjAð ˜T‘zðjAð  ™:ðjAð ˜d™
õjAðX ðH°#ð H¸#ò Hó ðHð ðV¨Sð V°Sò Vó ðVð ð} cð }¸Sð }Èsð }ÐWZò }ó ð}ð, ¨ó , ò\gò6gð<qÐ9Pð qÐUYó qò.
ò
ð,àÐ.Ð1HÑHÑIð,ð ð,ð ð	,ð
 
ó,ö\	/rM   r   )r¨   r9   r.   rh   r   Úcollections.abcr   Útypesr   Útypingr   Úurllib.parser   Úlitellm._loggingr   Ú(litellm.integrations.custom_batch_loggerr   Ú*litellm.litellm_core_utils.safe_json_dumpsr	   Ú&litellm.llms.custom_httpx.http_handlerr
   r   Úlitellm.types.utilsr   r   r   Ú__annotations__r   r   r©   r   r+   rM   rL   ú<module>r·      sˆ   ðòó Û 	Û Û Ý #Ý "Ý Ý !å +Ý FÝ A÷÷ Pà&IÐ ˜eÓ IØ%IÐ ˜UÓ Iá<Là%@Ø$Gñó=Ð   w¨s°C¨xÑ'8Ñ!9ó ôU/Ð+õ U/rM   