Skip to content

πŸš€ The fast, Pythonic way to build MCP servers and clients.

Enable ruff flake8-bandit (S) rules on the library (#5356)

Bill Eastonf49946db1d09
diff --git a/fastmcp_slim/fastmcp/apps/app.py b/fastmcp_slim/fastmcp/apps/app.py
index 8a4dc64d0..63d12b8bd 100644
--- a/fastmcp_slim/fastmcp/apps/app.py
+++ b/fastmcp_slim/fastmcp/apps/app.py
@@ -95,7 +95,7 @@ def _make_resolver(app_name: str | None = None) -> Any:
fmeta = get_fastmcp_meta(fn)
except Exception:
- pass
+ logger.debug("Failed to resolve FastMCP metadata for %r", fn, exc_info=True)
if fmeta is not None:
name: str | None = getattr(fmeta, "name", None)
diff --git a/fastmcp_slim/fastmcp/server/auth/handlers/authorize.py b/fastmcp_slim/fastmcp/server/auth/handlers/authorize.py
index 6b7e6eab8..d560acd1d 100644
--- a/fastmcp_slim/fastmcp/server/auth/handlers/authorize.py
+++ b/fastmcp_slim/fastmcp/server/auth/handlers/authorize.py
@@ -274,7 +274,10 @@ class AuthorizationHandler(SDKAuthorizationHandler):
)
except Exception:
# If we can't parse the response, just return the original
- pass
+ logger.debug(
+ "Failed to parse authorize error response for enhancement",
+ exc_info=True,
+ )
return response
diff --git a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
index ff601b57c..fe2d06f73 100644
--- a/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
+++ b/fastmcp_slim/fastmcp/server/auth/oauth_proxy/proxy.py
@@ -2289,8 +2289,11 @@ class OAuthProxy(OAuthProvider, ConsentMixin):
)
if validated:
upstream_token_set = reloaded
- except Exception:
- pass
+ except Exception as reload_error:
+ logger.debug(
+ "Re-read of upstream token after refresh failure also failed: %s",
+ reload_error,
+ )
if not validated:
logger.debug("Upstream token validation failed")
diff --git a/fastmcp_slim/fastmcp/server/auth/providers/descope.py b/fastmcp_slim/fastmcp/server/auth/providers/descope.py
index 8928cb082..65f4de389 100644
--- a/fastmcp_slim/fastmcp/server/auth/providers/descope.py
+++ b/fastmcp_slim/fastmcp/server/auth/providers/descope.py
@@ -353,7 +353,14 @@ class DescopeProvider(RemoteAuthProvider):
response = await client.get(metadata_url)
response.raise_for_status()
return JSONResponse(response.json())
- except Exception:
+ except Exception as metadata_error:
+ # Don't log `metadata_url`: CodeQL's taint tracking
+ # flags it as sensitive (it's built from the same
+ # class attributes as authenticated request URLs
+ # elsewhere in this provider).
+ logger.debug(
+ "Failed to fetch Descope metadata: %s", metadata_error
+ )
continue
except Exception as e:
return JSONResponse(
diff --git a/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py b/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py
index 56c55109a..6ffba52e9 100644
--- a/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py
+++ b/fastmcp_slim/fastmcp/server/providers/filesystem_discovery.py
@@ -133,7 +133,9 @@ def _package_path_matches(module: ModuleType, package_root: Path) -> bool:
def _private_package_prefix(directory: Path) -> str:
"""Compute a collision-safe synthetic package name anchored at a directory."""
- digest = hashlib.sha1(str(directory.resolve()).encode()).hexdigest()[:12]
+ digest = hashlib.sha1(
+ str(directory.resolve()).encode(), usedforsecurity=False
+ ).hexdigest()[:12]
return f"_fastmcp_pkg_{digest}"
@@ -233,7 +235,10 @@ def import_module_from_file(
if existing is not None and getattr(existing, "__file__", None) != str(
file_path
):
- module_name = f"_fastmcp_{stem}_{hashlib.sha1(str(file_path).encode()).hexdigest()[:12]}"
+ digest = hashlib.sha1(
+ str(file_path).encode(), usedforsecurity=False
+ ).hexdigest()[:12]
+ module_name = f"_fastmcp_{stem}_{digest}"
else:
module_name = stem
diff --git a/fastmcp_slim/fastmcp/server/providers/skills/_common.py b/fastmcp_slim/fastmcp/server/providers/skills/_common.py
index 916cbf533..473c2de40 100644
--- a/fastmcp_slim/fastmcp/server/providers/skills/_common.py
+++ b/fastmcp_slim/fastmcp/server/providers/skills/_common.py
@@ -102,7 +102,10 @@ def parse_frontmatter(content: str) -> tuple[dict[str, Any], str]:
remaining = content[3 + end_match.end() :]
try:
- parsed = yaml.load(frontmatter_text, Loader=yaml.BaseLoader)
+ # yaml.BaseLoader resolves everything to plain strings and never
+ # constructs Python objects, unlike yaml.Loader/UnsafeLoader/FullLoader
+ # - it's the loader SafeLoader itself is built on top of.
+ parsed = yaml.load(frontmatter_text, Loader=yaml.BaseLoader) # noqa: S506
except (yaml.YAMLError, RecursionError):
# Prefer partial recovery over discarding every key (issue #4416 review).
return _parse_frontmatter_line_based(frontmatter_text), remaining
diff --git a/fastmcp_slim/fastmcp/utilities/auth.py b/fastmcp_slim/fastmcp/utilities/auth.py
index 03eb59bb3..3b3c012ef 100644
--- a/fastmcp_slim/fastmcp/utilities/auth.py
+++ b/fastmcp_slim/fastmcp/utilities/auth.py
@@ -6,6 +6,10 @@ import base64
import json
from typing import Any
+from fastmcp.utilities.logging import get_logger
+
+logger = get_logger(__name__)
+
def _decode_jwt_part(token: str, part_index: int) -> dict[str, Any]:
"""Decode a JWT part (header or payload) without signature verification.
@@ -85,7 +89,10 @@ def parse_scopes(value: Any) -> list[str] | None:
if isinstance(data, list):
return [str(v).strip() for v in data if str(v).strip()]
except Exception:
- pass
+ # Don't log `value`: callers pass scopes pulled straight out of
+ # token exchange responses, which CodeQL's taint tracking (and
+ # potentially a real payload) treats as sensitive.
+ logger.debug("Failed to parse scopes value as a JSON array")
# Fallback to comma/space separated list
return [s.strip() for s in value.replace(",", " ").split() if s.strip()]
return value
diff --git a/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py b/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py
index b926bebcd..c7009fa94 100644
--- a/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py
+++ b/fastmcp_slim/fastmcp/utilities/mcp_server_config/v1/mcp_server_config.py
@@ -44,7 +44,7 @@ class Deployment(BaseModel):
host: str | None = Field(
default=None,
description="Host to bind to when using HTTP transport",
- examples=["127.0.0.1", "0.0.0.0", "localhost"],
+ examples=["127.0.0.1", "0.0.0.0", "localhost"], # noqa: S104 - schema example values, not a bind default
)
port: int | None = Field(
diff --git a/pyproject.toml b/pyproject.toml
index 3661f18e3..a9f34463a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -192,6 +192,19 @@ ignore = [
"PERF203",
"PLR0913",
"SIM102",
+ # flake8-bandit rules with a high false-positive rate in this codebase:
+ # `assert` is idiomatic Python (S101); subprocess calls here already use
+ # arg lists, not shell strings (S603); and "password"/"token"-named
+ # parameters and defaults are routinely non-secret in an OAuth/JWT
+ # framework (S105-S107). S606/S607 (bare command name, e.g. "uv") are a
+ # style preference, not a vulnerability, for our CLI's subprocess use.
+ "S101",
+ "S105",
+ "S106",
+ "S107",
+ "S603",
+ "S606",
+ "S607",
]
extend-select = [
"B",
@@ -209,6 +222,7 @@ extend-select = [
"PLE",
"RSE",
"RUF",
+ "S",
"SIM",
"SLOT",
"T20",
@@ -240,6 +254,7 @@ known-first-party = ["fastmcp", "fastmcp_remote"]
"PLE",
"RSE",
"RUF",
+ "S",
"SIM",
"SLOT",
"T20",