Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
35 changes: 35 additions & 0 deletions nitrostack/auth/oauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,11 +80,36 @@ def __init__(
enable_client_registration: Optional[bool] = None,
static_client_id: Optional[str] = None,
static_client_secret: Union[SecretValue, str, None] = None,
discovery_auto_retry: Optional[bool] = None,
discovery_max_retries: Optional[int] = None,
):
self.resource_uri = resource_uri
self.authorization_servers = authorization_servers
self.scopes_supported = scopes_supported
self.discovery_port = discovery_port
if discovery_auto_retry is not None:
self.discovery_auto_retry = discovery_auto_retry
else:
env_retry = os.environ.get("OAUTH_DISCOVERY_AUTO_RETRY")
self.discovery_auto_retry = (
env_retry.strip().lower() not in ("false", "0", "no", "off")
if env_retry is not None
else True
)

if discovery_max_retries is not None:
self.discovery_max_retries = discovery_max_retries
else:
raw_max_retries = os.environ.get("OAUTH_DISCOVERY_MAX_RETRIES")
if raw_max_retries is not None:
try:
self.discovery_max_retries = int(raw_max_retries)
except ValueError:
self.discovery_max_retries = 50
else:
self.discovery_max_retries = 50

self.bound_port: Optional[int] = None

# Introspection settings fall back to the environment when not passed
# explicitly. Both spellings of the endpoint variable are accepted: the
Expand Down Expand Up @@ -147,6 +172,10 @@ def start_discovery_server(self) -> None:
"""Starts a background HTTP discovery server for OAuth Protected Resource metadata."""
start_discovery_server(self)

def get_port(self) -> Optional[int]:
"""Returns the actual port bound by the discovery server, or None if not running."""
return self.bound_port

