Skip to content

fix(auth): retry on busy port and report bound port in discovery server - #134

Open
AadarshM07 wants to merge 1 commit into
nitrocloudofficial:developfrom
AadarshM07:issue#117
Open

AadarshM07 wants to merge 1 commit into
nitrocloudofficial:developfrom
AadarshM07:issue#117

Conversation

@AadarshM07

Copy link
Copy Markdown
Collaborator

Summary

Follow-up from the #77 investigation (#104, docs/investigations/discovery-http-server.md).

Closes #117

Changes

  • nitrostack/auth/oauth.py:
    • Added discovery_auto_retry and discovery_max_retries parameters and env var fallbacks (OAUTH_DISCOVERY_AUTO_RETRY, OAUTH_DISCOVERY_MAX_RETRIES) to OAuthService and OAuthModule.for_root().
    • Added bound_port attribute and get_port() getter method.
    • Updated start_discovery_server() to attempt binding up to max_retries times, surface OSError on failure, and emit the actual bound port in the [NITROSTACK_OAUTH] stderr marker.
    • Updated _trusted_public_origin() to use bound_port or discovery_port.
    • Reset bound_port and invoke server_close() in stop_discovery_server().
  • scripts/probe_discovery_port.py:
    • Updated probe to read service.bound_port and verify GET against the bound port.
  • tests/test_oauth_discovery.py:
    • Added unit tests for busy port with retry, retries exhausted, retry disabled, and bound port reporting.

Testing

  • uv run pytest tests/test_oauth_discovery.py -v (7 passed)
  • uv run pytest tests/test_oauth.py (34 passed)
  • python scripts/probe_discovery_port.py (verified retry on occupied port, bound port reporting, and 200 GET)
image

@AadarshM07 AadarshM07 linked an issue Nov 8, 2026 that may be closed by this pull request
4 tasks
@manish-wekan

Copy link
Copy Markdown
Collaborator

Path to the env.example in the typescript-sdk
/nitrostack/typescript/packages/cli/templates/typescript-oauth/.env.example

# NitroStack Configuration
NITRO_LOG_LEVEL=info
NITROSTACK_APP_MODE=universal

# Server Transport Configuration (Optional)
# =============================================================================
# MCP_TRANSPORT_TYPE: Toggles transport mode. Values: stdio | http | dual.
# Defaults to 'stdio' in development and 'dual' in production/NODE_ENV=production.
# =============================================================================
# MCP_TRANSPORT_TYPE=dual
# PORT=3000
# HOST=localhost
# ENABLE_CORS=true

# MCP Protocol Version (Optional)
# =============================================================================
# NITRO_MCP_PROTOCOL_VERSION selects which MCP wire revision NitroStack speaks.
# Unset (default) defaults to 'auto' (serves 2026-07-28 stateless with legacy fallback).
#   - auto       : serve both eras from one process (default).
#   - 2026-07-28 : the new stateless spec (server/discover, per-request _meta,
#                  Mcp-Method/Mcp-Name headers, cache hints, MRTR, extensions).
#   - 2025-06-18 : the legacy 2025 sessionful spec.
# On 2026, Dynamic Client Registration (below) is deprecated in favor of CIMD.
# Your @Tool/@Resource/@Prompt/@Widget code is identical either way.
# =============================================================================
# NITRO_MCP_PROTOCOL_VERSION=auto

# Streamable HTTP Session Limits (Optional)
# =============================================================================
# Bounds memory against unauthenticated initialize floods. Defaults: 1000 sessions,
# 30-minute idle timeout. Only applies when running in http or dual transport mode.
# =============================================================================
# MCP_MAX_SESSIONS=1000
# MCP_SESSION_TIMEOUT_MS=1800000

# OAuth 2.1 MCP Server Configuration
# =============================================================================
# Enforcement Gate (Optional)
# =============================================================================
# OAUTH_REQUIRED controls whether authentication is enforced.
#   - Unset / false (default): auth is NOT enforced. The server runs out-of-the-box
#     and protected endpoints are reachable without a token. Best for local dev.
#   - true: auth is enforced (fail-closed). If neither JWKS_URI nor
#     INTROSPECTION_ENDPOINT is configured, the server STILL starts and logs a
#     clear warning, but rejects all protected requests until a verifier is set.
# Set this to true (and configure a verifier below) before deploying.
# =============================================================================
# OAUTH_REQUIRED=true

# =============================================================================
# REQUIRED: Server Configuration
# =============================================================================
# Your Auth0 API Identifier (from APIs → MCP Server → Identifier)
# This MUST match exactly what you set when creating the API
RESOURCE_URI=https://mcplocal

# Your Auth0 tenant domain (authorization server URL)
AUTH_SERVER_URL=https://dev-5dt0utuk315713tjm.us.auth0.com

