Skip to content

Commit 33f6ae3

Browse files
committed
update
Signed-off-by: NAYANAR <[email protected]>
1 parent 951ab3b commit 33f6ae3

File tree

5 files changed

+18
-29
lines changed

5 files changed

+18
-29
lines changed

mcpgateway/config.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,8 @@
6060
import jq
6161
from jsonpath_ng.ext import parse
6262
from jsonpath_ng.jsonpath import JSONPath
63-
from pydantic import Field,field_validator
64-
from pydantic_settings import BaseSettings,NoDecode,SettingsConfigDict
63+
from pydantic import Field, field_validator
64+
from pydantic_settings import BaseSettings, NoDecode, SettingsConfigDict
6565

6666
logging.basicConfig(
6767
level=logging.INFO,
@@ -116,10 +116,7 @@ class Settings(BaseSettings):
116116
auth_required: bool = True
117117
token_expiry: int = 10080 # minutes
118118

119-
require_token_expiration: bool = Field(
120-
default=False, # Default to flexible mode for backward compatibility
121-
description="Require all JWT tokens to have expiration claims"
122-
)
119+
require_token_expiration: bool = Field(default=False, description="Require all JWT tokens to have expiration claims") # Default to flexible mode for backward compatibility
123120

124121
# Encryption key phrase for auth storage
125122
auth_encryption_secret: str = "my-test-salt"

mcpgateway/utils/create_jwt_token.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,8 +111,8 @@ def _create_jwt_token(
111111
"⚠️ WARNING: Creating token without expiration. This is a security risk!\n"
112112
" Consider using --exp with a value > 0 for production use.\n"
113113
" Once JWT API (#425) is available, use it for automatic token renewal.",
114-
file=sys.stderr
115-
)
114+
file=sys.stderr,
115+
)
116116
return jwt.encode(payload, secret, algorithm=algorithm)
117117

118118

mcpgateway/utils/verify_credentials.py

Lines changed: 8 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"""
4040

4141
# Standard
42+
import logging
4243
from typing import Optional
4344

4445
# Third-Party
@@ -51,20 +52,18 @@
5152
)
5253
from fastapi.security.utils import get_authorization_scheme_param
5354
import jwt
54-
from jwt import PyJWTError
55-
5655

5756
# First-Party
5857
from mcpgateway.config import settings
5958

6059
basic_security = HTTPBasic(auto_error=False)
6160
security = HTTPBearer(auto_error=False)
6261

63-
import logging
62+
# Standard
6463
logger = logging.getLogger(__name__)
6564

65+
6666
async def verify_jwt_token(token: str) -> dict:
67-
6867
"""Verify and decode a JWT token.
6968
7069
Decodes and validates a JWT token using the configured secret key
@@ -78,6 +77,7 @@ async def verify_jwt_token(token: str) -> dict:
7877
7978
Raises:
8079
HTTPException: 401 status if the token has expired or is invalid.
80+
MissingRequiredClaimError: If the 'exp' claim is required but missing.
8181
8282
Examples:
8383
>>> from mcpgateway.utils import verify_credentials as vc
@@ -143,23 +143,14 @@ async def verify_jwt_token(token: str) -> dict:
143143

144144
# Log warning for non-expiring tokens
145145
if "exp" not in unverified:
146-
logger.warning(
147-
"JWT token without expiration accepted. "
148-
"Consider enabling REQUIRE_TOKEN_EXPIRATION for better security. "
149-
f"Token sub: {unverified.get('sub', 'unknown')}"
150-
)
146+
logger.warning("JWT token without expiration accepted. " "Consider enabling REQUIRE_TOKEN_EXPIRATION for better security. " f"Token sub: {unverified.get('sub', 'unknown')}")
151147

152148
# Full validation
153149
options = {}
154150
if settings.require_token_expiration:
155151
options["require"] = ["exp"]
156152

157-
payload = jwt.decode(
158-
token,
159-
settings.jwt_secret_key,
160-
algorithms=[settings.jwt_algorithm],
161-
options=options
162-
)
153+
payload = jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm], options=options)
163154
return payload
164155

165156
except jwt.MissingRequiredClaimError:
@@ -180,7 +171,8 @@ async def verify_jwt_token(token: str) -> dict:
180171
detail="Invalid token",
181172
headers={"WWW-Authenticate": "Bearer"},
182173
)
183-
174+
175+
184176
async def verify_credentials(token: str) -> dict:
185177
"""Verify credentials using a JWT token.
186178

tests/security/test_rpc_endpoint_validation.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,14 +39,13 @@ class TestRPCEndpointValidation:
3939
@pytest.fixture
4040
def client(self):
4141
"""Create a test client for the FastAPI app."""
42-
return TestClient(app)
42+
return TestClient(app)
43+
4344
@pytest.fixture
4445
def auth_headers(self):
4546
"""Create authorization headers for testing."""
4647
# You might need to adjust this based on your auth setup
4748
return {"Authorization": "Bearer test-token", "Content-Type": "application/json"}
48-
49-
5049

5150
def test_rpc_endpoint_with_malicious_methods(self, client, auth_headers):
5251
"""Test that malicious method names are rejected before processing.

tests/unit/mcpgateway/utils/test_verify_credentials.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
# payload = payload | {"exp": int(expire.timestamp())}
4949
# return jwt.encode(payload, secret, algorithm=ALGO)
5050

51+
5152
def _token(payload: dict, *, exp_delta: int | None = 60, secret: str = SECRET) -> str:
5253
"""Return a signed JWT with optional expiry offset (minutes)."""
5354
if exp_delta is not None:
@@ -63,8 +64,8 @@ def _token(payload: dict, *, exp_delta: int | None = 60, secret: str = SECRET) -
6364
async def test_verify_jwt_token_success(monkeypatch):
6465
monkeypatch.setattr(vc.settings, "jwt_secret_key", SECRET, raising=False)
6566
monkeypatch.setattr(vc.settings, "jwt_algorithm", ALGO, raising=False)
66-
monkeypatch.setattr(vc.settings, "require_token_expiration", False, raising=False)
67-
67+
monkeypatch.setattr(vc.settings, "require_token_expiration", False, raising=False)
68+
6869
token = _token({"sub": "abc"})
6970
data = await vc.verify_jwt_token(token)
7071

0 commit comments

Comments
 (0)