Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Authentication protocols and helpers for NemoClient.

Defines the protocols that any token provider must satisfy, plus simple
concrete implementations.

OIDC-specific machinery lives in :mod:`~.oidc` (token provider, token set,
discovery) and :mod:`~.oidc_factory` (provider caching, config persistence).
"""

from __future__ import annotations

from typing import Protocol, runtime_checkable

# ---------------------------------------------------------------------------
# Protocols
# ---------------------------------------------------------------------------


@runtime_checkable
class TokenProvider(Protocol):
"""Sync protocol for objects that can supply an access token."""

def get_access_token(self) -> str: ...


@runtime_checkable
class AsyncTokenProvider(Protocol):
"""Async protocol for objects that can supply an access token."""

async def get_access_token(self) -> str: ...


# ---------------------------------------------------------------------------
# StaticToken
# ---------------------------------------------------------------------------


class StaticToken:
"""Wraps a plain token string into a TokenProvider."""

def __init__(self, token: str) -> None:
self._token = token

def get_access_token(self) -> str:
return self._token

async def get_access_token_async(self) -> str:
return self._token


# ---------------------------------------------------------------------------
# Auth errors
# ---------------------------------------------------------------------------


class AuthError(Exception):
"""Authentication-related error."""
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,17 @@
from __future__ import annotations

import asyncio
import inspect
import time
from collections.abc import Mapping
from pathlib import Path
from typing import Any, TypeVar, get_args, get_origin, overload

import httpx
from nemo_platform_plugin.client.auth import (
StaticToken,
TokenProvider,
)
from nemo_platform_plugin.client.response import (
AsyncNemoBinaryResponse,
AsyncNemoPaginatedResponse,
Expand Down Expand Up @@ -107,10 +113,12 @@ def __init__(
*,
base_url: str,
workspace: str | None = None,
auth: TokenProvider | str | None = None,
retry: RetryPolicy | None = None,
) -> None:
self._base_url = base_url.rstrip("/")
self._workspace = workspace
self._auth: TokenProvider | None = StaticToken(auth) if isinstance(auth, str) else auth
self._retry = retry

@property
Expand Down Expand Up @@ -202,12 +210,13 @@ def __init__(
*,
base_url: str,
workspace: str | None = None,
auth: TokenProvider | str | None = None,
default_headers: Mapping[str, str] | None = None,
timeout: float = DEFAULT_TIMEOUT,
retry: RetryPolicy | None = None,
http_client: httpx.Client | None = None,
) -> None:
super().__init__(base_url=base_url, workspace=workspace, retry=retry)
super().__init__(base_url=base_url, workspace=workspace, auth=auth, retry=retry)
self._http = http_client or httpx.Client(
headers=dict(default_headers) if default_headers else None,
timeout=timeout,
Expand Down Expand Up @@ -254,6 +263,20 @@ def send(
retry: RetryPolicy | None = None,
) -> NemoResponse[ResponseT]: ...

@classmethod
def from_config(
cls,
context: str | None = None,
config_path: Path | str | None = None,
) -> NemoClient:
"""Create a NemoClient from the user's nmp config file.

Args:
context: Context name to use (default: active context).
config_path: Path to config file (default: ``~/.config/nmp/config.yaml``).
"""
return _client_from_config(cls, context=context, config_path=config_path)

def send(
self,
request: PreparedRequest,
Expand All @@ -280,6 +303,14 @@ def send(
if headers:
request = request.with_headers(headers)

# Inject auth header if a TokenProvider is configured.
# NOTE: If a 401 occurs despite this, a future enhancement could
# call provider.force_refresh() and retry once. The proactive
# refresh margin (60s) makes this unlikely in practice.
if self._auth:
token = self._auth.get_access_token()
request = request.with_headers({"Authorization": f"Bearer {token}"})

url = self._resolve_path(request)
req_headers = self._request_headers(request)
params = self._resolve_query_params(request)
Expand Down Expand Up @@ -371,12 +402,13 @@ def __init__(
*,
base_url: str,
workspace: str | None = None,
auth: TokenProvider | str | None = None,
default_headers: Mapping[str, str] | None = None,
timeout: float = DEFAULT_TIMEOUT,
retry: RetryPolicy | None = None,
http_client: httpx.AsyncClient | None = None,
) -> None:
super().__init__(base_url=base_url, workspace=workspace, retry=retry)
super().__init__(base_url=base_url, workspace=workspace, auth=auth, retry=retry)
self._http = http_client or httpx.AsyncClient(
headers=dict(default_headers) if default_headers else None,
timeout=timeout,
Expand Down Expand Up @@ -423,6 +455,20 @@ async def send(
retry: RetryPolicy | None = None,
) -> NemoResponse[ResponseT]: ...

@classmethod
def from_config(
cls,
context: str | None = None,
config_path: Path | str | None = None,
) -> AsyncNemoClient:
"""Create an AsyncNemoClient from the user's nmp config file.

