Skip to content

Commit f03df62

Browse files
refactor: rename pre_authenticate option to use_eager_auth
Signed-off-by: Patrick Chin <8509935+thepatrickchin@users.noreply.github.com>
1 parent 0effe17 commit f03df62

File tree

6 files changed

+23
-24
lines changed

6 files changed

+23
-24
lines changed

docs/source/components/auth/api-authentication.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -114,8 +114,8 @@ authentication:
114114
| `token_endpoint_auth_method` | Some token provider endpoints require specific types of authentication. For example `client_secret_post`. |
115115
| `redirect_uri` | The redirect URI for OAuth 2.0 authentication. Must match the registered redirect URI with the OAuth provider.|
116116
| `scopes` | List of permissions to the API provider (e.g., `read`, `write`). |
117-
| `pre_authenticate` | Whether to trigger authentication at WebSocket connection time before the user submits their first prompt, defaults to `False`. Only applies in `nat serve` mode. When enabled, tokens are cached for the session to avoid re-authentication on reconnect. |
118117
| `use_pkce` | Whether to use PKCE (Proof Key for Code Exchange) in the OAuth 2.0 flow, defaults to `False` |
118+
| `use_eager_auth` | Whether to trigger authentication at WebSocket connection time before the workflow requires credentials, defaults to `False`. When enabled, tokens are cached for the session to avoid re-authentication on reconnect. |
119119
| `use_redirect_auth` | Whether to use a redirect-based flow or open the OAuth consent page in a popup window, defaults to `False` (popup) |
120120
| `authorization_kwargs` | Additional keyword arguments to include in the authorization request. |
121121

examples/front_ends/simple_auth/src/nat_simple_auth/configs/config.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,8 @@ authentication:
5656
- email
5757
client_id: ${NAT_OAUTH_CLIENT_ID}
5858
client_secret: ${NAT_OAUTH_CLIENT_SECRET}
59-
pre_authenticate: false
6059
use_pkce: false
60+
use_eager_auth: false
6161
use_redirect_auth: false
6262

6363
workflow:

packages/nvidia_nat_core/src/nat/authentication/oauth2/oauth2_auth_code_flow_provider_config.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,10 @@ class OAuth2AuthCodeFlowProviderConfig(AuthProviderBaseConfig, name="oauth2_auth
4141
"remains open. When True, the browser navigates to the OAuth login page directly and is "
4242
"redirected back after authentication completes."))
4343

44-
pre_authenticate: bool = Field(
44+
use_eager_auth: bool = Field(
4545
default=False,
46-
description=("When True, authentication is triggered at WebSocket connection time before the user submits "
47-
"their first prompt. When False (default), authentication is deferred until the workflow first "
48-
"requires credentials. Only applies in nat serve mode."))
46+
description=("When False (default), authentication is deferred until the workflow first requires "
47+
"credentials. When True, authentication is triggered at WebSocket connection time."))
4948