# Cryptographic JWKS Signature Verification (Recommended)
# =============================================================================
# If configured, the SDK cryptographically verifies token signatures using JWKS keys.
# Token validation is SECURE BY DEFAULT (fail-closed): if neither JWKS_URI nor an
# introspection endpoint (below) is configured, ALL tokens are rejected. Configure
# one of them for a working server.
# NOTE: Unsigned/signature-less token decoding is disabled by default and is only
# available via the in-code `allowInsecureTokenDecode: true` option in
# OAuthModule.forRoot(...) — intended for local development only, never production.
# =============================================================================
# JWKS_URI=https://dev-5dt0utuk315713tjm.us.auth0.com/.well-known/jwks.json

# Expected token validation audience (should match RESOURCE_URI)
TOKEN_AUDIENCE=https://mcplocal

# Expected token validation issuer (your authorization server tenant domain)
TOKEN_ISSUER=https://dev-5dt0utuk315713tjm.us.auth0.com

# Token Introspection Configuration (Alternative to JWKS signature verification)
# =============================================================================
# INTROSPECTION_ENDPOINT=https://dev-5dt0utuk315713tjm.us.auth0.com/oauth/introspect
# INTROSPECTION_CLIENT_ID=your-introspection-client-id
# INTROSPECTION_CLIENT_SECRET=your-introspection-client-secret

# OAuth Discovery Settings (Optional)
# =============================================================================
# OAUTH_DISCOVERY_PORT=3005
# OAUTH_DISCOVERY_AUTO_RETRY=true
# MCP_SERVER_PORT=3000

# Dynamic Client Registration (Optional / disabled by default)
# =============================================================================
# Set to 'true' to expose the /oauth/v2/register endpoint. It only serves the
# statically configured client below; without OAUTH_CLIENT_ID it stays disabled.
# =============================================================================
# OAUTH_ENABLE_CLIENT_REGISTRATION=true
# OAUTH_CLIENT_ID=your-client-id
# OAUTH_CLIENT_SECRET=your-client-secret

# Duffel API Integration (Required for Flight Search & Booking)
# =============================================================================
DUFFEL_API_KEY=your-duffel-api-key

@manish-wekan
manish-wekan requested a review from ROHIT-JR November 9, 2026 12:08
@AadarshM07
AadarshM07 force-pushed the issue#117 branch 2 times, most recently from 3a1a304 to 5913ed2 Compare November 9, 2026 15:31
@AadarshM07

Copy link
Copy Markdown
Collaborator Author

Hi, I have addressed the changes. Updated the .env.example in fligth oauth template.

cc: @manish-wekan @ROHIT-JR

@ROHIT-JR ROHIT-JR left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The discovery-server change itself is right and matches #117: retry on a busy port, bound_port and get_port(), the actual port in the [NITROSTACK_OAUTH] marker, and the bind error now surfaces. The new tests and test_oauth.py pass on my run, and the probe script change is fine. I'm requesting changes for two things.

1. The flight-booking/.env.example rewrite is out of scope and partly wrong for Python. The change for #117 needed only the two new variables, but this file grows by about 100 lines, copied from the TypeScript template (commit 5ecdc19):

  • It mentions OAuthModule.forRoot(...), allowInsecureTokenDecode: true and @Tool/@Resource/@Prompt/@Widget. None of these exist in the Python SDK (allowInsecureTokenDecode appears nowhere in nitrostack/).
  • It removes PORT=3000, NODE_ENV=development and the note about OAUTH_REQUIRED for Studio, and the template's own app_module.py still uses PORT as a default.
  • Anyone who runs init --template flight-booking gets this file, so it should not change in a PR about a port retry.

Please revert that file to develop's version and add only these two lines under the existing discovery settings, or send the template refresh as its own PR with Python wording.

2. Two inputs raise errors that are not OSError.

  • If the discovery port is 65535 and busy, the retry goes to port 65536 and raises OverflowError: bind(): port must be 0-65535 instead of the clear "Failed to start" message and OSError. Stop the retries at 65535, or catch OverflowError with the other bind errors.
  • OAUTH_DISCOVERY_MAX_RETRIES=abc raises a bare ValueError while building OAuthService. Fall back to the default (or raise a ConfigurationError that names the variable).

Please add a test for each.

Small, not blocking: .file_length_baseline.json now also drops the views.py and route_templates.py entries. That is correct, since both are now under 500 lines, but it is unrelated cleanup, so a short mention in the description would help.

@AadarshM07

Copy link
Copy Markdown
Collaborator Author

Hi @ROHIT-JR , Thanks for the review! Both points have been addressed:

  1. Reverted flight-booking/.env.example: Restored the clean develop template and added only the three optional discovery settings (OAUTH_DISCOVERY_PORT, OAUTH_DISCOVERY_AUTO_RETRY, OAUTH_DISCOVERY_MAX_RETRIES).
  2. Edge case exception handling:
    • Added a bounds check (candidate_port <= 65535) and caught OverflowError during retries so collisions at port 65535 stop gracefully and surface the clear Failed to start message as an OSError.
    • Wrapped OAUTH_DISCOVERY_MAX_RETRIES parsing in a try/except ValueError to fall back to the default of 50 on invalid inputs like abc.
    • Added unit tests for both edge cases (test_discovery_server_port_overflow_surfaces_oserror and test_discovery_server_invalid_max_retries_falls_back_to_default).

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[auth] OAuth discovery server: retry on busy port and report the bound port

3 participants