kiba-core 0.5.3.dev96__tar.gz → 0.5.3.dev97__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/CHANGELOG.md +4 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/PKG-INFO +1 -1
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/request_body.py +1 -1
- kiba_core-0.5.3.dev97/core/mcp/mcp_identity_provider.py +15 -0
- kiba_core-0.5.3.dev97/core/mcp/mcp_oauth_server.py +384 -0
- kiba_core-0.5.3.dev97/core/mcp/mcp_routes.py +213 -0
- kiba_core-0.5.3.dev97/core/mcp/mcp_server.py +235 -0
- kiba_core-0.5.3.dev97/core/mcp/model.py +63 -0
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/dict_mcp_oauth_store.py +25 -0
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/mcp_oauth_store.py +12 -0
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/sql_mcp_oauth_store.py +53 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/PKG-INFO +1 -1
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/SOURCES.txt +15 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/pyproject.toml +1 -1
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_json_route.py +7 -0
- kiba_core-0.5.3.dev97/tests/mcp/__init__.py +0 -0
- kiba_core-0.5.3.dev97/tests/mcp/conftest.py +156 -0
- kiba_core-0.5.3.dev97/tests/mcp/test_mcp_oauth.py +279 -0
- kiba_core-0.5.3.dev97/tests/mcp/test_mcp_oauth_store.py +46 -0
- kiba_core-0.5.3.dev97/tests/mcp/test_mcp_server.py +146 -0
- kiba_core-0.5.3.dev97/tests/requester/__init__.py +0 -0
- kiba_core-0.5.3.dev97/tests/web3/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.github/pull_request_template.md +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.github/workflows/deploy.yml +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.github/workflows/publish.yml +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.github/workflows/pull-request.yml +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.github/workflows/release.yml +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/.gitignore +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/Dockerfile +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/README.md +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/api_request.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/api_response.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/authorizer.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/default_routes.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/health.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/json_route.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/database_connection_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/logging_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/middleware/server_headers_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/openapi.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/rate_limit.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/request_context.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/route.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/route_auth.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/route_metadata.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/api/uploaded_file.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/aws_requester.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/caching/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/caching/cache.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/caching/dict_cache.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/caching/file_cache.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/cron/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/cron/api_request_cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/cron/cron_executor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/cron/cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/cron/model.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/exceptions.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/http/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/http/basic_authentication.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/http/jwt.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/http/rest_method.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/locks/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/locks/lock.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/locks/model.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/locks/sql.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/logging.py +0 -0
- {kiba_core-0.5.3.dev96/core/notifications → kiba_core-0.5.3.dev97/core/mcp}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96/core/queues → kiba_core-0.5.3.dev97/core/mcp/oauth_store}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96/core/store → kiba_core-0.5.3.dev97/core/notifications}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/notifications/discord_client.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/notifications/notification_client.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/notifications/slack_client.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/py.typed +0 -0
- {kiba_core-0.5.3.dev96/core/util → kiba_core-0.5.3.dev97/core/queues}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/aqs.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/cosmos.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/message_queue.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/model.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/sql.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/queues/sqs.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/requester/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/requester/requester.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/s3_manager.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/service_client.py +0 -0
- {kiba_core-0.5.3.dev96/core/web3 → kiba_core-0.5.3.dev97/core/store}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/store/database.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/store/entity_repository.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/store/retriever.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/store/saver.py +0 -0
- {kiba_core-0.5.3.dev96/tests/cron → kiba_core-0.5.3.dev97/core/util}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/async_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/chain_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/date_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/dict_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/file_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/hashing_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/http_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/json_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/list_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/process_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/string_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/typing_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/url_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/util/value_holder.py +0 -0
- {kiba_core-0.5.3.dev96/tests/requester → kiba_core-0.5.3.dev97/core/web3}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/web3/eth_client.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/web3/eth_client_registry.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/core/web3/multicall3.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/dependency_links.txt +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/requires.txt +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/top_level.txt +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/makefile +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/setup.cfg +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_api_response.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_authorizer.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_database_connection_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_openapi.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_rate_limit.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_request_context.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_route.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/api/test_streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/caching/test_dict_cache.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/caching/test_file_cache.py +0 -0
- {kiba_core-0.5.3.dev96/tests/web3 → kiba_core-0.5.3.dev97/tests/cron}/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/cron/test_cron_executor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/locks/test_sql_lock.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/conftest.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/test_aqs_queue.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/test_cosmos_queue.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/test_message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/test_sql_queue.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/queues/test_sqs_queue.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/requester/test_requester.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/test_database.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/test_entity_repository.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/test_exceptions.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/test_logging.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/__init__.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_async_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_chain_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_date_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_dict_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_file_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_json_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_list_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_process_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_string_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/util/test_url_util.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/web3/test_eth_client_registry.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/tests/web3/test_rest_eth_client.py +0 -0
- {kiba_core-0.5.3.dev96 → kiba_core-0.5.3.dev97}/uv.lock +0 -0
|
@@ -8,6 +8,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
|
+
- [MINOR] Added `core.mcp.mcp_server.McpServer` to serve MCP tools over streamable HTTP for both the `2026-07-28` (per-request `_meta`) and `2025-03-26`–`2025-11-25` (`initialize`) protocol eras; tools take a pydantic arguments model and an optional output model
|
|
12
|
+
- [MINOR] Added `core.mcp.mcp_oauth_server.McpOAuthServer`, an OAuth 2.1 authorization server for MCP clients that delegates login to a `core.mcp.mcp_identity_provider.McpIdentityProvider` and shows a per-client consent page first; single-use and revoked tokens are recorded in a `core.mcp.oauth_store` store (`DictMcpOAuthStore`, or `SqlMcpOAuthStore` whose `McpOAuthClaimsTable` apps add to their migrations)
|
|
13
|
+
- [MINOR] Added `core.mcp.mcp_routes.create_mcp_routes` to mount both on a starlette app
|
|
14
|
+
- [MINOR] Updated `json_route` and `streaming_json_route` (via `read_request_body`) to accept `application/x-www-form-urlencoded` bodies
|
|
11
15
|
- [MINOR] Added `excludedPaths` (exact) and `excludedPathPrefixes` to `DatabaseConnectionMiddleware`: matching requests run without a context connection, e.g. a long-lived SSE stream that shouldn't hold a pooled connection and open transaction, or routes that use a different database
|
|
12
16
|
- [PATCH] Updated `ExceptionHandlingMiddleware` to answer a client that disconnects before the response starts (starlette's `ClientDisconnect`, e.g. while reading the body) with a 499 instead of logging a traceback and a 500
|
|
13
17
|
- [MAJOR] Added `priority` to `SqlMessageQueue.send_message` and `send_messages` (default 0): visible messages are claimed highest priority first, then by `visibleDate`, and a duplicate send, or a retry folded into a pending duplicate, keeps the higher priority. `tbl_queue_messages` has a new `priority` column (`INTEGER NOT NULL DEFAULT 0`), so apps must add it with a migration before upgrading
|
|
@@ -11,7 +11,7 @@ from core.util.typing_util import JsonObject
|
|
|
11
11
|
|
|
12
12
|
|
|
13
13
|
async def read_request_body(request: Request) -> Mapping[str, object]:
|
|
14
|
-
if request.headers.get('Content-Type', '').startswith('multipart/form-data'):
|
|
14
|
+
if request.headers.get('Content-Type', '').startswith(('multipart/form-data', 'application/x-www-form-urlencoded')):
|
|
15
15
|
body: dict[str, object] = {}
|
|
16
16
|
# NOTE(krishan711): the form is closed on exit so uploaded files' temporary files are closed (their content has been read by then)
|
|
17
17
|
async with request.form() as form:
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from abc import ABC
|
|
2
|
+
from abc import abstractmethod
|
|
3
|
+
|
|
4
|
+
from core.mcp.model import McpUser
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class McpIdentityProvider(ABC):
|
|
8
|
+
@abstractmethod
|
|
9
|
+
def create_authorize_url(self, redirectUri: str, state: str) -> str: ...
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
async def authenticate_code(self, code: str, redirectUri: str) -> McpUser: ...
|
|
13
|
+
|
|
14
|
+
@abstractmethod
|
|
15
|
+
async def ensure_user_allowed(self, user: McpUser) -> None: ...
|
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import datetime
|
|
5
|
+
import hashlib
|
|
6
|
+
import hmac
|
|
7
|
+
import ipaddress
|
|
8
|
+
import re
|
|
9
|
+
import secrets
|
|
10
|
+
import typing
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import uuid
|
|
13
|
+
|
|
14
|
+
from core import logging
|
|
15
|
+
from core.exceptions import BadRequestException
|
|
16
|
+
from core.exceptions import KibaException
|
|
17
|
+
from core.exceptions import UnauthorizedException
|
|
18
|
+
from core.http.jwt import KibaJwt
|
|
19
|
+
from core.mcp.mcp_identity_provider import McpIdentityProvider
|
|
20
|
+
from core.mcp.model import McpAuthorizationRequest
|
|
21
|
+
from core.mcp.model import McpCachedClient
|
|
22
|
+
from core.mcp.model import McpClient
|
|
23
|
+
from core.mcp.model import McpProviderLogin
|
|
24
|
+
from core.mcp.model import McpTokenPair
|
|
25
|
+
from core.mcp.model import McpUser
|
|
26
|
+
from core.mcp.oauth_store.mcp_oauth_store import McpOAuthStore
|
|
27
|
+
from core.util import date_util
|
|
28
|
+
from core.util import json_util
|
|
29
|
+
from core.util.typing_util import JsonObject
|
|
30
|
+
|
|
31
|
+
if typing.TYPE_CHECKING:
|
|
32
|
+
from core.requester import Requester
|
|
33
|
+
|
|
34
|
+
JWT_KEY_ID = 'mcp-oauth-v1'
|
|
35
|
+
TOKEN_TYPE_KEY = 'tty'
|
|
36
|
+
AUDIENCE_KEY = 'aud'
|
|
37
|
+
CLIENT_ID_KEY = 'cid'
|
|
38
|
+
CLIENT_NAME_KEY = 'cnm'
|
|
39
|
+
CLIENT_REDIRECT_URIS_KEY = 'crs'
|
|
40
|
+
CLIENT_REDIRECT_URI_KEY = 'cru'
|
|
41
|
+
CLIENT_STATE_KEY = 'cst'
|
|
42
|
+
CODE_CHALLENGE_KEY = 'cch'
|
|
43
|
+
STATE_NONCE_KEY = 'non'
|
|
44
|
+
GRANT_ID_KEY = 'gid'
|
|
45
|
+
GRANT_EXPIRY_KEY = 'gex'
|
|
46
|
+
CONSENTS_KEY = 'cns'
|
|
47
|
+
CLIENT_REGISTRATION_LIFETIME = datetime.timedelta(days=365 * 100)
|
|
48
|
+
CONSENT_REQUEST_LIFETIME = datetime.timedelta(minutes=10)
|
|
49
|
+
MAX_CONSENT_COUNT = 20
|
|
50
|
+
CLIENT_METADATA_CACHE_LIFETIME = datetime.timedelta(hours=1)
|
|
51
|
+
MAX_CACHED_CLIENT_COUNT = 1000
|
|
52
|
+
PKCE_VERIFIER_PATTERN = re.compile(r'^[A-Za-z0-9\-._~]{43,128}$')
|
|
53
|
+
PKCE_S256_CHALLENGE_PATTERN = re.compile(r'^[A-Za-z0-9\-_]{43}$')
|
|
54
|
+
LOOPBACK_HOSTS = {'localhost', '127.0.0.1', '::1'}
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# NOTE(krishan711): an OAuth 2.1 authorization server for MCP clients that delegates login to an identity provider. Tokens are
|
|
58
|
+
# typed signed JWTs; the store only records what must be single-use (state, codes, refresh tokens) or revoked.
|
|
59
|
+
class McpOAuthServer:
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
identityProvider: McpIdentityProvider,
|
|
63
|
+
store: McpOAuthStore,
|
|
64
|
+
jwtSecret: str,
|
|
65
|
+
baseUrl: str,
|
|
66
|
+
allowedRedirectUris: list[str] | None = None,
|
|
67
|
+
requester: Requester | None = None,
|
|
68
|
+
mcpPath: str = '/mcp',
|
|
69
|
+
stateTokenLifetime: datetime.timedelta = datetime.timedelta(minutes=10),
|
|
70
|
+
codeTokenLifetime: datetime.timedelta = datetime.timedelta(minutes=2),
|
|
71
|
+
accessTokenLifetime: datetime.timedelta = datetime.timedelta(hours=1),
|
|
72
|
+
refreshTokenLifetime: datetime.timedelta = datetime.timedelta(days=14),
|
|
73
|
+
grantLifetime: datetime.timedelta = datetime.timedelta(days=30),
|
|
74
|
+
consentLifetime: datetime.timedelta = datetime.timedelta(days=30),
|
|
75
|
+
) -> None:
|
|
76
|
+
self.identityProvider = identityProvider
|
|
77
|
+
self.store = store
|
|
78
|
+
self._jwtSecret = jwtSecret.encode('utf-8')
|
|
79
|
+
self.baseUrl = baseUrl.rstrip('/')
|
|
80
|
+
self.allowedRedirectUris = set(allowedRedirectUris) if allowedRedirectUris is not None else None
|
|
81
|
+
# NOTE(krishan711): enables Client ID Metadata Documents; pass a Requester that doesn't follow redirects (SSRF)
|
|
82
|
+
self.requester = requester
|
|
83
|
+
self.mcpPath = mcpPath
|
|
84
|
+
self.resourceUrl = f'{self.baseUrl}{mcpPath}'
|
|
85
|
+
self.providerCallbackUrl = f'{self.baseUrl}{mcpPath}/oauth/callback'
|
|
86
|
+
self.stateTokenLifetime = stateTokenLifetime
|
|
87
|
+
self.codeTokenLifetime = codeTokenLifetime
|
|
88
|
+
self.accessTokenLifetime = accessTokenLifetime
|
|
89
|
+
self.refreshTokenLifetime = refreshTokenLifetime
|
|
90
|
+
self.grantLifetime = grantLifetime
|
|
91
|
+
self.consentLifetime = consentLifetime
|
|
92
|
+
self._cachedClients: dict[str, McpCachedClient] = {}
|
|
93
|
+
|
|
94
|
+
def get_protected_resource_metadata(self, resourceName: str) -> JsonObject:
|
|
95
|
+
return {'resource': self.resourceUrl, 'authorization_servers': [self.baseUrl], 'bearer_methods_supported': ['header'], 'resource_name': resourceName}
|
|
96
|
+
|
|
97
|
+
def get_authorization_server_metadata(self) -> JsonObject:
|
|
98
|
+
return {
|
|
99
|
+
'issuer': self.baseUrl,
|
|
100
|
+
'authorization_endpoint': f'{self.resourceUrl}/oauth/authorize',
|
|
101
|
+
'token_endpoint': f'{self.resourceUrl}/oauth/token',
|
|
102
|
+
'registration_endpoint': f'{self.resourceUrl}/oauth/register',
|
|
103
|
+
'revocation_endpoint': f'{self.resourceUrl}/oauth/revoke',
|
|
104
|
+
'response_types_supported': ['code'],
|
|
105
|
+
'grant_types_supported': ['authorization_code', 'refresh_token'],
|
|
106
|
+
'code_challenge_methods_supported': ['S256'],
|
|
107
|
+
'token_endpoint_auth_methods_supported': ['none'],
|
|
108
|
+
'revocation_endpoint_auth_methods_supported': ['none'],
|
|
109
|
+
'authorization_response_iss_parameter_supported': True,
|
|
110
|
+
'client_id_metadata_document_supported': self.requester is not None,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
def register_client(self, redirectUris: list[str], clientName: str | None) -> JsonObject:
|
|
114
|
+
if not redirectUris:
|
|
115
|
+
raise BadRequestException(message='INVALID_REDIRECT_URI')
|
|
116
|
+
for redirectUri in redirectUris:
|
|
117
|
+
self._ensure_allowed_redirect_uri(redirectUri=redirectUri)
|
|
118
|
+
name = clientName or 'MCP client'
|
|
119
|
+
clientId = self._create_token(tokenType='mcpClient', lifetime=CLIENT_REGISTRATION_LIFETIME, claims={CLIENT_NAME_KEY: name, CLIENT_REDIRECT_URIS_KEY: redirectUris})
|
|
120
|
+
return {
|
|
121
|
+
'client_id': clientId,
|
|
122
|
+
'client_id_issued_at': int(date_util.datetime_from_now().timestamp()),
|
|
123
|
+
'client_name': name,
|
|
124
|
+
'redirect_uris': redirectUris,
|
|
125
|
+
'token_endpoint_auth_method': 'none',
|
|
126
|
+
'grant_types': ['authorization_code', 'refresh_token'],
|
|
127
|
+
'response_types': ['code'],
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async def create_authorization_request(
|
|
131
|
+
self,
|
|
132
|
+
clientId: str,
|
|
133
|
+
redirectUri: str,
|
|
134
|
+
responseType: str | None,
|
|
135
|
+
clientState: str | None,
|
|
136
|
+
codeChallenge: str,
|
|
137
|
+
codeChallengeMethod: str | None,
|
|
138
|
+
resource: str | None,
|
|
139
|
+
) -> McpAuthorizationRequest:
|
|
140
|
+
client = await self._resolve_client(clientId=clientId)
|
|
141
|
+
if redirectUri not in client.redirectUris:
|
|
142
|
+
raise BadRequestException(message='INVALID_REDIRECT_URI')
|
|
143
|
+
self._ensure_allowed_redirect_uri(redirectUri=redirectUri)
|
|
144
|
+
if responseType != 'code':
|
|
145
|
+
raise BadRequestException(message='UNSUPPORTED_RESPONSE_TYPE')
|
|
146
|
+
if codeChallengeMethod != 'S256' or not PKCE_S256_CHALLENGE_PATTERN.match(codeChallenge):
|
|
147
|
+
raise BadRequestException(message='INVALID_CODE_CHALLENGE')
|
|
148
|
+
if not self._is_valid_resource(resource=resource):
|
|
149
|
+
raise BadRequestException(message='INVALID_TARGET')
|
|
150
|
+
return McpAuthorizationRequest(clientId=client.clientId, clientName=client.clientName, redirectUri=redirectUri, clientState=clientState, codeChallenge=codeChallenge)
|
|
151
|
+
|
|
152
|
+
def has_consent(self, consentToken: str | None, request: McpAuthorizationRequest) -> bool:
|
|
153
|
+
return self._consent_key(request=request) in self._get_consent_keys(consentToken=consentToken)
|
|
154
|
+
|
|
155
|
+
def create_consent_request_token(self, request: McpAuthorizationRequest) -> str:
|
|
156
|
+
return self._create_token(tokenType='mcpConsentRequest', lifetime=CONSENT_REQUEST_LIFETIME, claims=self._request_claims(request=request))
|
|
157
|
+
|
|
158
|
+
def get_consent_request(self, consentRequestToken: str) -> McpAuthorizationRequest:
|
|
159
|
+
try:
|
|
160
|
+
requestJwt = self._validate_token(tokenString=consentRequestToken, tokenType='mcpConsentRequest')
|
|
161
|
+
except UnauthorizedException as exception:
|
|
162
|
+
raise BadRequestException(message='INVALID_CONSENT_REQUEST') from exception
|
|
163
|
+
return self._request_from_jwt(jwt=requestJwt)
|
|
164
|
+
|
|
165
|
+
def add_consent(self, consentToken: str | None, request: McpAuthorizationRequest) -> str:
|
|
166
|
+
consentKey = self._consent_key(request=request)
|
|
167
|
+
consentKeys = [*[key for key in self._get_consent_keys(consentToken=consentToken) if key != consentKey], consentKey][-MAX_CONSENT_COUNT:]
|
|
168
|
+
return self._create_token(tokenType='mcpConsent', lifetime=self.consentLifetime, claims={CONSENTS_KEY: consentKeys})
|
|
169
|
+
|
|
170
|
+
def start_provider_login(self, request: McpAuthorizationRequest) -> McpProviderLogin:
|
|
171
|
+
stateNonce = secrets.token_urlsafe(32)
|
|
172
|
+
stateToken = self._create_token(tokenType='mcpState', lifetime=self.stateTokenLifetime, claims={**self._request_claims(request=request), STATE_NONCE_KEY: stateNonce})
|
|
173
|
+
return McpProviderLogin(authorizeUrl=self.identityProvider.create_authorize_url(redirectUri=self.providerCallbackUrl, state=stateToken), stateNonce=stateNonce)
|
|
174
|
+
|
|
175
|
+
def create_client_error_redirect(self, request: McpAuthorizationRequest, error: str) -> str:
|
|
176
|
+
return self._client_redirect_url(redirectUri=request.redirectUri, params={'error': error, 'state': request.clientState})
|
|
177
|
+
|
|
178
|
+
async def complete_provider_login(self, providerCode: str | None, stateToken: str, stateNonce: str | None) -> str:
|
|
179
|
+
try:
|
|
180
|
+
stateJwt = self._validate_token(tokenString=stateToken, tokenType='mcpState')
|
|
181
|
+
except UnauthorizedException as exception:
|
|
182
|
+
raise BadRequestException(message='INVALID_STATE') from exception
|
|
183
|
+
if not stateNonce or not hmac.compare_digest(stateNonce, typing.cast(str, stateJwt.payloadDict[STATE_NONCE_KEY])):
|
|
184
|
+
raise BadRequestException(message='STATE_NOT_FROM_THIS_BROWSER')
|
|
185
|
+
if not await self.store.claim(key=f'state:{stateJwt.tokenId}', lifetime=self.stateTokenLifetime):
|
|
186
|
+
raise BadRequestException(message='STATE_ALREADY_USED')
|
|
187
|
+
request = self._request_from_jwt(jwt=stateJwt)
|
|
188
|
+
if not providerCode:
|
|
189
|
+
return self.create_client_error_redirect(request=request, error='access_denied')
|
|
190
|
+
try:
|
|
191
|
+
user = await self.identityProvider.authenticate_code(code=providerCode, redirectUri=self.providerCallbackUrl)
|
|
192
|
+
except KibaException as exception:
|
|
193
|
+
logging.warning(f'MCP provider login failed: {exception.message}')
|
|
194
|
+
return self.create_client_error_redirect(request=request, error='access_denied')
|
|
195
|
+
code = self._create_token(tokenType='mcpCode', lifetime=self.codeTokenLifetime, claims={**self._user_claims(user=user), **self._request_claims(request=request)})
|
|
196
|
+
return self._client_redirect_url(redirectUri=request.redirectUri, params={'code': code, 'state': request.clientState})
|
|
197
|
+
|
|
198
|
+
async def exchange_authorization_code(self, code: str, codeVerifier: str, redirectUri: str, clientId: str, resource: str | None) -> McpTokenPair:
|
|
199
|
+
codeJwt = self._validate_token(tokenString=code, tokenType='mcpCode')
|
|
200
|
+
if clientId != codeJwt.payloadDict[CLIENT_ID_KEY] or redirectUri != codeJwt.payloadDict[CLIENT_REDIRECT_URI_KEY] or not PKCE_VERIFIER_PATTERN.match(codeVerifier):
|
|
201
|
+
raise UnauthorizedException(message='INVALID_GRANT')
|
|
202
|
+
codeChallenge = base64.urlsafe_b64encode(hashlib.sha256(codeVerifier.encode('ascii')).digest()).decode('ascii').rstrip('=')
|
|
203
|
+
if not hmac.compare_digest(codeChallenge, typing.cast(str, codeJwt.payloadDict[CODE_CHALLENGE_KEY])):
|
|
204
|
+
raise UnauthorizedException(message='INVALID_GRANT')
|
|
205
|
+
if not self._is_valid_resource(resource=resource):
|
|
206
|
+
raise UnauthorizedException(message='INVALID_TARGET')
|
|
207
|
+
if not await self.store.claim(key=f'code:{codeJwt.tokenId}', lifetime=self.codeTokenLifetime):
|
|
208
|
+
raise UnauthorizedException(message='CODE_ALREADY_USED')
|
|
209
|
+
grantExpiryDate = date_util.datetime_from_now(seconds=self.grantLifetime.total_seconds())
|
|
210
|
+
return self._create_token_pair(user=self._user_from_jwt(jwt=codeJwt), clientId=clientId, grantId=str(uuid.uuid4()), grantExpiryTimestamp=int(grantExpiryDate.timestamp()))
|
|
211
|
+
|
|
212
|
+
async def refresh_tokens(self, refreshToken: str, clientId: str | None, resource: str | None) -> McpTokenPair:
|
|
213
|
+
refreshJwt = self._validate_token(tokenString=refreshToken, tokenType='mcpRefresh')
|
|
214
|
+
tokenClientId = typing.cast(str, refreshJwt.payloadDict[CLIENT_ID_KEY])
|
|
215
|
+
grantId = typing.cast(str, refreshJwt.payloadDict[GRANT_ID_KEY])
|
|
216
|
+
if clientId is not None and clientId != tokenClientId:
|
|
217
|
+
raise UnauthorizedException(message='INVALID_GRANT')
|
|
218
|
+
if not self._is_valid_resource(resource=resource):
|
|
219
|
+
raise UnauthorizedException(message='INVALID_TARGET')
|
|
220
|
+
if await self.store.is_claimed(key=f'revoked:{grantId}'):
|
|
221
|
+
raise UnauthorizedException(message='TOKEN_REVOKED')
|
|
222
|
+
user = self._user_from_jwt(jwt=refreshJwt)
|
|
223
|
+
await self.identityProvider.ensure_user_allowed(user=user)
|
|
224
|
+
if not await self.store.claim(key=f'refresh:{refreshJwt.tokenId}', lifetime=self.refreshTokenLifetime):
|
|
225
|
+
# NOTE(krishan711): a refresh token used twice has leaked, so the whole grant is revoked
|
|
226
|
+
await self.store.claim(key=f'revoked:{grantId}', lifetime=self.grantLifetime)
|
|
227
|
+
raise UnauthorizedException(message='REFRESH_TOKEN_REUSED')
|
|
228
|
+
return self._create_token_pair(user=user, clientId=tokenClientId, grantId=grantId, grantExpiryTimestamp=typing.cast(int, refreshJwt.payloadDict[GRANT_EXPIRY_KEY]))
|
|
229
|
+
|
|
230
|
+
async def revoke_token(self, token: str) -> None:
|
|
231
|
+
for tokenType in ('mcpRefresh', 'mcpAccess'):
|
|
232
|
+
try:
|
|
233
|
+
tokenJwt = self._validate_token(tokenString=token, tokenType=tokenType)
|
|
234
|
+
except UnauthorizedException:
|
|
235
|
+
continue
|
|
236
|
+
await self.store.claim(key=f'revoked:{tokenJwt.payloadDict[GRANT_ID_KEY]}', lifetime=self.grantLifetime)
|
|
237
|
+
return
|
|
238
|
+
|
|
239
|
+
async def validate_access_token(self, accessToken: str) -> McpUser:
|
|
240
|
+
accessJwt = self._validate_token(tokenString=accessToken, tokenType='mcpAccess')
|
|
241
|
+
if accessJwt.payloadDict.get(AUDIENCE_KEY) != self.resourceUrl:
|
|
242
|
+
raise UnauthorizedException(message='INVALID_AUDIENCE')
|
|
243
|
+
if await self.store.is_claimed(key=f'revoked:{accessJwt.payloadDict[GRANT_ID_KEY]}'):
|
|
244
|
+
raise UnauthorizedException(message='TOKEN_REVOKED')
|
|
245
|
+
return self._user_from_jwt(jwt=accessJwt)
|
|
246
|
+
|
|
247
|
+
def _ensure_allowed_redirect_uri(self, redirectUri: str) -> None:
|
|
248
|
+
if self.allowedRedirectUris is not None:
|
|
249
|
+
if redirectUri not in self.allowedRedirectUris:
|
|
250
|
+
raise BadRequestException(message='INVALID_REDIRECT_URI')
|
|
251
|
+
return
|
|
252
|
+
parsedUri = urllib.parse.urlparse(redirectUri)
|
|
253
|
+
isLoopback = parsedUri.scheme == 'http' and parsedUri.hostname in LOOPBACK_HOSTS
|
|
254
|
+
if (parsedUri.scheme != 'https' and not isLoopback) or not parsedUri.netloc or parsedUri.fragment:
|
|
255
|
+
raise BadRequestException(message='INVALID_REDIRECT_URI')
|
|
256
|
+
|
|
257
|
+
def _is_valid_resource(self, resource: str | None) -> bool:
|
|
258
|
+
return resource is None or resource.rstrip('/') == self.resourceUrl
|
|
259
|
+
|
|
260
|
+
async def _resolve_client(self, clientId: str) -> McpClient:
|
|
261
|
+
if clientId.startswith('https://'):
|
|
262
|
+
return await self._fetch_client_metadata(clientId=clientId)
|
|
263
|
+
try:
|
|
264
|
+
clientJwt = self._validate_token(tokenString=clientId, tokenType='mcpClient')
|
|
265
|
+
except UnauthorizedException as exception:
|
|
266
|
+
raise BadRequestException(message='INVALID_CLIENT') from exception
|
|
267
|
+
return McpClient(clientId=clientId, clientName=typing.cast(str, clientJwt.payloadDict[CLIENT_NAME_KEY]), redirectUris=typing.cast(list[str], clientJwt.payloadDict[CLIENT_REDIRECT_URIS_KEY]))
|
|
268
|
+
|
|
269
|
+
async def _fetch_client_metadata(self, clientId: str) -> McpClient:
|
|
270
|
+
now = date_util.datetime_from_now()
|
|
271
|
+
cachedClient = self._cachedClients.get(clientId)
|
|
272
|
+
if cachedClient and cachedClient.expiryDate > now:
|
|
273
|
+
return cachedClient.client
|
|
274
|
+
parsedClientId = urllib.parse.urlparse(clientId)
|
|
275
|
+
hostname = parsedClientId.hostname
|
|
276
|
+
# NOTE(krishan711): the client id is chosen by the caller; this blocks ip literals and loopback, not names resolving to private ips
|
|
277
|
+
if self.requester is None or hostname is None or parsedClientId.path in ('', '/') or hostname in LOOPBACK_HOSTS or _is_ip_address(hostname=hostname):
|
|
278
|
+
raise BadRequestException(message='INVALID_CLIENT')
|
|
279
|
+
try:
|
|
280
|
+
document = json_util.loads((await self.requester.get(url=clientId, timeout=5)).content)
|
|
281
|
+
except Exception as exception:
|
|
282
|
+
raise BadRequestException(message='INVALID_CLIENT_METADATA') from exception
|
|
283
|
+
if not isinstance(document, dict) or document.get('client_id') != clientId:
|
|
284
|
+
raise BadRequestException(message='INVALID_CLIENT_METADATA')
|
|
285
|
+
clientName = document.get('client_name')
|
|
286
|
+
redirectUris = document.get('redirect_uris')
|
|
287
|
+
if not isinstance(redirectUris, list) or not all(isinstance(redirectUri, str) for redirectUri in redirectUris):
|
|
288
|
+
raise BadRequestException(message='INVALID_CLIENT_METADATA')
|
|
289
|
+
client = McpClient(clientId=clientId, clientName=clientName if isinstance(clientName, str) else hostname, redirectUris=[str(redirectUri) for redirectUri in redirectUris])
|
|
290
|
+
self._cachedClients = {key: value for key, value in self._cachedClients.items() if value.expiryDate > now}
|
|
291
|
+
if len(self._cachedClients) < MAX_CACHED_CLIENT_COUNT:
|
|
292
|
+
self._cachedClients[clientId] = McpCachedClient(client=client, expiryDate=now + CLIENT_METADATA_CACHE_LIFETIME)
|
|
293
|
+
return client
|
|
294
|
+
|
|
295
|
+
def _get_consent_keys(self, consentToken: str | None) -> list[str]:
|
|
296
|
+
if not consentToken:
|
|
297
|
+
return []
|
|
298
|
+
try:
|
|
299
|
+
consentJwt = self._validate_token(tokenString=consentToken, tokenType='mcpConsent')
|
|
300
|
+
except UnauthorizedException:
|
|
301
|
+
return []
|
|
302
|
+
return typing.cast(list[str], consentJwt.payloadDict.get(CONSENTS_KEY, []))
|
|
303
|
+
|
|
304
|
+
@staticmethod
|
|
305
|
+
def _consent_key(request: McpAuthorizationRequest) -> str:
|
|
306
|
+
return hashlib.sha256(f'{request.clientId}\n{request.redirectUri}'.encode()).hexdigest()[:32]
|
|
307
|
+
|
|
308
|
+
@staticmethod
|
|
309
|
+
def _request_claims(request: McpAuthorizationRequest) -> JsonObject:
|
|
310
|
+
return {CLIENT_ID_KEY: request.clientId, CLIENT_NAME_KEY: request.clientName, CLIENT_REDIRECT_URI_KEY: request.redirectUri, CLIENT_STATE_KEY: request.clientState, CODE_CHALLENGE_KEY: request.codeChallenge}
|
|
311
|
+
|
|
312
|
+
@staticmethod
|
|
313
|
+
def _request_from_jwt(jwt: KibaJwt) -> McpAuthorizationRequest:
|
|
314
|
+
return McpAuthorizationRequest(
|
|
315
|
+
clientId=typing.cast(str, jwt.payloadDict[CLIENT_ID_KEY]),
|
|
316
|
+
clientName=typing.cast(str, jwt.payloadDict[CLIENT_NAME_KEY]),
|
|
317
|
+
redirectUri=typing.cast(str, jwt.payloadDict[CLIENT_REDIRECT_URI_KEY]),
|
|
318
|
+
clientState=typing.cast(str | None, jwt.payloadDict.get(CLIENT_STATE_KEY)),
|
|
319
|
+
codeChallenge=typing.cast(str, jwt.payloadDict[CODE_CHALLENGE_KEY]),
|
|
320
|
+
)
|
|
321
|
+
|
|
322
|
+
def _client_redirect_url(self, redirectUri: str, params: dict[str, str | None]) -> str:
|
|
323
|
+
queryString = urllib.parse.urlencode({key: value for key, value in {**params, 'iss': self.baseUrl}.items() if value is not None})
|
|
324
|
+
separator = '&' if '?' in redirectUri else '?'
|
|
325
|
+
return f'{redirectUri}{separator}{queryString}'
|
|
326
|
+
|
|
327
|
+
def _create_token_pair(self, user: McpUser, clientId: str, grantId: str, grantExpiryTimestamp: int) -> McpTokenPair:
|
|
328
|
+
grantClaims: JsonObject = {**self._user_claims(user=user), CLIENT_ID_KEY: clientId, GRANT_ID_KEY: grantId, GRANT_EXPIRY_KEY: grantExpiryTimestamp}
|
|
329
|
+
refreshLifetime = min(self.refreshTokenLifetime, datetime.datetime.fromtimestamp(grantExpiryTimestamp, tz=datetime.UTC) - date_util.datetime_from_now())
|
|
330
|
+
if refreshLifetime <= datetime.timedelta(0):
|
|
331
|
+
raise UnauthorizedException(message='GRANT_EXPIRED')
|
|
332
|
+
accessToken = self._create_token(tokenType='mcpAccess', lifetime=min(self.accessTokenLifetime, refreshLifetime), claims={**grantClaims, AUDIENCE_KEY: self.resourceUrl})
|
|
333
|
+
refreshToken = self._create_token(tokenType='mcpRefresh', lifetime=refreshLifetime, claims=grantClaims)
|
|
334
|
+
return McpTokenPair(accessToken=accessToken, refreshToken=refreshToken, expiresInSeconds=int(min(self.accessTokenLifetime, refreshLifetime).total_seconds()))
|
|
335
|
+
|
|
336
|
+
@staticmethod
|
|
337
|
+
def _user_claims(user: McpUser) -> JsonObject:
|
|
338
|
+
return {KibaJwt.Key.USER_ID: user.userId, KibaJwt.Key.USER_NAME: user.userName}
|
|
339
|
+
|
|
340
|
+
@staticmethod
|
|
341
|
+
def _user_from_jwt(jwt: KibaJwt) -> McpUser:
|
|
342
|
+
return McpUser(userId=typing.cast(str, jwt.payloadDict[KibaJwt.Key.USER_ID]), userName=typing.cast(str, jwt.payloadDict[KibaJwt.Key.USER_NAME]))
|
|
343
|
+
|
|
344
|
+
def _create_token(self, tokenType: str, lifetime: datetime.timedelta, claims: JsonObject) -> str:
|
|
345
|
+
issueDate = date_util.datetime_from_now()
|
|
346
|
+
jwt = KibaJwt(
|
|
347
|
+
headerDict={KibaJwt.Key.ALGORITHM: 'HS256', KibaJwt.Key.TYPE: 'JWT', KibaJwt.Key.KEY_ID: JWT_KEY_ID},
|
|
348
|
+
payloadDict={
|
|
349
|
+
**claims,
|
|
350
|
+
KibaJwt.Key.TOKEN_ID: str(uuid.uuid4()),
|
|
351
|
+
TOKEN_TYPE_KEY: tokenType,
|
|
352
|
+
KibaJwt.Key.ISSUE_DATE: int(issueDate.timestamp()),
|
|
353
|
+
KibaJwt.Key.EXPIRY_DATE: int((issueDate + lifetime).timestamp()),
|
|
354
|
+
},
|
|
355
|
+
)
|
|
356
|
+
jwt.signatureBytes = self._sign(jwt=jwt)
|
|
357
|
+
return jwt.to_string()
|
|
358
|
+
|
|
359
|
+
def _validate_token(self, tokenString: str, tokenType: str) -> KibaJwt:
|
|
360
|
+
try:
|
|
361
|
+
jwt = KibaJwt.from_string(jwtString=tokenString)
|
|
362
|
+
except Exception as exception:
|
|
363
|
+
raise UnauthorizedException(message='INVALID_TOKEN') from exception
|
|
364
|
+
if not isinstance(jwt.headerDict, dict) or not isinstance(jwt.payloadDict, dict):
|
|
365
|
+
raise UnauthorizedException(message='INVALID_TOKEN')
|
|
366
|
+
if jwt.algorithm != 'HS256' or jwt.keyId != JWT_KEY_ID or not hmac.compare_digest(jwt.signatureBytes, self._sign(jwt=jwt)):
|
|
367
|
+
raise UnauthorizedException(message='INVALID_TOKEN')
|
|
368
|
+
if jwt.payloadDict.get(TOKEN_TYPE_KEY) != tokenType:
|
|
369
|
+
raise UnauthorizedException(message='INVALID_TOKEN_TYPE')
|
|
370
|
+
expiryDate = jwt.expiryDate
|
|
371
|
+
if not expiryDate or expiryDate <= date_util.datetime_from_now():
|
|
372
|
+
raise UnauthorizedException(message='TOKEN_EXPIRED')
|
|
373
|
+
return jwt
|
|
374
|
+
|
|
375
|
+
def _sign(self, jwt: KibaJwt) -> bytes:
|
|
376
|
+
return hmac.new(self._jwtSecret, jwt.verificationString.encode('utf-8'), hashlib.sha256).digest()
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _is_ip_address(hostname: str) -> bool:
|
|
380
|
+
try:
|
|
381
|
+
ipaddress.ip_address(hostname)
|
|
382
|
+
except ValueError:
|
|
383
|
+
return False
|
|
384
|
+
return True
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import hmac
|
|
2
|
+
import html
|
|
3
|
+
import secrets
|
|
4
|
+
import urllib.parse
|
|
5
|
+
|
|
6
|
+
from starlette.requests import Request
|
|
7
|
+
from starlette.responses import HTMLResponse
|
|
8
|
+
from starlette.responses import JSONResponse
|
|
9
|
+
from starlette.responses import PlainTextResponse
|
|
10
|
+
from starlette.responses import RedirectResponse
|
|
11
|
+
from starlette.responses import Response
|
|
12
|
+
from starlette.routing import Route
|
|
13
|
+
|
|
14
|
+
from core.api.request_body import read_request_body
|
|
15
|
+
from core.exceptions import BadRequestException
|
|
16
|
+
from core.exceptions import ForbiddenException
|
|
17
|
+
from core.exceptions import UnauthorizedException
|
|
18
|
+
from core.mcp.mcp_oauth_server import McpOAuthServer
|
|
19
|
+
from core.mcp.mcp_server import McpServer
|
|
20
|
+
from core.mcp.model import McpAuthorizationRequest
|
|
21
|
+
|
|
22
|
+
DEFAULT_MAX_BODY_BYTES = 4 * 1024 * 1024
|
|
23
|
+
CONSENT_COOKIE_NAME = '__Host-mcp-consent'
|
|
24
|
+
CSRF_COOKIE_NAME = '__Host-mcp-csrf'
|
|
25
|
+
STATE_COOKIE_NAME = '__Host-mcp-state'
|
|
26
|
+
CONSENT_PAGE_HEADERS = {
|
|
27
|
+
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'",
|
|
28
|
+
'X-Frame-Options': 'DENY',
|
|
29
|
+
'Cache-Control': 'no-store',
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def create_mcp_routes(mcpServer: McpServer, oauthServer: McpOAuthServer, resourceName: str, allowedOrigins: list[str] | None = None, maxBodyBytes: int = DEFAULT_MAX_BODY_BYTES) -> list[Route]:
|
|
34
|
+
mcpPath = oauthServer.mcpPath
|
|
35
|
+
protectedResourceMetadataUrl = f'{oauthServer.baseUrl}/.well-known/oauth-protected-resource'
|
|
36
|
+
parsedBaseUrl = urllib.parse.urlparse(oauthServer.baseUrl)
|
|
37
|
+
validOrigins = set(allowedOrigins) if allowedOrigins is not None else {f'{parsedBaseUrl.scheme}://{parsedBaseUrl.netloc}'}
|
|
38
|
+
|
|
39
|
+
async def get_protected_resource_metadata(request: Request) -> Response: # noqa: ARG001
|
|
40
|
+
return JSONResponse(oauthServer.get_protected_resource_metadata(resourceName=resourceName))
|
|
41
|
+
|
|
42
|
+
async def get_authorization_server_metadata(request: Request) -> Response: # noqa: ARG001
|
|
43
|
+
return JSONResponse(oauthServer.get_authorization_server_metadata())
|
|
44
|
+
|
|
45
|
+
async def register_client(request: Request) -> Response:
|
|
46
|
+
body = await read_request_body(request=request)
|
|
47
|
+
redirectUris = body.get('redirect_uris')
|
|
48
|
+
clientName = body.get('client_name')
|
|
49
|
+
if not isinstance(redirectUris, list) or not all(isinstance(redirectUri, str) for redirectUri in redirectUris):
|
|
50
|
+
return _oauth_error(error='invalid_redirect_uri', description='redirect_uris must be a list of strings')
|
|
51
|
+
try:
|
|
52
|
+
registration = oauthServer.register_client(redirectUris=[str(redirectUri) for redirectUri in redirectUris], clientName=clientName if isinstance(clientName, str) else None)
|
|
53
|
+
except BadRequestException:
|
|
54
|
+
return _oauth_error(error='invalid_redirect_uri', description='redirect_uri is not allowed')
|
|
55
|
+
return JSONResponse(registration, status_code=201, headers={'Cache-Control': 'no-store'})
|
|
56
|
+
|
|
57
|
+
async def authorize(request: Request) -> Response:
|
|
58
|
+
queryParams = request.query_params
|
|
59
|
+
try:
|
|
60
|
+
authorizationRequest = await oauthServer.create_authorization_request(
|
|
61
|
+
clientId=queryParams.get('client_id', ''),
|
|
62
|
+
redirectUri=queryParams.get('redirect_uri', ''),
|
|
63
|
+
responseType=queryParams.get('response_type'),
|
|
64
|
+
clientState=queryParams.get('state'),
|
|
65
|
+
codeChallenge=queryParams.get('code_challenge', ''),
|
|
66
|
+
codeChallengeMethod=queryParams.get('code_challenge_method'),
|
|
67
|
+
resource=queryParams.get('resource'),
|
|
68
|
+
)
|
|
69
|
+
except BadRequestException as exception:
|
|
70
|
+
return PlainTextResponse(f'Invalid authorization request: {exception.message}', status_code=400)
|
|
71
|
+
if oauthServer.has_consent(consentToken=request.cookies.get(CONSENT_COOKIE_NAME), request=authorizationRequest):
|
|
72
|
+
return start_provider_login(authorizationRequest=authorizationRequest, statusCode=302)
|
|
73
|
+
csrfToken = secrets.token_urlsafe(32)
|
|
74
|
+
response = HTMLResponse(
|
|
75
|
+
_render_consent_page(consentRequestToken=oauthServer.create_consent_request_token(request=authorizationRequest), csrfToken=csrfToken, request=authorizationRequest, resourceName=resourceName, consentPath=f'{mcpPath}/oauth/consent'),
|
|
76
|
+
headers=CONSENT_PAGE_HEADERS,
|
|
77
|
+
)
|
|
78
|
+
_set_cookie(response=response, name=CSRF_COOKIE_NAME, value=csrfToken, maxAgeSeconds=int(oauthServer.stateTokenLifetime.total_seconds()))
|
|
79
|
+
return response
|
|
80
|
+
|
|
81
|
+
async def consent(request: Request) -> Response:
|
|
82
|
+
body = await read_request_body(request=request)
|
|
83
|
+
csrfCookie = request.cookies.get(CSRF_COOKIE_NAME)
|
|
84
|
+
csrfToken = body.get('csrf_token')
|
|
85
|
+
if not csrfCookie or not isinstance(csrfToken, str) or not hmac.compare_digest(csrfCookie, csrfToken):
|
|
86
|
+
return PlainTextResponse('Consent request expired or did not come from this browser. Start the connection again from your MCP client.', status_code=403)
|
|
87
|
+
try:
|
|
88
|
+
authorizationRequest = oauthServer.get_consent_request(consentRequestToken=str(body.get('consent_request', '')))
|
|
89
|
+
except BadRequestException:
|
|
90
|
+
return PlainTextResponse('Consent request expired. Start the connection again from your MCP client.', status_code=400)
|
|
91
|
+
if body.get('decision') != 'approve':
|
|
92
|
+
response: Response = RedirectResponse(url=oauthServer.create_client_error_redirect(request=authorizationRequest, error='access_denied'), status_code=303)
|
|
93
|
+
else:
|
|
94
|
+
response = start_provider_login(authorizationRequest=authorizationRequest, statusCode=303)
|
|
95
|
+
_set_cookie(response=response, name=CONSENT_COOKIE_NAME, value=oauthServer.add_consent(consentToken=request.cookies.get(CONSENT_COOKIE_NAME), request=authorizationRequest), maxAgeSeconds=int(oauthServer.consentLifetime.total_seconds()))
|
|
96
|
+
response.delete_cookie(key=CSRF_COOKIE_NAME, path='/', secure=True, httponly=True, samesite='lax')
|
|
97
|
+
return response
|
|
98
|
+
|
|
99
|
+
def start_provider_login(authorizationRequest: McpAuthorizationRequest, statusCode: int) -> Response:
|
|
100
|
+
providerLogin = oauthServer.start_provider_login(request=authorizationRequest)
|
|
101
|
+
response = RedirectResponse(url=providerLogin.authorizeUrl, status_code=statusCode)
|
|
102
|
+
_set_cookie(response=response, name=STATE_COOKIE_NAME, value=providerLogin.stateNonce, maxAgeSeconds=int(oauthServer.stateTokenLifetime.total_seconds()))
|
|
103
|
+
return response
|
|
104
|
+
|
|
105
|
+
async def provider_callback(request: Request) -> Response:
|
|
106
|
+
queryParams = request.query_params
|
|
107
|
+
try:
|
|
108
|
+
clientRedirectUrl = await oauthServer.complete_provider_login(providerCode=queryParams.get('code'), stateToken=queryParams.get('state', ''), stateNonce=request.cookies.get(STATE_COOKIE_NAME))
|
|
109
|
+
except BadRequestException as exception:
|
|
110
|
+
return PlainTextResponse(f'Login failed: {exception.message}. Start the connection again from your MCP client.', status_code=400)
|
|
111
|
+
response = RedirectResponse(url=clientRedirectUrl, status_code=302)
|
|
112
|
+
response.delete_cookie(key=STATE_COOKIE_NAME, path='/', secure=True, httponly=True, samesite='lax')
|
|
113
|
+
return response
|
|
114
|
+
|
|
115
|
+
async def token(request: Request) -> Response:
|
|
116
|
+
body = await read_request_body(request=request)
|
|
117
|
+
grantType = body.get('grant_type')
|
|
118
|
+
resource = body.get('resource')
|
|
119
|
+
clientId = body.get('client_id')
|
|
120
|
+
try:
|
|
121
|
+
if grantType == 'authorization_code':
|
|
122
|
+
tokenPair = await oauthServer.exchange_authorization_code(
|
|
123
|
+
code=str(body.get('code', '')),
|
|
124
|
+
codeVerifier=str(body.get('code_verifier', '')),
|
|
125
|
+
redirectUri=str(body.get('redirect_uri', '')),
|
|
126
|
+
clientId=str(clientId or ''),
|
|
127
|
+
resource=resource if isinstance(resource, str) else None,
|
|
128
|
+
)
|
|
129
|
+
elif grantType == 'refresh_token':
|
|
130
|
+
tokenPair = await oauthServer.refresh_tokens(refreshToken=str(body.get('refresh_token', '')), clientId=clientId if isinstance(clientId, str) else None, resource=resource if isinstance(resource, str) else None)
|
|
131
|
+
else:
|
|
132
|
+
return _oauth_error(error='unsupported_grant_type', description='grant_type must be authorization_code or refresh_token')
|
|
133
|
+
except (UnauthorizedException, ForbiddenException) as exception:
|
|
134
|
+
return _oauth_error(error='invalid_target' if exception.message == 'INVALID_TARGET' else 'invalid_grant', description=exception.message or 'invalid grant')
|
|
135
|
+
return JSONResponse(
|
|
136
|
+
{'access_token': tokenPair.accessToken, 'token_type': 'Bearer', 'expires_in': tokenPair.expiresInSeconds, 'refresh_token': tokenPair.refreshToken},
|
|
137
|
+
headers={'Cache-Control': 'no-store'},
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
async def revoke(request: Request) -> Response:
|
|
141
|
+
body = await read_request_body(request=request)
|
|
142
|
+
tokenValue = body.get('token')
|
|
143
|
+
if not isinstance(tokenValue, str):
|
|
144
|
+
return _oauth_error(error='invalid_request', description='token is required')
|
|
145
|
+
await oauthServer.revoke_token(token=tokenValue)
|
|
146
|
+
return Response(status_code=200, headers={'Cache-Control': 'no-store'})
|
|
147
|
+
|
|
148
|
+
async def handle_mcp(request: Request) -> Response:
|
|
149
|
+
origin = request.headers.get('Origin')
|
|
150
|
+
if origin is not None and origin not in validOrigins:
|
|
151
|
+
return JSONResponse({'jsonrpc': '2.0', 'error': {'code': -32600, 'message': 'Origin not allowed'}}, status_code=403)
|
|
152
|
+
scheme, _, accessToken = request.headers.get('Authorization', '').partition(' ')
|
|
153
|
+
if scheme.lower() != 'bearer' or not accessToken:
|
|
154
|
+
return Response(status_code=401, headers={'WWW-Authenticate': f'Bearer resource_metadata="{protectedResourceMetadataUrl}"'})
|
|
155
|
+
try:
|
|
156
|
+
user = await oauthServer.validate_access_token(accessToken=accessToken)
|
|
157
|
+
except UnauthorizedException as exception:
|
|
158
|
+
return Response(status_code=401, headers={'WWW-Authenticate': f'Bearer error="invalid_token", error_description="{exception.message}", resource_metadata="{protectedResourceMetadataUrl}"'})
|
|
159
|
+
body = bytearray()
|
|
160
|
+
async for chunk in request.stream():
|
|
161
|
+
body.extend(chunk)
|
|
162
|
+
if len(body) > maxBodyBytes:
|
|
163
|
+
return Response(status_code=413)
|
|
164
|
+
mcpResponse = await mcpServer.handle_http_message(body=bytes(body), headers=request.headers, user=user)
|
|
165
|
+
if mcpResponse.body is None:
|
|
166
|
+
return Response(status_code=mcpResponse.statusCode)
|
|
167
|
+
return JSONResponse(mcpResponse.body, status_code=mcpResponse.statusCode)
|
|
168
|
+
|
|
169
|
+
async def reject_mcp_stream(request: Request) -> Response: # noqa: ARG001
|
|
170
|
+
return Response(status_code=405, headers={'Allow': 'POST'})
|
|
171
|
+
|
|
172
|
+
return [
|
|
173
|
+
Route('/.well-known/oauth-protected-resource', get_protected_resource_metadata, methods=['GET']),
|
|
174
|
+
Route(f'/.well-known/oauth-protected-resource{mcpPath}', get_protected_resource_metadata, methods=['GET']),
|
|
175
|
+
Route('/.well-known/oauth-authorization-server', get_authorization_server_metadata, methods=['GET']),
|
|
176
|
+
Route(f'{mcpPath}/oauth/register', register_client, methods=['POST']),
|
|
177
|
+
Route(f'{mcpPath}/oauth/authorize', authorize, methods=['GET']),
|
|
178
|
+
Route(f'{mcpPath}/oauth/consent', consent, methods=['POST']),
|
|
179
|
+
Route(f'{mcpPath}/oauth/callback', provider_callback, methods=['GET']),
|
|
180
|
+
Route(f'{mcpPath}/oauth/token', token, methods=['POST']),
|
|
181
|
+
Route(f'{mcpPath}/oauth/revoke', revoke, methods=['POST']),
|
|
182
|
+
Route(mcpPath, handle_mcp, methods=['POST']),
|
|
183
|
+
Route(mcpPath, reject_mcp_stream, methods=['GET', 'DELETE']),
|
|
184
|
+
]
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _render_consent_page(consentRequestToken: str, csrfToken: str, request: McpAuthorizationRequest, resourceName: str, consentPath: str) -> str:
|
|
188
|
+
redirectHost = urllib.parse.urlparse(request.redirectUri).netloc
|
|
189
|
+
return f"""<!DOCTYPE html>
|
|
190
|
+
<html lang="en">
|
|
191
|
+
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Connect {html.escape(request.clientName)}</title>
|
|
192
|
+
<style>body{{font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;line-height:1.5}}code{{word-break:break-all}}button{{font-size:1rem;padding:.5rem 1rem;margin-right:.5rem}}</style></head>
|
|
193
|
+
<body>
|
|
194
|
+
<h1>Connect {html.escape(request.clientName)}?</h1>
|
|
195
|
+
<p><strong>{html.escape(request.clientName)}</strong> wants to access <strong>{html.escape(resourceName)}</strong> as you.</p>
|
|
196
|
+
<p>After you sign in, access will be sent to <strong>{html.escape(redirectHost)}</strong> (<code>{html.escape(request.redirectUri)}</code>). Only continue if you started this connection yourself.</p>
|
|
197
|
+
<form method="post" action="{html.escape(consentPath)}">
|
|
198
|
+
<input type="hidden" name="consent_request" value="{html.escape(consentRequestToken)}">
|
|
199
|
+
<input type="hidden" name="csrf_token" value="{html.escape(csrfToken)}">
|
|
200
|
+
<button type="submit" name="decision" value="approve">Allow</button>
|
|
201
|
+
<button type="submit" name="decision" value="deny">Deny</button>
|
|
202
|
+
</form>
|
|
203
|
+
</body>
|
|
204
|
+
</html>
|
|
205
|
+
"""
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _set_cookie(response: Response, name: str, value: str, maxAgeSeconds: int) -> None:
|
|
209
|
+
response.set_cookie(key=name, value=value, max_age=maxAgeSeconds, path='/', secure=True, httponly=True, samesite='lax')
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _oauth_error(error: str, description: str) -> Response:
|
|
213
|
+
return JSONResponse({'error': error, 'error_description': description}, status_code=400, headers={'Cache-Control': 'no-store'})
|