kiba-core 0.5.3.dev95__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.dev95 → kiba_core-0.5.3.dev97}/CHANGELOG.md +5 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/PKG-INFO +1 -1
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/database_connection_middleware.py +6 -2
- {kiba_core-0.5.3.dev95 → 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.dev95 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/PKG-INFO +1 -1
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/SOURCES.txt +15 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/pyproject.toml +1 -1
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_database_connection_middleware.py +22 -0
- {kiba_core-0.5.3.dev95 → 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.dev95 → kiba_core-0.5.3.dev97}/.github/pull_request_template.md +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/.github/workflows/deploy.yml +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/.github/workflows/publish.yml +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/.github/workflows/pull-request.yml +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/.github/workflows/release.yml +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/.gitignore +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/Dockerfile +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/README.md +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/api_request.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/api_response.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/authorizer.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/default_routes.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/health.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/json_route.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/logging_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/middleware/server_headers_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/openapi.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/rate_limit.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/request_context.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/route.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/route_auth.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/route_metadata.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/api/uploaded_file.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/aws_requester.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/caching/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/caching/cache.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/caching/dict_cache.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/caching/file_cache.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/cron/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/cron/api_request_cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/cron/cron_executor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/cron/cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/cron/model.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/exceptions.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/http/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/http/basic_authentication.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/http/jwt.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/http/rest_method.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/locks/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/locks/lock.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/locks/model.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/locks/sql.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/logging.py +0 -0
- {kiba_core-0.5.3.dev95/core/notifications → kiba_core-0.5.3.dev97/core/mcp}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95/core/queues → kiba_core-0.5.3.dev97/core/mcp/oauth_store}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95/core/store → kiba_core-0.5.3.dev97/core/notifications}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/notifications/discord_client.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/notifications/notification_client.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/notifications/slack_client.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/py.typed +0 -0
- {kiba_core-0.5.3.dev95/core/util → kiba_core-0.5.3.dev97/core/queues}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/aqs.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/cosmos.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/message_queue.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/model.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/sql.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/queues/sqs.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/requester/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/requester/requester.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/s3_manager.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/service_client.py +0 -0
- {kiba_core-0.5.3.dev95/core/web3 → kiba_core-0.5.3.dev97/core/store}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/store/database.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/store/entity_repository.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/store/retriever.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/store/saver.py +0 -0
- {kiba_core-0.5.3.dev95/tests/cron → kiba_core-0.5.3.dev97/core/util}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/async_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/chain_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/date_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/dict_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/file_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/hashing_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/http_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/json_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/list_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/process_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/string_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/typing_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/url_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/util/value_holder.py +0 -0
- {kiba_core-0.5.3.dev95/tests/requester → kiba_core-0.5.3.dev97/core/web3}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/web3/eth_client.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/web3/eth_client_registry.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/core/web3/multicall3.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/dependency_links.txt +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/requires.txt +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/kiba_core.egg-info/top_level.txt +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/makefile +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/setup.cfg +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_api_response.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_authorizer.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_openapi.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_rate_limit.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_request_context.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_route.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/api/test_streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/caching/test_dict_cache.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/caching/test_file_cache.py +0 -0
- {kiba_core-0.5.3.dev95/tests/web3 → kiba_core-0.5.3.dev97/tests/cron}/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/cron/test_cron_executor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/locks/test_sql_lock.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/conftest.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/test_aqs_queue.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/test_cosmos_queue.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/test_message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/test_sql_queue.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/queues/test_sqs_queue.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/requester/test_requester.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/test_database.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/test_entity_repository.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/test_exceptions.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/test_logging.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/__init__.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_async_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_chain_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_date_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_dict_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_file_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_json_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_list_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_process_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_string_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/util/test_url_util.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/web3/test_eth_client_registry.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/tests/web3/test_rest_eth_client.py +0 -0
- {kiba_core-0.5.3.dev95 → kiba_core-0.5.3.dev97}/uv.lock +0 -0
|
@@ -8,6 +8,11 @@ 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
|
|
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
|
|
11
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
|
|
12
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
|
|
13
18
|
- [PATCH] Fixed `DatabaseConnectionMiddleware`'s commit when the response starts failing ("another operation is in progress") for streaming responses behind a `BaseHTTPMiddleware`: `Database.execute` and `Database.commit_context_connection` now wait for each other on the same connection
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
from collections.abc import Collection
|
|
2
|
+
|
|
1
3
|
from starlette.types import ASGIApp
|
|
2
4
|
from starlette.types import Message
|
|
3
5
|
from starlette.types import Receive
|
|
@@ -8,14 +10,16 @@ from core.store.database import Database
|
|
|
8
10
|
|
|
9
11
|
|
|
10
12
|
class DatabaseConnectionMiddleware:
|
|
11
|
-
def __init__(self, app: ASGIApp, database: Database) -> None:
|
|
13
|
+
def __init__(self, app: ASGIApp, database: Database, excludedPaths: Collection[str] = (), excludedPathPrefixes: Collection[str] = ()) -> None:
|
|
12
14
|
self.app = app
|
|
13
15
|
self.database = database
|
|
16
|
+
self.excludedPaths = frozenset(excludedPaths)
|
|
17
|
+
self.excludedPathPrefixes = tuple(excludedPathPrefixes)
|
|
14
18
|
|
|
15
19
|
# NOTE(krishan711): see note in database.py about why this can cause problems with concurrent operations
|
|
16
20
|
# NOTE(krishan711): raw ASGI (not BaseHTTPMiddleware) so the DB connection stays open across streaming body
|
|
17
21
|
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
18
|
-
if scope['type'] != 'http':
|
|
22
|
+
if scope['type'] != 'http' or scope['path'] in self.excludedPaths or scope['path'].startswith(self.excludedPathPrefixes):
|
|
19
23
|
await self.app(scope, receive, send)
|
|
20
24
|
return
|
|
21
25
|
async with self.database.create_context_connection():
|
|
@@ -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
|