Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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,61 @@
# 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 @@ -15,10 +15,17 @@

from __future__ import annotations

import asyncio
import inspect
from collections.abc import Mapping
from pathlib import Path
from typing import 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,
AsyncNemoStreamResponse,
Expand Down Expand Up @@ -49,9 +56,16 @@ class BaseNemoClient:
Subclasses provide the actual HTTP transport (sync or async).
"""

def __init__(self, *, base_url: str, workspace: str | None = None) -> None:
def __init__(
self,
*,
base_url: str,
workspace: str | None = None,
auth: TokenProvider | str | None = None,
) -> None:
self._base_url = base_url.rstrip("/")
self._workspace = workspace
self._auth: TokenProvider | None = StaticToken(auth) if isinstance(auth, str) else auth

@property
def base_url(self) -> str:
Expand Down Expand Up @@ -108,11 +122,12 @@ 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,
http_client: httpx.Client | None = None,
) -> None:
super().__init__(base_url=base_url, workspace=workspace)
super().__init__(base_url=base_url, workspace=workspace, auth=auth)
self._http = http_client or httpx.Client(
headers=dict(default_headers) if default_headers else None,
timeout=timeout,
Expand All @@ -133,6 +148,20 @@ def send(
self, request: PreparedRequest[ResponseT], *, headers: dict[str, str] | 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, *, headers: dict[str, str] | None = None
) -> NemoResponse | NemoBinaryResponse | NemoStreamResponse:
Expand All @@ -152,6 +181,15 @@ 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 @@ -188,11 +226,12 @@ 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,
http_client: httpx.AsyncClient | None = None,
) -> None:
super().__init__(base_url=base_url, workspace=workspace)
super().__init__(base_url=base_url, workspace=workspace, auth=auth)
self._http = http_client or httpx.AsyncClient(
headers=dict(default_headers) if default_headers else None,
timeout=timeout,
Expand All @@ -215,12 +254,42 @@ async def send(
self, request: PreparedRequest[ResponseT], *, headers: dict[str, str] | 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, *, headers: dict[str, str] | None = None
) -> NemoResponse | AsyncNemoBinaryResponse | AsyncNemoStreamResponse:
"""Send a prepared request and return a typed response."""
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 All @@ -244,3 +313,49 @@ async def send(
if raw.is_success and request.response_type is not None:
body = request.response_type.model_validate(raw.json())
return NemoResponse(http_response=raw, body=body, request=request)


# ---------------------------------------------------------------------------
# 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.oidc_factory import resolve_oidc_provider
from nemo_platform_plugin.client.config.config import Config
from nemo_platform_plugin.client.config.models import OAuthUser

resolved_path = Path(config_path) if isinstance(config_path, str) else config_path
config = Config.load(config_path=resolved_path)
actual_config_path = config.get_config_path() or Config.get_default_config_path()
config_exists = actual_config_path.exists()
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,
)
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
Loading