feat(mcp): per-user scope restrictions for BasicAuth mode#628
Open
tkaufmann wants to merge 16 commits into
Open
feat(mcp): per-user scope restrictions for BasicAuth mode#628tkaufmann wants to merge 16 commits into
tkaufmann wants to merge 16 commits into
Conversation
User-provided values (display names, search patterns, MIME types, tag names) were interpolated into XML bodies via f-strings without escaping. A malicious input could inject XML structures, alter WebDAV search queries, or cause malformed XML errors. Add escape_xml() utility using xml.sax.saxutils.escape and apply it to all user-controlled values in CalDAV, CardDAV, and WebDAV XML bodies.
Replace bare .lstrip('/') with sanitize_webdav_path() that normalizes
paths via posixpath.normpath and rejects any containing '..' components.
Nextcloud blocks traversal server-side, but this adds defense-in-depth
against path manipulation by untrusted MCP clients.
Replace xml.etree.ElementTree with defusedxml.ElementTree in WebDAV and CardDAV clients to block XXE attacks (billion laughs, external entity loading). For the lxml-based CalDAV parser, configure XMLParser with resolve_entities=False and no_network=True.
Validate the 'next' query parameter in OAuth login/logout/callback to only allow relative paths. Reject absolute URLs, protocol-relative URLs, and any URL containing '://' to prevent redirect-based phishing attacks.
Add a dedicated appuser (UID 10001) and switch to it before the entrypoint. Also clean apt lists to reduce image size.
nc_share_get and nc_share_list are read-only operations but incorrectly required the sharing:write scope. Introduce sharing:read for these tools so that clients with read-only access can list and inspect shares.
Change OTEL exporter SSL verification default from False to True. Add verify=self.verify_ssl to synchronous httpx calls in Ollama provider that were missing it (the async client was already configured correctly).
Validate URLs in cookbook recipe import and news feed creation to reject non-HTTP schemes and private/loopback/link-local IP addresses. This prevents MCP clients from using these endpoints to scan internal services via the Nextcloud server.
Add get_basic_auth_scopes() to read per-user scope configuration from BASIC_AUTH_SCOPES_<USERNAME> env vars. Returns None (= full access) when no config exists, preserving backward compatibility.
When BASIC_AUTH_SCOPES_<USERNAME> is configured, the BasicAuth middleware now creates a synthetic AccessToken and sets it in the MCP SDK's auth_context_var. This makes all existing @require_scopes checks and list_tools_filtered() work transparently for BasicAuth users. Users without scope config (env var not set) retain full access, preserving backward compatibility.
Extend the list_tools_filtered() activation condition to also include multi-user BasicAuth mode. Users with BASIC_AUTH_SCOPES_<USERNAME> config now only see tools matching their scopes.
Add require_resource_scopes decorator that reads the access token directly from auth_context_var (no Context parameter needed). Apply to all 14 resource handlers: 8 Deck, 3 Notes, 3 Cookbook. This closes the gap where resources were accessible without scope checks, even when tools required them.
Add BASIC_AUTH_SCOPES_<USERNAME> env var documentation to the authentication guide and README. Per-user scope restrictions are optional and backward compatible (omitting the variable grants full access).
The glob pattern !nextcloud_mcp_server/**/*.py did not match recursively on Podman/Buildah, causing missing modules (alembic). Replace with !nextcloud_mcp_server/ to include the entire package.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds per-user scope configuration for multi-user BasicAuth deployments. LLM clients can be restricted to specific operations (e.g. "files:read,files:write only") without requiring OAuth infrastructure.
Builds on #627 (security hardening) — this branch includes those commits.
How it works
Configure scopes per user via environment variables:
The implementation injects a synthetic
AccessTokeninto the MCP SDK'sauth_context_var, so all existing@require_scopeschecks andlist_tools_filtered()work transparently — no changes needed to the 90+ tool definitions.Changes
config.py—get_basic_auth_scopes(username)readsBASIC_AUTH_SCOPES_<USERNAME>env varsapp.py(BasicAuthMiddleware) — injects syntheticAccessTokenwhen scopes are configured for a userapp.py(list_tools_filtered) — activation extended to include multi-user BasicAuth modescope_authorization.py— newrequire_resource_scopesdecorator for@mcp.resource()handlersserver/{deck,notes,cookbook}.py—@require_resource_scopesapplied to all 14 resource handlersdocs/authentication.mdupdatedDesign decisions
BASIC_AUTH_SCOPES_*env vars retain full accessrequire_resource_scopesdecorator reads fromauth_context_vardirectly (resource handlers don't receive aContextparameter)Test plan
uv run ruff format --check .anduv run ruff check .uv run pytest -v -m unitBASIC_AUTH_SCOPES_TEST=notes:read→ only notes:read tools visible