def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]:
"""Raise ``TokenInactiveError`` / ``AudienceMismatchError`` for an introspection result."""
if token_info.get("error") == "audience_mismatch" or (
Expand All @@ -160,10 +189,12 @@ def raise_if_invalid(self, token_info: Dict[str, Any]) -> Dict[str, Any]:
def stop_discovery_server(self) -> None:
if self._server:
self._server.shutdown()
self._server.server_close()
self._server = None
if self._thread:
self._thread.join(timeout=1.0)
self._thread = None
self.bound_port = None

async def introspect_token(self, token: str) -> Dict[str, Any]:
"""
Expand Down Expand Up @@ -248,6 +279,8 @@ def for_root(
enable_client_registration: Optional[bool] = None,
static_client_id: Optional[str] = None,
static_client_secret: Union[SecretValue, str, None] = None,
discovery_auto_retry: Optional[bool] = None,
discovery_max_retries: Optional[int] = None,
):
if not resource_uri or not str(resource_uri).strip():
raise ConfigurationError("OAuthModule.for_root requires resource_uri")
Expand All @@ -270,6 +303,8 @@ def for_root(
enable_client_registration=enable_client_registration,
static_client_id=static_client_id,
static_client_secret=static_client_secret,
discovery_auto_retry=discovery_auto_retry,
discovery_max_retries=discovery_max_retries,
)
DIContainer.get_instance().register_value(OAuthService, service)
warn_if_oauth_fail_open()
Expand Down
70 changes: 49 additions & 21 deletions nitrostack/auth/oauth_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,11 @@ def _trusted_public_origin(self) -> Optional[str]:
peer = self._proxy_peer()
if not trusted_forwarded_host(headers, peer):
return None
port = service_instance.bound_port or service_instance.discovery_port
return public_origin(
headers,
peer,
fallback_host=f"localhost:{service_instance.discovery_port}",
fallback_host=f"localhost:{port}",
fallback_proto="http",
)

Expand Down Expand Up @@ -141,25 +142,52 @@ def do_POST(self):

_write_json(self, 200, build_registration_response(service_instance, body))

def run_server():
# Try binding to OAUTH_DISCOVERY_PORT
port = int(os.environ.get("OAUTH_DISCOVERY_PORT", service.discovery_port))
raw_port = os.environ.get("OAUTH_DISCOVERY_PORT")
if raw_port is not None:
try:
service._server = HTTPServer(("localhost", port), DiscoveryHandler)
# Notify client via stderr
oauth_metadata = {
"port": port,
"resource_uri": service.resource_uri,
"authorization_servers": service.authorization_servers
}
sys.stderr.write(
f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n"
)
sys.stderr.flush()
service._server.serve_forever()
except Exception as e:
sys.stderr.write(f"Failed to start OAuth Discovery Server on port {port}: {e}\n")
sys.stderr.flush()

service._thread = threading.Thread(target=run_server, daemon=True)
start_port = int(raw_port)
except ValueError:
start_port = service.discovery_port
else:
start_port = service.discovery_port

max_retries = max(0, service.discovery_max_retries) if service.discovery_auto_retry else 0
last_error: Optional[Exception] = None
bound_server: Optional[HTTPServer] = None

for attempt in range(max_retries + 1):
candidate_port = start_port + attempt
if candidate_port > 65535:
if last_error is None:
last_error = OverflowError("bind(): port must be 0-65535")
break
try:
server = HTTPServer(("localhost", candidate_port), DiscoveryHandler)
bound_server = server
service.bound_port = server.server_address[1]
break
except (OSError, OverflowError) as e:
last_error = e

if bound_server is None:
sys.stderr.write(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}\n")
sys.stderr.flush()
if isinstance(last_error, OSError):
raise last_error
raise OSError(f"Failed to start OAuth Discovery Server on port {start_port}: {last_error}") from last_error

service._server = bound_server

# Notify client via stderr
oauth_metadata = {
"port": service.bound_port,
"resource_uri": service.resource_uri,
"authorization_servers": service.authorization_servers,
}
sys.stderr.write(
f"[NITROSTACK_OAUTH]{json.dumps(oauth_metadata)}[/NITROSTACK_OAUTH]\n"
)
sys.stderr.flush()

service._thread = threading.Thread(target=service._server.serve_forever, daemon=True)
service._thread.start()
4 changes: 4 additions & 0 deletions nitrostack/templates/flight-booking/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,7 @@ NITROSTACK_APP_MODE=universal
# Unset by default so Studio can call tools without a token (TS default).
# Set to true only when testing real OAuth enforcement.
# OAUTH_REQUIRED=true
# OAuth Discovery Settings (Optional)
# OAUTH_DISCOVERY_PORT=3005
# OAUTH_DISCOVERY_AUTO_RETRY=true
# OAUTH_DISCOVERY_MAX_RETRIES=50
2 changes: 2 additions & 0 deletions nitrostack/templates/flight-booking/OAUTH_SETUP.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ TOKEN_ISSUER=https://your-tenant.us.auth0.com/
# OAUTH_TOKEN_CACHE_SECONDS=300
# Port for the .well-known discovery server (default 3005).
# OAUTH_DISCOVERY_PORT=3005
# OAUTH_DISCOVERY_AUTO_RETRY=true
# OAUTH_DISCOVERY_MAX_RETRIES=50
```

## 2. Protected Routes
Expand Down
5 changes: 4 additions & 1 deletion scripts/probe_discovery_port.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,11 @@ def free_port() -> int:
server = getattr(service, "_server", None)
print("server object:", server)
print("bound to:", getattr(server, "server_address", None))
bound_port = getattr(service, "bound_port", None)
print("reported bound_port:", bound_port)
target_port = bound_port or port
try:
url = f"http://127.0.0.1:{port}/.well-known/oauth-protected-resource"
url = f"http://127.0.0.1:{target_port}/.well-known/oauth-protected-resource"
with urllib.request.urlopen(url, timeout=2) as resp:
print("GET", url, "->", resp.status)
except Exception as exc:
Expand Down
159 changes: 159 additions & 0 deletions tests/test_oauth_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,162 @@ def test_warn_if_oauth_fail_open_writes_once(monkeypatch, capsys):
assert "OAuth is configured" in err
assert oauth._oauth_fail_open_warned is True
oauth._oauth_fail_open_warned = False


def test_discovery_server_busy_port_with_retry(capsys):
port = _free_port()
blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
blocker.bind(("127.0.0.1", port))
blocker.listen(1)

OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=port,
)
service = DIContainer.get_instance().resolve(OAuthService)
try:
service.start_discovery_server()
assert service.bound_port is not None
assert service.bound_port != port
assert service.get_port() == service.bound_port
assert service._server is not None

err = capsys.readouterr().err
assert f'"port": {service.bound_port}' in err

with urllib.request.urlopen(
f"http://127.0.0.1:{service.bound_port}/.well-known/oauth-protected-resource",
timeout=1.0,
) as resp:
body = json.loads(resp.read().decode("utf-8"))
assert body["resource"] == "http://localhost:3000/mcp"
finally:
service.stop_discovery_server()
blocker.close()


def test_discovery_server_retries_exhausted(capsys):
import pytest

port = _free_port()
blockers = []
for p in (port, port + 1):
b = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
b.bind(("127.0.0.1", p))
b.listen(1)
blockers.append(b)

OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=port,
discovery_max_retries=1,
)
service = DIContainer.get_instance().resolve(OAuthService)
try:
with pytest.raises(OSError):
service.start_discovery_server()
assert service._server is None
assert service.bound_port is None
assert service.get_port() is None
err = capsys.readouterr().err
assert f"Failed to start OAuth Discovery Server on port {port}" in err
finally:
service.stop_discovery_server()
for b in blockers:
b.close()


def test_discovery_server_auto_retry_disabled_surfaces_bind_failure(capsys, monkeypatch):
import pytest

port = _free_port()
blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
blocker.bind(("127.0.0.1", port))
blocker.listen(1)

monkeypatch.setenv("OAUTH_DISCOVERY_AUTO_RETRY", "false")
OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=port,
)
service = DIContainer.get_instance().resolve(OAuthService)
try:
with pytest.raises(OSError):
service.start_discovery_server()
assert service._server is None
assert service.bound_port is None
err = capsys.readouterr().err
assert f"Failed to start OAuth Discovery Server on port {port}" in err
finally:
service.stop_discovery_server()
blocker.close()


def test_discovery_server_reports_actual_bound_port(capsys):
port = _free_port()
OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=port,
)
service = DIContainer.get_instance().resolve(OAuthService)
try:
service.start_discovery_server()
assert service.bound_port == port
assert service.get_port() == port
err = capsys.readouterr().err
assert f'"port": {port}' in err
finally:
service.stop_discovery_server()
assert service.bound_port is None
assert service.get_port() is None


def test_discovery_server_port_overflow_surfaces_oserror(capsys):
import pytest

port = 65535
blocker = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
blocker.bind(("127.0.0.1", port))
blocker.listen(1)
except OSError:
pytest.skip("Port 65535 unavailable for test")

OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=port,
discovery_auto_retry=True,
)
service = DIContainer.get_instance().resolve(OAuthService)
try:
with pytest.raises(OSError):
service.start_discovery_server()
assert service._server is None
assert service.bound_port is None
err = capsys.readouterr().err
assert f"Failed to start OAuth Discovery Server on port {port}" in err
finally:
service.stop_discovery_server()
blocker.close()


def test_discovery_server_invalid_max_retries_falls_back_to_default(monkeypatch):
monkeypatch.setenv("OAUTH_DISCOVERY_MAX_RETRIES", "abc")
OAuthModule.for_root(
resource_uri="http://localhost:3000/mcp",
authorization_servers=["http://auth.example/oauth"],
scopes_supported=["read"],
discovery_port=3005,
)
service = DIContainer.get_instance().resolve(OAuthService)
assert service.discovery_max_retries == 50
Loading