Skip to content

[SECURITY FEATURE]: Per-Virtual-Server API Keys with Scoped AccessΒ #282

@crivetimihai

Description

@crivetimihai

🧭 Type of Feature

  • Enhancement to existing functionality
  • New feature or capability
  • Security Related (requires review)

🧭 Epic

Title: Per-Virtual-Server API Keys with Scoped Access
Goal: Create and manage API tokens scoped to specific virtual servers for granular access control
Why now: Global JWT tokens grant access to all virtual servers. For security isolation and least-privilege access, clients should only access the virtual servers they need. This enables multi-tenant scenarios where different API keys access different server subsets.

Depends on: #87 JWT Token Catalog with Per-User Expiry and Revocation


πŸ™‹β€β™‚οΈ User Story 1

As a: platform admin
I want: to create API keys tied to a specific virtual server
So that: credentials are limited in scope and clients can only access designated servers

βœ… Acceptance Criteria

Scenario: Generate server-scoped token from Admin UI
  Given I am viewing a virtual server in the Admin UI
  When I click "Generate API Key" in the server details
  And I enter a description and optional expiry
  Then I receive a JWT scoped only to that virtual server
  And the token appears in both global and server-specific token lists

πŸ™‹β€β™‚οΈ User Story 2

As a: platform admin
I want: to rotate or revoke a virtual server's API keys
So that: I can maintain security without affecting other servers

βœ… Acceptance Criteria

Scenario: Revoke server-specific token
  Given I see a list of API keys for a virtual server
  When I click "Delete" on a server-scoped token
  Then that token is revoked immediately
  And access to other virtual servers remains unaffected
  And the token is removed from all token listings

πŸ™‹β€β™‚οΈ User Story 3

As a: developer or automation client
I want: to use server-scoped API keys via REST API
So that: I can automate credential lifecycle for each virtual server

βœ… Acceptance Criteria

Scenario: Create and use server-scoped token via API
  Given I authenticate with admin credentials
  When I POST to /servers/{id}/tokens with description and expiry
  Then I get a JWT that only works for that virtual server
  And when I use the token to access /servers/{other_id}
  Then I receive a 403 Forbidden response

πŸ™‹β€β™‚οΈ User Story 4

As a: MCP client (Claude Desktop, mcpgateway.wrapper)
I want: to use server-scoped tokens for specific virtual servers
So that: my access is limited to only the servers I need

βœ… Acceptance Criteria

Scenario: Server-scoped token access control
  Given I have a token scoped to virtual server "weather-api"
  When I make requests to /servers/weather-api/sse
  Then I receive successful responses
  But when I make requests to /servers/other-api/sse
  Then I receive a 403 Forbidden with scope error

πŸ“ Design Sketch

  • Extend api_tokens table from [Feature Request]: Epic: Secure JWT Token Catalog with Per-User Expiry and RevocationΒ #87:

    -- Add scoping fields to existing table
    ALTER TABLE api_tokens ADD COLUMN scope_type VARCHAR(20) DEFAULT 'global';
    ALTER TABLE api_tokens ADD COLUMN scope_target VARCHAR(255) NULL;
    ALTER TABLE api_tokens ADD INDEX idx_scope (scope_type, scope_target);
  • JWT Claims Structure:

    {
      "sub": "admin",
      "jti": "uuid-here",
      "exp": 1234567890,
      "scope": {
        "type": "server", 
        "target": "server-123"
      }
    }
  • Access Control Logic:

    def verify_server_access(token_payload: dict, server_id: str) -> bool:
        scope = token_payload.get("scope", {})
        if scope.get("type") == "global":
            return True  # Global scope allows all servers
        elif scope.get("type") == "server":
            return scope.get("target") == server_id
        return False
  • UI Extensions:

    • Add "API Keys" tab to virtual server detail view
    • Show server-scoped tokens in both global and server-specific lists
    • Include scope indicator in token tables ("Global" vs "Server: weather-api")
  • API Extensions:

    • POST /servers/{id}/tokens β€” create server-scoped token
    • GET /servers/{id}/tokens β€” list tokens for specific server
    • DELETE /servers/{id}/tokens/{token_id} β€” revoke server token
    • Extend existing /auth/tokens endpoints with scope filtering