Args:
context: Context name to use (default: active context).
config_path: Path to config file (default: ``~/.config/nmp/config.yaml``).
"""
return _client_from_config(cls, context=context, config_path=config_path)

async def send(
self,
request: PreparedRequest,
Expand All @@ -434,6 +480,21 @@ async def send(
if headers:
request = request.with_headers(headers)

# Inject auth header. Three cases, in priority order:
# 1. Provider has get_access_token_async() (e.g. OIDCTokenProvider) — use it.
# 2. Provider.get_access_token() is a coroutine function — await it.
# 3. Provider.get_access_token() is sync — run in a thread to avoid
# blocking the event loop during IO (e.g. token refresh HTTP calls).
if self._auth:
get_async = getattr(self._auth, "get_access_token_async", None)
if get_async is not None and callable(get_async):
token = await get_async()
elif inspect.iscoroutinefunction(self._auth.get_access_token):
token = await self._auth.get_access_token()
else:
token = await asyncio.to_thread(self._auth.get_access_token)
request = request.with_headers({"Authorization": f"Bearer {token}"})

url = self._resolve_path(request)
req_headers = self._request_headers(request)
params = self._resolve_query_params(request)
Expand Down Expand Up @@ -514,3 +575,56 @@ async def fetch(request: PreparedRequest, page: int | str) -> httpx.Response:
return await self._request_with_retry(request, url, req_headers, params, retry)

return fetch


# ---------------------------------------------------------------------------
# from_config helper (shared by NemoClient and AsyncNemoClient)
# ---------------------------------------------------------------------------

_ClientT = TypeVar("_ClientT", NemoClient, AsyncNemoClient)


def _client_from_config(
cls: type[_ClientT],
*,
context: str | None = None,
config_path: Path | str | None = None,
) -> _ClientT:
"""Shared implementation for NemoClient.from_config / AsyncNemoClient.from_config."""
from nemo_platform_plugin.client.config.config import Config
from nemo_platform_plugin.client.config.models import ConfigParams, OAuthUser
from nemo_platform_plugin.client.oidc_factory import resolve_oidc_provider

resolved_path = Path(config_path) if isinstance(config_path, str) else config_path
overrides: ConfigParams | None = None
if context is not None:
overrides = {"current_context": context}
config = Config.load(config_path=resolved_path, overrides=overrides)
actual_config_path = config.get_config_path() or Config.get_default_config_path()
config_exists = actual_config_path.exists()
# If the token came from NMP_ACCESS_TOKEN (env override), it's not from
# the config file — don't cache or persist provider state for it.
explicit_access_token = config.access_token is not None
ctx = config.resolve()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

auth: TokenProvider | str | None = None

if isinstance(ctx.user, OAuthUser):
auth = resolve_oidc_provider(
base_url=str(ctx.cluster.base_url),
context_name=ctx.context_name,
access_token=ctx.user.token.get_secret_value(),
refresh_token=ctx.user.refresh_token.get_secret_value() if ctx.user.refresh_token else None,
config_exists=config_exists,
config_path=actual_config_path,
explicit_access_token=explicit_access_token,
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
elif ctx.user:
client_config = ctx.user.get_client_config()
raw_headers = client_config.get("default_headers")
if isinstance(raw_headers, dict):
raw_auth = dict(raw_headers).get("Authorization")
if isinstance(raw_auth, str) and raw_auth.startswith("Bearer "):
auth = raw_auth.removeprefix("Bearer ")

return cls(base_url=str(ctx.cluster.base_url), workspace=ctx.workspace, auth=auth)
Loading