5049
authorization_kwargs: dict[str, str] | None = Field(description=("Additional keyword arguments for the "
5150
"authorization request."),

packages/nvidia_nat_core/src/nat/front_ends/fastapi/auth_flow_handlers/websocket_flow_handler.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -75,15 +75,15 @@ async def authenticate(
7575

7676
raise NotImplementedError(f"Authentication method '{method}' is not supported by the websocket frontend.")
7777

78-
async def pre_authenticate(self, auth_providers: dict[str, AuthProviderBaseConfig]) -> None:
78+
async def run_eager_auth(self, auth_providers: dict[str, AuthProviderBaseConfig]) -> None:
7979
"""Run auth for every configured OAuth2 provider before the first user message.
8080
81-
Only providers with pre_authenticate option set in their config are processed.
81+
Only providers with use_eager_auth option set in their config are processed.
8282
Returns immediately if tokens are already cached. Otherwise triggers the OAuth
8383
redirect so the user authenticates at page load rather than mid-workflow.
8484
"""
8585
for provider_config in auth_providers.values():
86-
if isinstance(provider_config, OAuth2AuthCodeFlowProviderConfig) and provider_config.pre_authenticate:
86+
if isinstance(provider_config, OAuth2AuthCodeFlowProviderConfig) and provider_config.use_eager_auth:
8787
await self.authenticate(provider_config, AuthFlowType.OAUTH2_AUTHORIZATION_CODE)
8888

8989
def create_oauth_client(self, config: OAuth2AuthCodeFlowProviderConfig) -> AsyncOAuth2Client:

packages/nvidia_nat_core/src/nat/front_ends/fastapi/routes/websocket.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ async def _websocket_endpoint(websocket: WebSocket):
107107
skip_pre_auth = websocket.query_params.get("skip_pre_auth") == "true"
108108
if not skip_pre_auth:
109109
try:
110-
await flow_handler.pre_authenticate(worker._config.authentication)
110+
await flow_handler.run_eager_auth(worker._config.authentication)
111111
except Exception as e:
112112
logger.info("Pre-authentication did not complete: %s", e)
113113
await handler.run()

packages/nvidia_nat_core/tests/nat/front_ends/auth_flow_handlers/test_websocket_flow_handler.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -500,22 +500,22 @@ async def create_websocket_message(self, msg):
500500

501501

502502
# --------------------------------------------------------------------------- #
503-
# pre_authenticate tests #
503+
# run_eager_auth tests #
504504
# --------------------------------------------------------------------------- #
505-
async def test_pre_authenticate_skips_non_oauth2_providers(noop_handler):
506-
"""pre_authenticate is a no-op for non-OAuth2 providers such as APIKeyAuthProviderConfig."""
505+
async def test_run_eager_auth_skips_non_oauth2_providers(noop_handler):
506+
"""run_eager_auth is a no-op for non-OAuth2 providers such as APIKeyAuthProviderConfig."""
507507
api_key_config = APIKeyAuthProviderConfig(raw_key="my-api-key-value")
508-
await noop_handler.pre_authenticate({"my_api_key": api_key_config})
508+
await noop_handler.run_eager_auth({"my_api_key": api_key_config})
509509

510510

511-
async def test_pre_authenticate_skips_oauth2_provider_flag_false(noop_handler, minimal_oauth_config):
512-
"""pre_authenticate does not trigger auth for OAuth2 providers with pre_authenticate=False (the default)."""
513-
# minimal_oauth_config has pre_authenticate=False (the default); if the guard were absent this would hang
514-
await noop_handler.pre_authenticate({"my_provider": minimal_oauth_config})
511+
async def test_run_eager_auth_skips_oauth2_provider_flag_false(noop_handler, minimal_oauth_config):
512+
"""run_eager_auth does not trigger auth for OAuth2 providers with use_eager_auth=False (the default)."""
513+
# minimal_oauth_config has use_eager_auth=False (the default); if the guard were absent this would hang
514+
await noop_handler.run_eager_auth({"my_provider": minimal_oauth_config})
515515

516516

517-
async def test_pre_authenticate_uses_cached_token(minimal_oauth_config):
518-
"""pre_authenticate returns immediately without calling create_websocket_message on a cache hit."""
517+
async def test_run_eager_auth_uses_cached_token(minimal_oauth_config):
518+
"""run_eager_auth returns immediately without calling create_websocket_message on a cache hit."""
519519

520520
async def _noop_add(state, flow_state):
521521
pass
@@ -532,8 +532,8 @@ async def create_websocket_message(self, msg):
532532

533533
ctx = AuthenticatedContext(headers={"Authorization": "Bearer cached-tok"}, metadata={"expires_at": None})
534534
store: dict = {}
535-
# Enable pre_authenticate so the cache lookup is actually reached
536-
active_config = minimal_oauth_config.model_copy(update={"pre_authenticate": True})
535+
# Enable use_eager_auth so the cache lookup is actually reached
536+
active_config = minimal_oauth_config.model_copy(update={"use_eager_auth": True})
537537
handler = WebSocketAuthenticationFlowHandler(
538538
add_flow_cb=_noop_add,
539539
remove_flow_cb=_noop_remove,
@@ -544,5 +544,5 @@ async def create_websocket_message(self, msg):
544544
key = handler._token_cache_key(active_config)
545545
store[key] = (ctx, time.time() + 3600)
546546

547-
await handler.pre_authenticate({"my_provider": active_config})
548-
assert message_count[0] == 0, "pre_authenticate must not trigger OAuth when token is cached"
547+
await handler.run_eager_auth({"my_provider": active_config})
548+
assert message_count[0] == 0, "run_eager_auth must not trigger OAuth when token is cached"

0 commit comments

Comments
 (0)