πŸ”— MCP Standards Check

  • Does not affect MCP spec
  • No protocol impact
  • If deviations exist, please describe them below:

This is purely an authentication/authorization enhancement that operates at the Gateway layer, transparent to MCP protocol interactions.


πŸ”„ Alternatives Considered

Option Pros Cons
Separate secrets per server Simple isolation Key management complexity, rotation overhead
Role-based permissions Flexible, industry standard More complex to implement than scoped tokens
API Gateway-style scoping Proven pattern Requires additional infrastructure
Selected: JWT scope claims Leverages existing JWT infrastructure, fine-grained control Builds on #87 dependency

πŸ““ Additional Context

  • Scope Types: Start with global and server scopes, designed to extend to tool, resource, user scopes later
  • Backward Compatibility: Existing global tokens continue working; new scope-aware validation is additive
  • Multi-tenant Use Cases:
    • Different customers access different virtual server sets
    • Development/staging/production environment isolation
    • Service-specific API access for different applications
  • Security Model: Principle of least privilege - tokens should grant minimum necessary access

🧭 Tasks

  • Database Schema (extends [Feature Request]: Epic: Secure JWT Token Catalog with Per-User Expiry and RevocationΒ #87)

    • Add scope_type and scope_target columns to api_tokens table
    • Create migration with default scope_type='global' for existing tokens
    • Add database indexes for efficient scope-based queries
  • Token Service Extensions

    • Extend auth_token_service.py with scope-aware methods:
      • create_server_token(server_id, user, description, expiry)
      • list_server_tokens(server_id)
      • verify_server_access(token, server_id)
    • Update JWT creation to include scope claims in payload
    • Modify token verification to check scope permissions
  • Access Control Middleware

    • Create @require_server_access(server_id) decorator for FastAPI routes
    • Update require_auth() to extract and validate scope claims
    • Add scope checking to virtual server endpoints (/servers/{id}/*)
    • Implement fallback for legacy global tokens (with deprecation logging)
  • API Endpoints

    • Add server-scoped token routes:
      • POST /servers/{id}/tokens β€” create server-specific token
      • GET /servers/{id}/tokens β€” list tokens for server
      • DELETE /servers/{id}/tokens/{token_id} β€” revoke server token
    • Extend existing /auth/tokens with scope filtering query params
    • Add scope information to all token response schemas
  • Admin UI Extensions

    • Add "API Keys" tab to virtual server detail page:
      • Server-specific token creation form
      • Table of tokens scoped to this server
      • Scope indicator badges ("Global", "Server: weather-api")
    • Update global token management page:
      • Add scope column to token table
      • Filter tokens by scope type
      • Visual indicators for different scope levels
  • Security & Access Control

    • Apply server access checks to all virtual server routes:
      • /servers/{id}/sse
      • /servers/{id}/message
      • /servers/{id}/tools/*
      • /servers/{id}/resources/*
      • /servers/{id}/prompts/*
    • Add comprehensive error messages for scope violations
    • Log scope-based access attempts for security auditing
  • Testing

    • Unit tests for scope-aware token creation and verification
    • Integration tests for server-scoped API access patterns
    • Security tests verifying cross-server access denial
    • Backward compatibility tests for existing global tokens
  • Documentation

    • Document server-scoped token API in OpenAPI/Swagger
    • Add security guide explaining scope-based access control
    • Provide examples of server-specific token usage with curl/clients
    • Update authentication documentation with scope concepts
  • Client Integration

    • Update mcpgateway.wrapper to handle server-scoped tokens
    • Document Claude Desktop configuration with server-specific tokens
    • Provide example configurations for multi-server setups

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestpythonPython / backend development (FastAPI)securityImproves securitytriageIssues / Features awaiting triage

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions