kiba-core 0.5.3.dev97__tar.gz → 0.5.3.dev99__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.dev97 → kiba_core-0.5.3.dev99}/CHANGELOG.md +11 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/PKG-INFO +5 -5
- kiba_core-0.5.3.dev99/core/api/middleware/blocked_ip_middleware.py +69 -0
- kiba_core-0.5.3.dev99/core/api/middleware/gzip_middleware.py +21 -0
- kiba_core-0.5.3.dev99/core/api/middleware/public_cors_middleware.py +41 -0
- kiba_core-0.5.3.dev99/core/api/middleware/security_headers_middleware.py +26 -0
- kiba_core-0.5.3.dev99/core/auth_tokens/auth_token_invalidation_store.py +14 -0
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/dict_mcp_oauth_store.py → kiba_core-0.5.3.dev99/core/auth_tokens/dict_auth_token_invalidation_store.py +5 -5
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/sql_mcp_oauth_store.py → kiba_core-0.5.3.dev99/core/auth_tokens/sql_auth_token_invalidation_store.py +18 -15
- kiba_core-0.5.3.dev99/core/http/signed_token_manager.py +53 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/mcp/mcp_oauth_server.py +26 -60
- kiba_core-0.5.3.dev99/core/util/number_util.py +17 -0
- kiba_core-0.5.3.dev99/core/web3/erc20.py +62 -0
- kiba_core-0.5.3.dev99/core/web3/erc4626.py +251 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/web3/eth_client.py +34 -18
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/web3/multicall3.py +1 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/kiba_core.egg-info/PKG-INFO +5 -5
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/kiba_core.egg-info/SOURCES.txt +20 -5
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/kiba_core.egg-info/requires.txt +4 -4
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/pyproject.toml +6 -6
- kiba_core-0.5.3.dev99/tests/api/test_blocked_ip_middleware.py +89 -0
- kiba_core-0.5.3.dev99/tests/api/test_gzip_middleware.py +28 -0
- kiba_core-0.5.3.dev99/tests/api/test_public_cors_middleware.py +50 -0
- kiba_core-0.5.3.dev99/tests/auth_tokens/test_auth_token_invalidation_store.py +46 -0
- kiba_core-0.5.3.dev99/tests/http/test_signed_token_manager.py +57 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/locks/test_sql_lock.py +3 -2
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/mcp/conftest.py +2 -2
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/mcp/test_mcp_oauth.py +1 -1
- kiba_core-0.5.3.dev99/tests/requester/__init__.py +0 -0
- kiba_core-0.5.3.dev99/tests/util/test_number_util.py +26 -0
- kiba_core-0.5.3.dev99/tests/web3/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/web3/test_rest_eth_client.py +18 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/uv.lock +428 -338
- kiba_core-0.5.3.dev97/core/mcp/oauth_store/mcp_oauth_store.py +0 -12
- kiba_core-0.5.3.dev97/tests/mcp/test_mcp_oauth_store.py +0 -46
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.github/pull_request_template.md +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.github/workflows/deploy.yml +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.github/workflows/publish.yml +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.github/workflows/pull-request.yml +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.github/workflows/release.yml +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/.gitignore +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/Dockerfile +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/README.md +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/api_request.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/api_response.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/authorizer.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/default_routes.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/health.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/json_route.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/database_connection_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/logging_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/middleware/server_headers_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/openapi.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/rate_limit.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/request_body.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/request_context.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/route.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/route_auth.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/route_metadata.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/api/uploaded_file.py +0 -0
- {kiba_core-0.5.3.dev97/core/caching → kiba_core-0.5.3.dev99/core/auth_tokens}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/aws_requester.py +0 -0
- {kiba_core-0.5.3.dev97/core/cron → kiba_core-0.5.3.dev99/core/caching}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/caching/cache.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/caching/dict_cache.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/caching/file_cache.py +0 -0
- {kiba_core-0.5.3.dev97/core/locks → kiba_core-0.5.3.dev99/core/cron}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/cron/api_request_cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/cron/cron_executor.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/cron/cron_job_processor.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/cron/model.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/exceptions.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/http/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/http/basic_authentication.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/http/jwt.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/http/rest_method.py +0 -0
- {kiba_core-0.5.3.dev97/core/mcp → kiba_core-0.5.3.dev99/core/locks}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/locks/lock.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/locks/model.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/locks/sql.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/logging.py +0 -0
- {kiba_core-0.5.3.dev97/core/mcp/oauth_store → kiba_core-0.5.3.dev99/core/mcp}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/mcp/mcp_identity_provider.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/mcp/mcp_routes.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/mcp/mcp_server.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/mcp/model.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/notifications/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/notifications/discord_client.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/notifications/notification_client.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/notifications/slack_client.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/py.typed +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/aqs.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/cosmos.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/message_queue.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/model.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/sql.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/queues/sqs.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/requester/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/requester/requester.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/s3_manager.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/service_client.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/store/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/store/database.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/store/entity_repository.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/store/retriever.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/store/saver.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/async_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/chain_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/date_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/dict_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/file_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/hashing_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/http_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/json_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/list_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/process_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/string_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/typing_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/url_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/util/value_holder.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/web3/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/core/web3/eth_client_registry.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/kiba_core.egg-info/dependency_links.txt +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/kiba_core.egg-info/top_level.txt +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/makefile +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/setup.cfg +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_api_response.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_authorizer.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_database_connection_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_exception_handling_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_json_route.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_openapi.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_origin_ip_middleware.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_rate_limit.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_request_context.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_route.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/api/test_streaming_json_route.py +0 -0
- {kiba_core-0.5.3.dev97/tests/cron → kiba_core-0.5.3.dev99/tests/auth_tokens}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/caching/test_dict_cache.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/caching/test_file_cache.py +0 -0
- {kiba_core-0.5.3.dev97/tests/mcp → kiba_core-0.5.3.dev99/tests/cron}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/cron/test_cron_executor.py +0 -0
- {kiba_core-0.5.3.dev97/tests/requester → kiba_core-0.5.3.dev99/tests/http}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97/tests/web3 → kiba_core-0.5.3.dev99/tests/mcp}/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/mcp/test_mcp_server.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/conftest.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/test_aqs_queue.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/test_cosmos_queue.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/test_message_queue_processor.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/test_sql_queue.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/queues/test_sqs_queue.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/requester/test_requester.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/test_database.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/test_entity_repository.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/test_exceptions.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/test_logging.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/__init__.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_async_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_chain_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_date_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_dict_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_file_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_json_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_list_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_process_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_string_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/util/test_url_util.py +0 -0
- {kiba_core-0.5.3.dev97 → kiba_core-0.5.3.dev99}/tests/web3/test_eth_client_registry.py +0 -0
|
@@ -8,6 +8,17 @@ 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.api.middleware.blocked_ip_middleware.BlockedIpMiddleware` to answer 403 to requests from `blockedNetworks` (CIDRs) or a loaded `TorExitList`, checking every hop in `trustedProxyHeaders` and the socket peer
|
|
12
|
+
- [MINOR] Added `core.api.middleware.public_cors_middleware.PublicCorsMiddleware` to let any origin call the given `paths` (add it after starlette's `CORSMiddleware` so it answers their preflights first)
|
|
13
|
+
- [MINOR] Added `core.api.middleware.security_headers_middleware.SecurityHeadersMiddleware` to add fixed headers to every response
|
|
14
|
+
- [MINOR] Added `core.api.middleware.gzip_middleware.GZipMiddleware`, starlette's `GZipMiddleware` with `excludedPaths` and `excludedPathSuffixes` that are never compressed (e.g. responses carrying tokens, against BREACH)
|
|
15
|
+
- [MAJOR] Renamed `RestEthClient._make_request` to `make_request` for RPC methods without a helper (e.g. bundler methods)
|
|
16
|
+
- [MINOR] Added `RestEthClient.get_balance`, `get_storage_at` and `get_safe_block_number`
|
|
17
|
+
- [MINOR] Added `getEthBalance` to `MULTICALL3_ABI`
|
|
18
|
+
- [MINOR] Added `core.web3.erc20` (`ERC20_ABI`, `ERC20_TRANSFER_EVENT_TOPIC`) and `core.web3.erc4626` (`ERC4626_ABI`)
|
|
19
|
+
- [MINOR] Added `core.util.number_util.short_format_number`, matching `shortFormatNumber` in `@kibalabs/core`
|
|
20
|
+
- [MAJOR] Moved `core.mcp.oauth_store` to `core.auth_tokens`: `McpOAuthStore`, `DictMcpOAuthStore` and `SqlMcpOAuthStore` are now `AuthTokenInvalidationStore`, `DictAuthTokenInvalidationStore` and `SqlAuthTokenInvalidationStore`, with `claim`/`is_claimed` renamed to `invalidate`/`is_invalidated`. `McpOAuthClaimsTable` is now `AuthTokenInvalidationsTable` (`tbl_auth_token_invalidations`), which adds an `id` primary key and a `created_date` column and makes `key` unique, so apps that already created `tbl_mcp_oauth_claims` need a migration
|
|
21
|
+
- [MINOR] Added `core.http.signed_token_manager.SignedTokenManager` to create and validate typed HS256 JWTs (each with its own `tokenId`, so an `AuthTokenInvalidationStore` can make them single-use); `McpOAuthServer` uses it for its tokens
|
|
11
22
|
- [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
23
|
- [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
24
|
- [MINOR] Added `core.mcp.mcp_routes.create_mcp_routes` to mount both on a starlette app
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kiba-core
|
|
3
|
-
Version: 0.5.3.
|
|
3
|
+
Version: 0.5.3.dev99
|
|
4
4
|
Summary: Kiba Labs' python utilities
|
|
5
5
|
Project-URL: repository, https://github.com/kibalabs/core-py
|
|
6
6
|
Requires-Python: <4,>=3.12
|
|
7
7
|
Description-Content-Type: text/markdown
|
|
8
8
|
Requires-Dist: aiofiles>=25.1.0
|
|
9
|
-
Requires-Dist: pydantic>=2.14.
|
|
9
|
+
Requires-Dist: pydantic>=2.14.2
|
|
10
10
|
Requires-Dist: orjson>=3.13.0
|
|
11
11
|
Provides-Extra: api
|
|
12
12
|
Requires-Dist: fastapi>=0.162.0; extra == "api"
|
|
@@ -14,7 +14,7 @@ Requires-Dist: uvicorn[standard]>=0.54.0; extra == "api"
|
|
|
14
14
|
Provides-Extra: core-api
|
|
15
15
|
Requires-Dist: starlette>=1.10.0; extra == "core-api"
|
|
16
16
|
Requires-Dist: uvicorn[standard]>=0.54.0; extra == "core-api"
|
|
17
|
-
Requires-Dist: python-multipart>=0.0.
|
|
17
|
+
Requires-Dist: python-multipart>=0.0.33; extra == "core-api"
|
|
18
18
|
Provides-Extra: storage
|
|
19
19
|
Requires-Dist: aiobotocore>=3.10.0; extra == "storage"
|
|
20
20
|
Provides-Extra: queues
|
|
@@ -22,7 +22,7 @@ Requires-Dist: aiobotocore>=3.10.0; extra == "queues"
|
|
|
22
22
|
Provides-Extra: queue-sqs
|
|
23
23
|
Requires-Dist: aiobotocore>=3.10.0; extra == "queue-sqs"
|
|
24
24
|
Provides-Extra: queue-aqs
|
|
25
|
-
Requires-Dist: azure-storage-queue[aio]>=12.18.
|
|
25
|
+
Requires-Dist: azure-storage-queue[aio]>=12.18.1; extra == "queue-aqs"
|
|
26
26
|
Provides-Extra: queue-cosmos
|
|
27
27
|
Requires-Dist: azure-cosmos>=4.17.1; extra == "queue-cosmos"
|
|
28
28
|
Provides-Extra: database-psql
|
|
@@ -34,7 +34,7 @@ Requires-Dist: aiosqlite>=0.22.1; extra == "database-sqlite"
|
|
|
34
34
|
Provides-Extra: requester
|
|
35
35
|
Requires-Dist: httpx2>=2.16.0; extra == "requester"
|
|
36
36
|
Provides-Extra: web3
|
|
37
|
-
Requires-Dist: web3<
|
|
37
|
+
Requires-Dist: web3<9.0.0,>=8.0.0; extra == "web3"
|
|
38
38
|
Provides-Extra: cron
|
|
39
39
|
Requires-Dist: apscheduler<4,>=3.11.3; extra == "cron"
|
|
40
40
|
Provides-Extra: types
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import ipaddress
|
|
2
|
+
from collections.abc import Collection
|
|
3
|
+
|
|
4
|
+
from starlette.datastructures import Headers
|
|
5
|
+
from starlette.responses import Response
|
|
6
|
+
from starlette.types import ASGIApp
|
|
7
|
+
from starlette.types import Receive
|
|
8
|
+
from starlette.types import Scope
|
|
9
|
+
from starlette.types import Send
|
|
10
|
+
|
|
11
|
+
from core import logging
|
|
12
|
+
from core.requester import Requester
|
|
13
|
+
|
|
14
|
+
IpAddress = ipaddress.IPv4Address | ipaddress.IPv6Address
|
|
15
|
+
|
|
16
|
+
TOR_EXIT_LIST_URL = 'https://check.torproject.org/torbulkexitlist'
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _parse_ip(value: str) -> IpAddress | None:
|
|
20
|
+
try:
|
|
21
|
+
return ipaddress.ip_address(value.strip())
|
|
22
|
+
except ValueError:
|
|
23
|
+
return None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class TorExitList:
|
|
27
|
+
def __init__(self, requester: Requester) -> None:
|
|
28
|
+
self.requester = requester
|
|
29
|
+
self.addresses: frozenset[IpAddress] = frozenset()
|
|
30
|
+
|
|
31
|
+
async def load(self) -> None:
|
|
32
|
+
try:
|
|
33
|
+
response = await self.requester.get(url=TOR_EXIT_LIST_URL, timeout=30)
|
|
34
|
+
except Exception as exception: # noqa: BLE001
|
|
35
|
+
logging.error(f'Failed to load Tor exit list, Tor exits will not be blocked: {exception}')
|
|
36
|
+
return
|
|
37
|
+
self.addresses = frozenset(address for address in (_parse_ip(value=line) for line in response.text.splitlines()) if address is not None)
|
|
38
|
+
logging.info(f'Loaded {len(self.addresses)} Tor exit addresses')
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class BlockedIpMiddleware:
|
|
42
|
+
def __init__(self, app: ASGIApp, blockedNetworks: Collection[str] = (), torExitList: TorExitList | None = None, trustedProxyHeaders: Collection[str] = ()) -> None:
|
|
43
|
+
self.app = app
|
|
44
|
+
self.blockedNetworks = [ipaddress.ip_network(network) for network in blockedNetworks]
|
|
45
|
+
self.torExitList = torExitList
|
|
46
|
+
self.trustedProxyHeaders = tuple(trustedProxyHeaders)
|
|
47
|
+
|
|
48
|
+
def _is_blocked_ip(self, value: str) -> bool:
|
|
49
|
+
address = _parse_ip(value=value)
|
|
50
|
+
if address is None:
|
|
51
|
+
return False
|
|
52
|
+
if self.torExitList is not None and address in self.torExitList.addresses:
|
|
53
|
+
return True
|
|
54
|
+
return any(address in network for network in self.blockedNetworks)
|
|
55
|
+
|
|
56
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
57
|
+
if scope['type'] != 'http':
|
|
58
|
+
await self.app(scope, receive, send)
|
|
59
|
+
return
|
|
60
|
+
headers = Headers(scope=scope)
|
|
61
|
+
# NOTE(krishan711): every hop in the proxy headers is checked (not just the first like OriginIpMiddleware) so a spoofed first hop can't hide a blocked address
|
|
62
|
+
candidateIps = [value for headerName in self.trustedProxyHeaders for value in headers.get(headerName, '').split(',')]
|
|
63
|
+
client = scope.get('client')
|
|
64
|
+
if client:
|
|
65
|
+
candidateIps.append(str(client[0]))
|
|
66
|
+
if any(self._is_blocked_ip(value=candidateIp) for candidateIp in candidateIps):
|
|
67
|
+
await Response(status_code=403)(scope, receive, send)
|
|
68
|
+
return
|
|
69
|
+
await self.app(scope, receive, send)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
from collections.abc import Collection
|
|
2
|
+
|
|
3
|
+
from starlette.middleware import gzip
|
|
4
|
+
from starlette.types import ASGIApp
|
|
5
|
+
from starlette.types import Receive
|
|
6
|
+
from starlette.types import Scope
|
|
7
|
+
from starlette.types import Send
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class GZipMiddleware(gzip.GZipMiddleware):
|
|
11
|
+
# NOTE(krishan711): exclude responses that carry secrets (tokens, signed urls): compressing them enables BREACH
|
|
12
|
+
def __init__(self, app: ASGIApp, minimum_size: int = 500, compresslevel: int = 9, excludedPaths: Collection[str] = (), excludedPathSuffixes: Collection[str] = ()) -> None:
|
|
13
|
+
super().__init__(app=app, minimum_size=minimum_size, compresslevel=compresslevel)
|
|
14
|
+
self.excludedPaths = frozenset(excludedPaths)
|
|
15
|
+
self.excludedPathSuffixes = tuple(excludedPathSuffixes)
|
|
16
|
+
|
|
17
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
18
|
+
if scope['type'] == 'http' and (scope['path'] in self.excludedPaths or scope['path'].endswith(self.excludedPathSuffixes)):
|
|
19
|
+
await self.app(scope, receive, send)
|
|
20
|
+
return
|
|
21
|
+
await super().__call__(scope, receive, send)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from collections.abc import Collection
|
|
2
|
+
|
|
3
|
+
from starlette.datastructures import MutableHeaders
|
|
4
|
+
from starlette.responses import Response
|
|
5
|
+
from starlette.types import ASGIApp
|
|
6
|
+
from starlette.types import Message
|
|
7
|
+
from starlette.types import Receive
|
|
8
|
+
from starlette.types import Scope
|
|
9
|
+
from starlette.types import Send
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
# NOTE(krishan711): add this after starlette's CORSMiddleware so it runs outside it, otherwise CORSMiddleware rejects
|
|
13
|
+
# preflights for these paths from origins it doesn't allow before they get here
|
|
14
|
+
class PublicCorsMiddleware:
|
|
15
|
+
def __init__(self, app: ASGIApp, paths: Collection[str], allowedMethods: Collection[str] = ('GET',)) -> None:
|
|
16
|
+
self.app = app
|
|
17
|
+
self.paths = frozenset(paths)
|
|
18
|
+
self.allowMethodsHeader = ', '.join([*allowedMethods, 'OPTIONS'])
|
|
19
|
+
|
|
20
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
21
|
+
if scope['type'] != 'http' or scope['path'] not in self.paths:
|
|
22
|
+
await self.app(scope, receive, send)
|
|
23
|
+
return
|
|
24
|
+
if scope['method'] == 'OPTIONS':
|
|
25
|
+
response = Response(
|
|
26
|
+
status_code=204,
|
|
27
|
+
headers={
|
|
28
|
+
'Access-Control-Allow-Origin': '*',
|
|
29
|
+
'Access-Control-Allow-Methods': self.allowMethodsHeader,
|
|
30
|
+
'Access-Control-Allow-Headers': '*',
|
|
31
|
+
},
|
|
32
|
+
)
|
|
33
|
+
await response(scope, receive, send)
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
async def send_with_cors_header(message: Message) -> None:
|
|
37
|
+
if message['type'] == 'http.response.start':
|
|
38
|
+
MutableHeaders(scope=message).setdefault('Access-Control-Allow-Origin', '*')
|
|
39
|
+
await send(message)
|
|
40
|
+
|
|
41
|
+
await self.app(scope, receive, send_with_cors_header)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from collections.abc import Mapping
|
|
2
|
+
|
|
3
|
+
from starlette.datastructures import MutableHeaders
|
|
4
|
+
from starlette.types import ASGIApp
|
|
5
|
+
from starlette.types import Message
|
|
6
|
+
from starlette.types import Receive
|
|
7
|
+
from starlette.types import Scope
|
|
8
|
+
from starlette.types import Send
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class SecurityHeadersMiddleware:
|
|
12
|
+
def __init__(self, app: ASGIApp, headers: Mapping[str, str]) -> None:
|
|
13
|
+
self.app = app
|
|
14
|
+
self.headers = dict(headers)
|
|
15
|
+
|
|
16
|
+
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
|
17
|
+
if scope['type'] != 'http':
|
|
18
|
+
await self.app(scope, receive, send)
|
|
19
|
+
return
|
|
20
|
+
|
|
21
|
+
async def send_with_security_headers(message: Message) -> None:
|
|
22
|
+
if message['type'] == 'http.response.start':
|
|
23
|
+
MutableHeaders(scope=message).update(self.headers)
|
|
24
|
+
await send(message)
|
|
25
|
+
|
|
26
|
+
await self.app(scope, receive, send_with_security_headers)
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
from abc import ABC
|
|
3
|
+
from abc import abstractmethod
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
# NOTE(krishan711): records auth tokens (OAuth states, codes, refresh tokens, link secrets) and grants that must not be
|
|
7
|
+
# accepted again. Keep each invalidation until the token itself has expired; deleting one makes the token valid again
|
|
8
|
+
class AuthTokenInvalidationStore(ABC):
|
|
9
|
+
# NOTE(krishan711): must be atomic: only the first invalidation of an unexpired key returns True
|
|
10
|
+
@abstractmethod
|
|
11
|
+
async def invalidate(self, key: str, lifetime: datetime.timedelta) -> bool: ...
|
|
12
|
+
|
|
13
|
+
@abstractmethod
|
|
14
|
+
async def is_invalidated(self, key: str) -> bool: ...
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
import datetime
|
|
2
2
|
|
|
3
|
-
from core.
|
|
3
|
+
from core.auth_tokens.auth_token_invalidation_store import AuthTokenInvalidationStore
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
# NOTE(krishan711): only safe for a single process that is never restarted mid-flow; use
|
|
7
|
-
class
|
|
6
|
+
# NOTE(krishan711): only safe for a single process that is never restarted mid-flow; use SqlAuthTokenInvalidationStore otherwise
|
|
7
|
+
class DictAuthTokenInvalidationStore(AuthTokenInvalidationStore):
|
|
8
8
|
def __init__(self) -> None:
|
|
9
9
|
self._expiryDates: dict[str, datetime.datetime] = {}
|
|
10
10
|
|
|
11
|
-
async def
|
|
11
|
+
async def invalidate(self, key: str, lifetime: datetime.timedelta) -> bool:
|
|
12
12
|
self._remove_expired()
|
|
13
13
|
if key in self._expiryDates:
|
|
14
14
|
return False
|
|
15
15
|
self._expiryDates[key] = datetime.datetime.now(tz=datetime.UTC) + lifetime
|
|
16
16
|
return True
|
|
17
17
|
|
|
18
|
-
async def
|
|
18
|
+
async def is_invalidated(self, key: str) -> bool:
|
|
19
19
|
self._remove_expired()
|
|
20
20
|
return key in self._expiryDates
|
|
21
21
|
|
|
@@ -4,42 +4,45 @@ import sqlalchemy
|
|
|
4
4
|
from sqlalchemy.dialects import postgresql as sqlalchemy_psql
|
|
5
5
|
from sqlalchemy.dialects import sqlite as sqlalchemy_sqlite
|
|
6
6
|
|
|
7
|
+
from core.auth_tokens.auth_token_invalidation_store import AuthTokenInvalidationStore
|
|
7
8
|
from core.exceptions import InternalServerErrorException
|
|
8
|
-
from core.mcp.oauth_store.mcp_oauth_store import McpOAuthStore
|
|
9
9
|
from core.store.database import Database
|
|
10
10
|
from core.store.database import DatabaseTable
|
|
11
11
|
|
|
12
12
|
# NOTE(krishan711): like LocksTable, this table ships with core-py. To include it in an app's alembic-tracked metadata
|
|
13
|
-
# (so autogenerate creates it), call `
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
'
|
|
18
|
-
|
|
19
|
-
sqlalchemy.Column(key='
|
|
13
|
+
# (so autogenerate creates it), call `AuthTokenInvalidationsTable.to_metadata(appMetadata)` from the app's schema module.
|
|
14
|
+
AuthTokenInvalidationsMetadata = sqlalchemy.MetaData()
|
|
15
|
+
|
|
16
|
+
AuthTokenInvalidationsTable = sqlalchemy.Table(
|
|
17
|
+
'tbl_auth_token_invalidations',
|
|
18
|
+
AuthTokenInvalidationsMetadata,
|
|
19
|
+
sqlalchemy.Column(key='id', name='id', type_=sqlalchemy.Integer, autoincrement=True, primary_key=True, nullable=False),
|
|
20
|
+
sqlalchemy.Column(key='createdDate', name='created_date', type_=sqlalchemy.DateTime(timezone=True), nullable=False),
|
|
21
|
+
sqlalchemy.Column(key='key', name='key', type_=sqlalchemy.Text, nullable=False),
|
|
20
22
|
sqlalchemy.Column(key='expiryDate', name='expiry_date', type_=sqlalchemy.DateTime(timezone=True), nullable=False),
|
|
21
|
-
sqlalchemy.
|
|
23
|
+
sqlalchemy.UniqueConstraint('key', name='tbl_auth_token_invalidations_ux_key'),
|
|
24
|
+
sqlalchemy.Index('tbl_auth_token_invalidations_idx_expiry_date', 'expiryDate'),
|
|
22
25
|
)
|
|
23
26
|
|
|
24
27
|
|
|
25
|
-
class
|
|
26
|
-
def __init__(self, database: Database, table: DatabaseTable =
|
|
28
|
+
class SqlAuthTokenInvalidationStore(AuthTokenInvalidationStore):
|
|
29
|
+
def __init__(self, database: Database, table: DatabaseTable = AuthTokenInvalidationsTable) -> None:
|
|
27
30
|
self.database = database
|
|
28
31
|
self.table = table
|
|
29
32
|
|
|
30
|
-
async def
|
|
33
|
+
async def invalidate(self, key: str, lifetime: datetime.timedelta) -> bool:
|
|
31
34
|
async with self.database.create_transaction() as connection:
|
|
32
35
|
await self.database.execute(query=sqlalchemy.delete(self.table).where(self.table.c.expiryDate <= self.database.now()), connection=connection)
|
|
33
36
|
insertQuery = (
|
|
34
37
|
self._create_insert(dialectName=connection.dialect.name)
|
|
35
|
-
.values({self.table.c.key: key, self.table.c.expiryDate: self.database.now(seconds=lifetime.total_seconds())})
|
|
38
|
+
.values({self.table.c.createdDate: self.database.now(), self.table.c.key: key, self.table.c.expiryDate: self.database.now(seconds=lifetime.total_seconds())})
|
|
36
39
|
.on_conflict_do_nothing(index_elements=[self.table.c.key])
|
|
37
40
|
.returning(self.table.c.key)
|
|
38
41
|
)
|
|
39
42
|
result = await self.database.execute(query=insertQuery, connection=connection)
|
|
40
43
|
return result.first() is not None
|
|
41
44
|
|
|
42
|
-
async def
|
|
45
|
+
async def is_invalidated(self, key: str) -> bool:
|
|
43
46
|
async with self.database.create_transaction() as connection:
|
|
44
47
|
query = sqlalchemy.select(self.table.c.key).where(self.table.c.key == key).where(self.table.c.expiryDate > self.database.now())
|
|
45
48
|
result = await self.database.execute(query=query, connection=connection)
|
|
@@ -50,4 +53,4 @@ class SqlMcpOAuthStore(McpOAuthStore):
|
|
|
50
53
|
return sqlalchemy_psql.insert(self.table)
|
|
51
54
|
if dialectName == 'sqlite':
|
|
52
55
|
return sqlalchemy_sqlite.insert(self.table)
|
|
53
|
-
raise InternalServerErrorException(message=f'
|
|
56
|
+
raise InternalServerErrorException(message=f'SqlAuthTokenInvalidationStore does not support dialect: {dialectName}')
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import uuid
|
|
5
|
+
|
|
6
|
+
from core.exceptions import UnauthorizedException
|
|
7
|
+
from core.http.jwt import KibaJwt
|
|
8
|
+
from core.util import date_util
|
|
9
|
+
from core.util.typing_util import JsonObject
|
|
10
|
+
|
|
11
|
+
TOKEN_TYPE_KEY = 'tty'
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
# NOTE(krishan711): HS256 JWTs typed by tokenType so a token issued for one purpose can't be used for another. Each token
|
|
15
|
+
# has a tokenId, so pair it with an AuthTokenInvalidationStore to make a token single-use
|
|
16
|
+
class SignedTokenManager:
|
|
17
|
+
def __init__(self, secret: str, keyId: str) -> None:
|
|
18
|
+
self._secret = secret.encode('utf-8')
|
|
19
|
+
self.keyId = keyId
|
|
20
|
+
|
|
21
|
+
def create_token(self, tokenType: str, lifetime: datetime.timedelta, claims: JsonObject) -> str:
|
|
22
|
+
issueDate = date_util.datetime_from_now()
|
|
23
|
+
jwt = KibaJwt(
|
|
24
|
+
headerDict={KibaJwt.Key.ALGORITHM: 'HS256', KibaJwt.Key.TYPE: 'JWT', KibaJwt.Key.KEY_ID: self.keyId},
|
|
25
|
+
payloadDict={
|
|
26
|
+
**claims,
|
|
27
|
+
KibaJwt.Key.TOKEN_ID: str(uuid.uuid4()),
|
|
28
|
+
TOKEN_TYPE_KEY: tokenType,
|
|
29
|
+
KibaJwt.Key.ISSUE_DATE: int(issueDate.timestamp()),
|
|
30
|
+
KibaJwt.Key.EXPIRY_DATE: int((issueDate + lifetime).timestamp()),
|
|
31
|
+
},
|
|
32
|
+
)
|
|
33
|
+
jwt.signatureBytes = self._sign(jwt=jwt)
|
|
34
|
+
return jwt.to_string()
|
|
35
|
+
|
|
36
|
+
def validate_token(self, tokenString: str, tokenType: str) -> KibaJwt:
|
|
37
|
+
try:
|
|
38
|
+
jwt = KibaJwt.from_string(jwtString=tokenString)
|
|
39
|
+
except Exception as exception:
|
|
40
|
+
raise UnauthorizedException(message='INVALID_TOKEN') from exception
|
|
41
|
+
if not isinstance(jwt.headerDict, dict) or not isinstance(jwt.payloadDict, dict):
|
|
42
|
+
raise UnauthorizedException(message='INVALID_TOKEN')
|
|
43
|
+
if jwt.algorithm != 'HS256' or jwt.keyId != self.keyId or not hmac.compare_digest(jwt.signatureBytes, self._sign(jwt=jwt)):
|
|
44
|
+
raise UnauthorizedException(message='INVALID_TOKEN')
|
|
45
|
+
if jwt.payloadDict.get(TOKEN_TYPE_KEY) != tokenType:
|
|
46
|
+
raise UnauthorizedException(message='INVALID_TOKEN_TYPE')
|
|
47
|
+
expiryDate = jwt.expiryDate
|
|
48
|
+
if not expiryDate or expiryDate <= date_util.datetime_from_now():
|
|
49
|
+
raise UnauthorizedException(message='TOKEN_EXPIRED')
|
|
50
|
+
return jwt
|
|
51
|
+
|
|
52
|
+
def _sign(self, jwt: KibaJwt) -> bytes:
|
|
53
|
+
return hmac.new(self._secret, jwt.verificationString.encode('utf-8'), hashlib.sha256).digest()
|
|
@@ -12,10 +12,12 @@ import urllib.parse
|
|
|
12
12
|
import uuid
|
|
13
13
|
|
|
14
14
|
from core import logging
|
|
15
|
+
from core.auth_tokens.auth_token_invalidation_store import AuthTokenInvalidationStore
|
|
15
16
|
from core.exceptions import BadRequestException
|
|
16
17
|
from core.exceptions import KibaException
|
|
17
18
|
from core.exceptions import UnauthorizedException
|
|
18
19
|
from core.http.jwt import KibaJwt
|
|
20
|
+
from core.http.signed_token_manager import SignedTokenManager
|
|
19
21
|
from core.mcp.mcp_identity_provider import McpIdentityProvider
|
|
20
22
|
from core.mcp.model import McpAuthorizationRequest
|
|
21
23
|
from core.mcp.model import McpCachedClient
|
|
@@ -23,7 +25,6 @@ from core.mcp.model import McpClient
|
|
|
23
25
|
from core.mcp.model import McpProviderLogin
|
|
24
26
|
from core.mcp.model import McpTokenPair
|
|
25
27
|
from core.mcp.model import McpUser
|
|
26
|
-
from core.mcp.oauth_store.mcp_oauth_store import McpOAuthStore
|
|
27
28
|
from core.util import date_util
|
|
28
29
|
from core.util import json_util
|
|
29
30
|
from core.util.typing_util import JsonObject
|
|
@@ -32,7 +33,6 @@ if typing.TYPE_CHECKING:
|
|
|
32
33
|
from core.requester import Requester
|
|
33
34
|
|
|
34
35
|
JWT_KEY_ID = 'mcp-oauth-v1'
|
|
35
|
-
TOKEN_TYPE_KEY = 'tty'
|
|
36
36
|
AUDIENCE_KEY = 'aud'
|
|
37
37
|
CLIENT_ID_KEY = 'cid'
|
|
38
38
|
CLIENT_NAME_KEY = 'cnm'
|
|
@@ -60,7 +60,7 @@ class McpOAuthServer:
|
|
|
60
60
|
def __init__(
|
|
61
61
|
self,
|
|
62
62
|
identityProvider: McpIdentityProvider,
|
|
63
|
-
store:
|
|
63
|
+
store: AuthTokenInvalidationStore,
|
|
64
64
|
jwtSecret: str,
|
|
65
65
|
baseUrl: str,
|
|
66
66
|
allowedRedirectUris: list[str] | None = None,
|
|
@@ -75,7 +75,7 @@ class McpOAuthServer:
|
|
|
75
75
|
) -> None:
|
|
76
76
|
self.identityProvider = identityProvider
|
|
77
77
|
self.store = store
|
|
78
|
-
self.
|
|
78
|
+
self.tokenManager = SignedTokenManager(secret=jwtSecret, keyId=JWT_KEY_ID)
|
|
79
79
|
self.baseUrl = baseUrl.rstrip('/')
|
|
80
80
|
self.allowedRedirectUris = set(allowedRedirectUris) if allowedRedirectUris is not None else None
|
|
81
81
|
# NOTE(krishan711): enables Client ID Metadata Documents; pass a Requester that doesn't follow redirects (SSRF)
|
|
@@ -116,7 +116,7 @@ class McpOAuthServer:
|
|
|
116
116
|
for redirectUri in redirectUris:
|
|
117
117
|
self._ensure_allowed_redirect_uri(redirectUri=redirectUri)
|
|
118
118
|
name = clientName or 'MCP client'
|
|
119
|
-
clientId = self.
|
|
119
|
+
clientId = self.tokenManager.create_token(tokenType='mcpClient', lifetime=CLIENT_REGISTRATION_LIFETIME, claims={CLIENT_NAME_KEY: name, CLIENT_REDIRECT_URIS_KEY: redirectUris})
|
|
120
120
|
return {
|
|
121
121
|
'client_id': clientId,
|
|
122
122
|
'client_id_issued_at': int(date_util.datetime_from_now().timestamp()),
|
|
@@ -153,11 +153,11 @@ class McpOAuthServer:
|
|
|
153
153
|
return self._consent_key(request=request) in self._get_consent_keys(consentToken=consentToken)
|
|
154
154
|
|
|
155
155
|
def create_consent_request_token(self, request: McpAuthorizationRequest) -> str:
|
|
156
|
-
return self.
|
|
156
|
+
return self.tokenManager.create_token(tokenType='mcpConsentRequest', lifetime=CONSENT_REQUEST_LIFETIME, claims=self._request_claims(request=request))
|
|
157
157
|
|
|
158
158
|
def get_consent_request(self, consentRequestToken: str) -> McpAuthorizationRequest:
|
|
159
159
|
try:
|
|
160
|
-
requestJwt = self.
|
|
160
|
+
requestJwt = self.tokenManager.validate_token(tokenString=consentRequestToken, tokenType='mcpConsentRequest')
|
|
161
161
|
except UnauthorizedException as exception:
|
|
162
162
|
raise BadRequestException(message='INVALID_CONSENT_REQUEST') from exception
|
|
163
163
|
return self._request_from_jwt(jwt=requestJwt)
|
|
@@ -165,11 +165,11 @@ class McpOAuthServer:
|
|
|
165
165
|
def add_consent(self, consentToken: str | None, request: McpAuthorizationRequest) -> str:
|
|
166
166
|
consentKey = self._consent_key(request=request)
|
|
167
167
|
consentKeys = [*[key for key in self._get_consent_keys(consentToken=consentToken) if key != consentKey], consentKey][-MAX_CONSENT_COUNT:]
|
|
168
|
-
return self.
|
|
168
|
+
return self.tokenManager.create_token(tokenType='mcpConsent', lifetime=self.consentLifetime, claims={CONSENTS_KEY: consentKeys})
|
|
169
169
|
|
|
170
170
|
def start_provider_login(self, request: McpAuthorizationRequest) -> McpProviderLogin:
|
|
171
171
|
stateNonce = secrets.token_urlsafe(32)
|
|
172
|
-
stateToken = self.
|
|
172
|
+
stateToken = self.tokenManager.create_token(tokenType='mcpState', lifetime=self.stateTokenLifetime, claims={**self._request_claims(request=request), STATE_NONCE_KEY: stateNonce})
|
|
173
173
|
return McpProviderLogin(authorizeUrl=self.identityProvider.create_authorize_url(redirectUri=self.providerCallbackUrl, state=stateToken), stateNonce=stateNonce)
|
|
174
174
|
|
|
175
175
|
def create_client_error_redirect(self, request: McpAuthorizationRequest, error: str) -> str:
|
|
@@ -177,12 +177,12 @@ class McpOAuthServer:
|
|
|
177
177
|
|
|
178
178
|
async def complete_provider_login(self, providerCode: str | None, stateToken: str, stateNonce: str | None) -> str:
|
|
179
179
|
try:
|
|
180
|
-
stateJwt = self.
|
|
180
|
+
stateJwt = self.tokenManager.validate_token(tokenString=stateToken, tokenType='mcpState')
|
|
181
181
|
except UnauthorizedException as exception:
|
|
182
182
|
raise BadRequestException(message='INVALID_STATE') from exception
|
|
183
183
|
if not stateNonce or not hmac.compare_digest(stateNonce, typing.cast(str, stateJwt.payloadDict[STATE_NONCE_KEY])):
|
|
184
184
|
raise BadRequestException(message='STATE_NOT_FROM_THIS_BROWSER')
|
|
185
|
-
if not await self.store.
|
|
185
|
+
if not await self.store.invalidate(key=f'state:{stateJwt.tokenId}', lifetime=self.stateTokenLifetime):
|
|
186
186
|
raise BadRequestException(message='STATE_ALREADY_USED')
|
|
187
187
|
request = self._request_from_jwt(jwt=stateJwt)
|
|
188
188
|
if not providerCode:
|
|
@@ -192,11 +192,11 @@ class McpOAuthServer:
|
|
|
192
192
|
except KibaException as exception:
|
|
193
193
|
logging.warning(f'MCP provider login failed: {exception.message}')
|
|
194
194
|
return self.create_client_error_redirect(request=request, error='access_denied')
|
|
195
|
-
code = self.
|
|
195
|
+
code = self.tokenManager.create_token(tokenType='mcpCode', lifetime=self.codeTokenLifetime, claims={**self._user_claims(user=user), **self._request_claims(request=request)})
|
|
196
196
|
return self._client_redirect_url(redirectUri=request.redirectUri, params={'code': code, 'state': request.clientState})
|
|
197
197
|
|
|
198
198
|
async def exchange_authorization_code(self, code: str, codeVerifier: str, redirectUri: str, clientId: str, resource: str | None) -> McpTokenPair:
|
|
199
|
-
codeJwt = self.
|
|
199
|
+
codeJwt = self.tokenManager.validate_token(tokenString=code, tokenType='mcpCode')
|
|
200
200
|
if clientId != codeJwt.payloadDict[CLIENT_ID_KEY] or redirectUri != codeJwt.payloadDict[CLIENT_REDIRECT_URI_KEY] or not PKCE_VERIFIER_PATTERN.match(codeVerifier):
|
|
201
201
|
raise UnauthorizedException(message='INVALID_GRANT')
|
|
202
202
|
codeChallenge = base64.urlsafe_b64encode(hashlib.sha256(codeVerifier.encode('ascii')).digest()).decode('ascii').rstrip('=')
|
|
@@ -204,43 +204,43 @@ class McpOAuthServer:
|
|
|
204
204
|
raise UnauthorizedException(message='INVALID_GRANT')
|
|
205
205
|
if not self._is_valid_resource(resource=resource):
|
|
206
206
|
raise UnauthorizedException(message='INVALID_TARGET')
|
|
207
|
-
if not await self.store.
|
|
207
|
+
if not await self.store.invalidate(key=f'code:{codeJwt.tokenId}', lifetime=self.codeTokenLifetime):
|
|
208
208
|
raise UnauthorizedException(message='CODE_ALREADY_USED')
|
|
209
209
|
grantExpiryDate = date_util.datetime_from_now(seconds=self.grantLifetime.total_seconds())
|
|
210
210
|
return self._create_token_pair(user=self._user_from_jwt(jwt=codeJwt), clientId=clientId, grantId=str(uuid.uuid4()), grantExpiryTimestamp=int(grantExpiryDate.timestamp()))
|
|
211
211
|
|
|
212
212
|
async def refresh_tokens(self, refreshToken: str, clientId: str | None, resource: str | None) -> McpTokenPair:
|
|
213
|
-
refreshJwt = self.
|
|
213
|
+
refreshJwt = self.tokenManager.validate_token(tokenString=refreshToken, tokenType='mcpRefresh')
|
|
214
214
|
tokenClientId = typing.cast(str, refreshJwt.payloadDict[CLIENT_ID_KEY])
|
|
215
215
|
grantId = typing.cast(str, refreshJwt.payloadDict[GRANT_ID_KEY])
|
|
216
216
|
if clientId is not None and clientId != tokenClientId:
|
|
217
217
|
raise UnauthorizedException(message='INVALID_GRANT')
|
|
218
218
|
if not self._is_valid_resource(resource=resource):
|
|
219
219
|
raise UnauthorizedException(message='INVALID_TARGET')
|
|
220
|
-
if await self.store.
|
|
220
|
+
if await self.store.is_invalidated(key=f'revoked:{grantId}'):
|
|
221
221
|
raise UnauthorizedException(message='TOKEN_REVOKED')
|
|
222
222
|
user = self._user_from_jwt(jwt=refreshJwt)
|
|
223
223
|
await self.identityProvider.ensure_user_allowed(user=user)
|
|
224
|
-
if not await self.store.
|
|
224
|
+
if not await self.store.invalidate(key=f'refresh:{refreshJwt.tokenId}', lifetime=self.refreshTokenLifetime):
|
|
225
225
|
# NOTE(krishan711): a refresh token used twice has leaked, so the whole grant is revoked
|
|
226
|
-
await self.store.
|
|
226
|
+
await self.store.invalidate(key=f'revoked:{grantId}', lifetime=self.grantLifetime)
|
|
227
227
|
raise UnauthorizedException(message='REFRESH_TOKEN_REUSED')
|
|
228
228
|
return self._create_token_pair(user=user, clientId=tokenClientId, grantId=grantId, grantExpiryTimestamp=typing.cast(int, refreshJwt.payloadDict[GRANT_EXPIRY_KEY]))
|
|
229
229
|
|
|
230
230
|
async def revoke_token(self, token: str) -> None:
|
|
231
231
|
for tokenType in ('mcpRefresh', 'mcpAccess'):
|
|
232
232
|
try:
|
|
233
|
-
tokenJwt = self.
|
|
233
|
+
tokenJwt = self.tokenManager.validate_token(tokenString=token, tokenType=tokenType)
|
|
234
234
|
except UnauthorizedException:
|
|
235
235
|
continue
|
|
236
|
-
await self.store.
|
|
236
|
+
await self.store.invalidate(key=f'revoked:{tokenJwt.payloadDict[GRANT_ID_KEY]}', lifetime=self.grantLifetime)
|
|
237
237
|
return
|
|
238
238
|
|
|
239
239
|
async def validate_access_token(self, accessToken: str) -> McpUser:
|
|
240
|
-
accessJwt = self.
|
|
240
|
+
accessJwt = self.tokenManager.validate_token(tokenString=accessToken, tokenType='mcpAccess')
|
|
241
241
|
if accessJwt.payloadDict.get(AUDIENCE_KEY) != self.resourceUrl:
|
|
242
242
|
raise UnauthorizedException(message='INVALID_AUDIENCE')
|
|
243
|
-
if await self.store.
|
|
243
|
+
if await self.store.is_invalidated(key=f'revoked:{accessJwt.payloadDict[GRANT_ID_KEY]}'):
|
|
244
244
|
raise UnauthorizedException(message='TOKEN_REVOKED')
|
|
245
245
|
return self._user_from_jwt(jwt=accessJwt)
|
|
246
246
|
|
|
@@ -261,7 +261,7 @@ class McpOAuthServer:
|
|
|
261
261
|
if clientId.startswith('https://'):
|
|
262
262
|
return await self._fetch_client_metadata(clientId=clientId)
|
|
263
263
|
try:
|
|
264
|
-
clientJwt = self.
|
|
264
|
+
clientJwt = self.tokenManager.validate_token(tokenString=clientId, tokenType='mcpClient')
|
|
265
265
|
except UnauthorizedException as exception:
|
|
266
266
|
raise BadRequestException(message='INVALID_CLIENT') from exception
|
|
267
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]))
|
|
@@ -296,7 +296,7 @@ class McpOAuthServer:
|
|
|
296
296
|
if not consentToken:
|
|
297
297
|
return []
|
|
298
298
|
try:
|
|
299
|
-
consentJwt = self.
|
|
299
|
+
consentJwt = self.tokenManager.validate_token(tokenString=consentToken, tokenType='mcpConsent')
|
|
300
300
|
except UnauthorizedException:
|
|
301
301
|
return []
|
|
302
302
|
return typing.cast(list[str], consentJwt.payloadDict.get(CONSENTS_KEY, []))
|
|
@@ -329,8 +329,8 @@ class McpOAuthServer:
|
|
|
329
329
|
refreshLifetime = min(self.refreshTokenLifetime, datetime.datetime.fromtimestamp(grantExpiryTimestamp, tz=datetime.UTC) - date_util.datetime_from_now())
|
|
330
330
|
if refreshLifetime <= datetime.timedelta(0):
|
|
331
331
|
raise UnauthorizedException(message='GRANT_EXPIRED')
|
|
332
|
-
accessToken = self.
|
|
333
|
-
refreshToken = self.
|
|
332
|
+
accessToken = self.tokenManager.create_token(tokenType='mcpAccess', lifetime=min(self.accessTokenLifetime, refreshLifetime), claims={**grantClaims, AUDIENCE_KEY: self.resourceUrl})
|
|
333
|
+
refreshToken = self.tokenManager.create_token(tokenType='mcpRefresh', lifetime=refreshLifetime, claims=grantClaims)
|
|
334
334
|
return McpTokenPair(accessToken=accessToken, refreshToken=refreshToken, expiresInSeconds=int(min(self.accessTokenLifetime, refreshLifetime).total_seconds()))
|
|
335
335
|
|
|
336
336
|
@staticmethod
|
|
@@ -341,40 +341,6 @@ class McpOAuthServer:
|
|
|
341
341
|
def _user_from_jwt(jwt: KibaJwt) -> McpUser:
|
|
342
342
|
return McpUser(userId=typing.cast(str, jwt.payloadDict[KibaJwt.Key.USER_ID]), userName=typing.cast(str, jwt.payloadDict[KibaJwt.Key.USER_NAME]))
|
|
343
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
344
|
|
|
379
345
|
def _is_ip_address(hostname: str) -> bool:
|
|
380
346
|
try:
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
# NOTE(krishan711): mirrors shortFormatNumber in @kibalabs/core so server-written text reads like the app
|
|
2
|
+
def short_format_number(value: float) -> str:
|
|
3
|
+
if value >= 1e9: # noqa: PLR2004
|
|
4
|
+
return f'{value / 1e9:.0f}B'
|
|
5
|
+
if value >= 1e7: # noqa: PLR2004
|
|
6
|
+
return f'{value / 1e6:.0f}M'
|
|
7
|
+
if value >= 1e6: # noqa: PLR2004
|
|
8
|
+
return f'{value / 1e6:.1f}M'
|
|
9
|
+
if value >= 1e4: # noqa: PLR2004
|
|
10
|
+
return f'{value / 1e3:.0f}K'
|
|
11
|
+
if value >= 1e3: # noqa: PLR2004
|
|
12
|
+
return f'{value / 1e3:.1f}K'
|
|
13
|
+
if value > 100: # noqa: PLR2004
|
|
14
|
+
return f'{value:.0f}'
|
|
15
|
+
if value > 1:
|
|
16
|
+
return f'{value:.1f}'
|
|
17
|
+
return f'{value:.2f}'
|