Skip to content

feat(mcp): per-user scope restrictions for BasicAuth mode#628

Open
tkaufmann wants to merge 16 commits into
cbcoutinho:masterfrom
tkaufmann:feat/basic-auth-scopes
Open

feat(mcp): per-user scope restrictions for BasicAuth mode#628
tkaufmann wants to merge 16 commits into
cbcoutinho:masterfrom
tkaufmann:feat/basic-auth-scopes

Conversation

@tkaufmann

Copy link
Copy Markdown

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:

ENABLE_MULTI_USER_BASIC_AUTH=true

# Per-user restrictions (optional — omit for full access)
BASIC_AUTH_SCOPES_CLAUDE=files:read,files:write,notes:read
BASIC_AUTH_SCOPES_N8N=calendar:read,calendar:write
# BASIC_AUTH_SCOPES_ADMIN not set → full access (backward compatible)

The implementation injects a synthetic AccessToken into the MCP SDK's auth_context_var, so all existing @require_scopes checks and list_tools_filtered() work transparently — no changes needed to the 90+ tool definitions.

Changes

  1. config.pyget_basic_auth_scopes(username) reads BASIC_AUTH_SCOPES_<USERNAME> env vars
  2. app.py (BasicAuthMiddleware) — injects synthetic AccessToken when scopes are configured for a user
  3. app.py (list_tools_filtered) — activation extended to include multi-user BasicAuth mode
  4. scope_authorization.py — new require_resource_scopes decorator for @mcp.resource() handlers
  5. server/{deck,notes,cookbook}.py@require_resource_scopes applied to all 14 resource handlers
  6. Documentation — README and docs/authentication.md updated

Design decisions

  • No changes to tool definitions: synthetic token + existing decorators = zero coupling
  • Backward compatible: users without BASIC_AUTH_SCOPES_* env vars retain full access
  • Resource handlers covered: new require_resource_scopes decorator reads from auth_context_var directly (resource handlers don't receive a Context parameter)

Test plan

  • uv run ruff format --check . and uv run ruff check .
  • uv run pytest -v -m unit
  • BasicAuth without scope config → all tools visible
  • BasicAuth with BASIC_AUTH_SCOPES_TEST=notes:read → only notes:read tools visible
  • Resource access denied when scope missing

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.
@CLAassistant

CLAassistant commented Jun 3, 2026

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

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.

2 participants