o
    2j                     @   s  d 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	m
Z
 dZd	ZG d
d deeZdedB fddZdedefddZddddeeB dB dedB defddZdddedededB defddZddddddededB deeB dB dedB dedB defddZdS )u  Keyless CI/CD authentication via OIDC token exchange ("Trusted Publishers").

A CI job proves its identity to the Hub with a short-lived OIDC id token minted by its CI
provider (e.g. GitHub Actions), then exchanges it at ``POST {ENDPOINT}/oauth/token`` (RFC 8693)
for a short-lived Hugging Face token — no long-lived ``HF_TOKEN`` secret to store.

This module is self-contained: it only handles minting the provider id token and the exchange.
It deliberately does not register a public API or a CLI verb; the integration point is the token
resolution in ``utils/_auth.py`` (see ``_get_token_from_oidc``).

Docs: https://huggingface.co/docs/hub/trusted-publishers
    N)Enum   )	constants)	OIDCError)get_sessionhf_raise_for_statusz/urn:ietf:params:oauth:grant-type:token-exchangez)urn:ietf:params:oauth:token-type:id_tokenc                   @   s   e Zd ZdZdZdS )ProviderzRCI providers that can mint an OIDC id token natively. GitHub Actions only for now.githubN)__name__
__module____qualname____doc__GITHUB r   r   P/var/www/html/whisper/venv/lib/python3.10/site-packages/huggingface_hub/_oidc.pyr   (   s    r   returnc                   C   s   t jddkrtjS dS )zYDetect the CI provider able to mint an OIDC id token, or `None` if not in a supported CI.GITHUB_ACTIONStrueN)osenvirongetr   r   r   r   r   r   detect_provider.   s   r   audiencec                 C   s\   t jd}t jd}|r|stdt j|d| idd| id}t| | d S )	zMint an OIDC id token from the GitHub Actions runtime.

    Relies on the `ACTIONS_ID_TOKEN_REQUEST_URL` / `ACTIONS_ID_TOKEN_REQUEST_TOKEN` env vars,
    which GitHub only injects when the job declares `permissions: id-token: write`.
    ACTIONS_ID_TOKEN_REQUEST_URLACTIONS_ID_TOKEN_REQUEST_TOKENzCannot request an OIDC id token from GitHub Actions. Make sure the workflow job sets `permissions: id-token: write`. See https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/about-security-hardening-with-openid-connectr   AuthorizationzBearer )paramsheadersvalue)r   r   r   r   r   r   json)r   request_urlrequest_tokenresponser   r   r   _get_github_oidc_token5   s   r#   providerr   r%   c                 C   sh   |pt j}| p	t } ddd tD }| du r td| d| tjkr)t|S td|  d| d)	a  Mint a raw OIDC id token (JWT) from the current CI provider.

    Args:
        provider (`str`, *optional*):
            CI provider to use. Auto-detected from the environment when omitted.
        audience (`str`, *optional*):
            The `aud` claim to request. Defaults to `constants.ENDPOINT` so it matches the endpoint
            that validates it (respects `HF_ENDPOINT`/staging).

    Returns:
        `str`: The raw id token (JWT) to pass to [`exchange_oidc_token`].
    z, c                 s   s    | ]}|j V  qd S )N)r   ).0pr   r   r   	<genexpr>[   s    z!get_oidc_token.<locals>.<genexpr>NzONo supported CI OIDC provider detected. Trusted Publishers currently supports: .zOIDC provider 'z#' is not supported yet. Supported: )	r   ENDPOINTr   joinr   r   r   r#   NotImplementedError)r%   r   	supportedr   r   r   get_oidc_tokenL   s   


r.   )endpointsubject_tokenresourcer/   c                 C   s6   t  j|ptj dtt| |dd}t| | S )u  Exchange a CI OIDC id token for a short-lived Hugging Face token (RFC 8693).

    Args:
        subject_token (`str`):
            The raw OIDC id token (JWT) from the CI provider. Its `aud` claim must be the Hub URL.
        resource (`str`):
            What to scope the token to: a Hub repo (`namespace/name`, `datasets/namespace/name`,
            `spaces/namespace/name`, `kernels/namespace/name`) for a write token, or a bare Hub
            username for a read-only `gated-repos` token.
        endpoint (`str`, *optional*):
            Hub endpoint. Defaults to `constants.ENDPOINT` (respects `HF_ENDPOINT`/staging).

    Returns:
        `dict`: The token-exchange response, e.g.
        `{"access_token": "hf_jwt_…", "token_type": "bearer", "expires_in": 3600, ...}`.
    z/oauth/token)
grant_typesubject_token_typer0   r1   )r   )r   postr   r*   _TOKEN_EXCHANGE_GRANT_TYPE_ID_TOKEN_TYPEr   r   )r0   r1   r/   r"   r   r   r   exchange_oidc_tokenc   s   	r7   )r0   r%   r   r/   c                 C   s0   |pt j}|du rt||p|d}t|| |dS )u  Mint a CI OIDC id token and exchange it for a Hugging Face token.

    Convenience wrapper around [`get_oidc_token`] + [`exchange_oidc_token`]. Returns the raw
    exchange response (it does not persist anything — the caller decides what to do with the token).

    Args:
        resource (`str`):
            Repo or username to scope the token to. See [`exchange_oidc_token`].
        subject_token (`str`, *optional*):
            A pre-minted OIDC id token to exchange directly. Use this for CI providers not yet
            supported natively (e.g. GitLab): mint the id token in your job and pass it here. When
            omitted, the token is minted from the detected `provider`.
        provider (`str`, *optional*):
            CI provider. Auto-detected when omitted. Ignored when `subject_token` is provided.
        audience (`str`, *optional*):
            The `aud` claim to request. Defaults to the resolved `endpoint`, so it matches the
            endpoint that validates it.
        endpoint (`str`, *optional*):
            Hub endpoint. Defaults to `constants.ENDPOINT`.

    Returns:
        `dict`: The token-exchange response (`access_token`, `token_type`, `expires_in`, ...).
    Nr$   )r0   r1   r/   )r   r*   r.   r7   )r1   r0   r%   r   r/   r   r   r   
oidc_login   s   
r8   )r   r   enumr    r   errorsr   utilsr   r   r5   r6   strr   r   r#   r.   dictr7   r8   r   r   r   r   <module>   s<   *$!
