Skip to content

🛡️ Sentinel: [CRITICAL] Fix timing attack vulnerability in token validation#711

Open
matdev83 wants to merge 1 commit into
devfrom
fix-timing-attack-token-validation-11785717866638839489
Open

🛡️ Sentinel: [CRITICAL] Fix timing attack vulnerability in token validation#711
matdev83 wants to merge 1 commit into
devfrom
fix-timing-attack-token-validation-11785717866638839489

Conversation

@matdev83
Copy link
Copy Markdown
Owner

🛡️ Sentinel: [CRITICAL] Fix timing attack vulnerability in token validation

🚨 Severity: CRITICAL
💡 Vulnerability: API key and authentication token validation in AuthMiddleware and APIKeyMiddleware used standard Python string equality (!=) and set membership (in) checks. These standard comparison operators perform short-circuit evaluation, returning immediately upon finding a mismatch. This means the time it takes for a server to reject a request depends on how many characters of the provided token match the correct token, allowing a timing attack to brute-force valid tokens.
🎯 Impact: Attackers could potentially deduce valid API keys or auth tokens by measuring response times, leading to unauthorized access.
🔧 Fix: Replaced standard equality checks with secrets.compare_digest in src/core/security/middleware.py. This ensures constant-time comparisons, mitigating timing attack risks.
✅ Verification: Ran unit tests for authentication logic to ensure secrets.compare_digest operates seamlessly without throwing TypeError (by checking isinstance(valid_key, str)) and that authentication still effectively works.


PR created automatically by Jules for task 11785717866638839489 started by @matdev83

…dation

🚨 Severity: CRITICAL
💡 Vulnerability: API key and authentication token validation in `AuthMiddleware` and `APIKeyMiddleware` used standard Python string equality (`!=`) and set membership (`in`) checks. These standard comparison operators perform short-circuit evaluation, returning immediately upon finding a mismatch. This means the time it takes for a server to reject a request depends on how many characters of the provided token match the correct token, allowing a timing attack to brute-force valid tokens.
🎯 Impact: Attackers could potentially deduce valid API keys or auth tokens by measuring response times, leading to unauthorized access.
🔧 Fix: Replaced standard equality checks with `secrets.compare_digest` in `src/core/security/middleware.py`. This ensures constant-time comparisons, mitigating timing attack risks.
✅ Verification: Ran unit tests for authentication logic to ensure `secrets.compare_digest` operates seamlessly without throwing `TypeError` (by checking `isinstance(valid_key, str)`) and that authentication still effectively works.

Co-authored-by: matdev83 <211248003+matdev83@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 23, 2026

Important

Review skipped

Too many files!

This PR contains 300 files, which is 150 over the limit of 150.

To get a review, narrow the scope:
• coderabbit review --type committed # exclude uncommitted changes
• coderabbit review --dir # limit to a subdirectory
• coderabbit review --base # compare against a closer base

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8ca136a4-6f66-43f0-8bcd-3ee4cf31b83b

📥 Commits

Reviewing files that changed from the base of the PR and between 90c1385 and 3c0ef80.

📒 Files selected for processing (300)
  • .jules/sentinel.md
  • src/core/security/middleware.py
  • src/core/transport/fastapi/adapters/response/other_response_builder.py
  • src/core/transport/fastapi/adapters/response/streaming_response_builder.py
  • src/core/transport/fastapi/adapters/sanitization/__init__.py
  • src/core/transport/fastapi/adapters/sanitization/header_sanitizer.py
  • src/core/transport/fastapi/adapters/sanitization/json_sanitizer.py
  • src/core/transport/fastapi/adapters/sse/__init__.py
  • src/core/transport/fastapi/adapters/sse/formatter.py
  • src/core/transport/fastapi/adapters/streaming/__init__.py
  • src/core/transport/fastapi/adapters/streaming/tool_block_buffer.py
  • src/core/transport/fastapi/adapters/usage/__init__.py
  • src/core/transport/fastapi/adapters/usage/header_injector.py
  • src/core/transport/fastapi/adapters/usage/normalizer.py
  • src/core/transport/fastapi/exception_adapters.py
  • src/core/transport/fastapi/request_adapters.py
  • src/core/transport/fastapi/response_adapters.py
  • src/core/transport/streaming/__init__.py
  • src/core/transport/streaming/sse_serializer_utils.py
  • src/core/utils/message_processing_utils.py
  • src/core/utils/usage_recalculation.py
  • src/core/wire_capture/inspection/analysis_pairs.py
  • src/core/wire_capture/inspection/analysis_streaming.py
  • src/core/wire_capture/inspection/analysis_track.py
  • src/core/wire_capture/inspection/app.py
  • src/core/wire_capture/inspection/export_json.py
  • src/core/wire_capture/inspection/render_console.py
  • src/loop_detection/event.py
  • src/request_middleware.py
  • src/security.py
  • src/services/steering/policies/binary_file_edit_policy.py
  • src/services/steering/policies/configured_rules_policy.py
  • src/services/steering/policies/inline_python_policy.py
  • src/services/steering/unified_steering_handler.py
  • src/services/test_execution_reminder/__init__.py
  • src/services/test_execution_reminder/completion_signal_detector.py
  • src/services/test_execution_reminder/eos_subscriber.py
  • src/services/test_execution_reminder/file_modification_detector.py
  • src/services/test_execution_reminder/session_state.py
  • src/tool_call_loop/lifecycle_registry.py
  • src/tool_call_loop/tracker.py
  • tests/__init__.py
  • tests/architecture/test_boundaries.py
  • tests/behavior/test_application_state_behavior.py
  • tests/behavior/test_dangerous_command_behavior.py
  • tests/behavior/test_failure_handling_behavior.py
  • tests/behavior/test_gemini_base_performance_regression.py
  • tests/behavior/test_gemini_base_regression.py
  • tests/behavior/test_loop_breaking_behavior.py
  • tests/behavior/test_project_directory_detection_behavior.py
  • tests/behavior/test_pytest_context_saving_behavior.py
  • tests/behavior/test_wire_capture_behavior.py
  • tests/benchmark_loop_detection.py
  • tests/characterization/test_backend_completion_flow_invariants.py
  • tests/chat_completions_tests/test_anthropic_api_compatibility.py
  • tests/chat_completions_tests/test_anthropic_frontend.py
  • tests/codex/__init__.py
  • tests/codex/conftest.py
  • tests/codex/integration/__init__.py
  • tests/codex/integration/test_droid_codex_compatibility.py
  • tests/codex/unit/__init__.py
  • tests/codex/unit/test_droid_result_formatter.py
  • tests/codex/unit/test_droid_session_detector.py
  • tests/codex/unit/test_droid_tool_translator.py
  • tests/demo_schema_fix.py
  • tests/example_usage.py
  • tests/fixtures/__init__.py
  • tests/fixtures/app_config.py
  • tests/helpers/backend_request_manager_fixtures.py
  • tests/helpers/quality_verifier_factory_stub.py
  • tests/integration/__init__.py
  • tests/integration/codebuff/test_server_integration.py
  • tests/integration/codebuff/test_websocket_flows.py
  • tests/integration/commands/loop_detection_commands/test_integration_loop_detection_command.py
  • tests/integration/commands/loop_detection_commands/test_integration_tool_loop_detection_command.py
  • tests/integration/commands/loop_detection_commands/test_integration_tool_loop_max_repeats_command.py
  • tests/integration/commands/loop_detection_commands/test_integration_tool_loop_mode_command.py
  • tests/integration/commands/loop_detection_commands/test_integration_tool_loop_ttl_command.py
  • tests/integration/commands/test_integration_failover_commands.py
  • tests/integration/commands/test_integration_help_command.py
  • tests/integration/commands/test_integration_model_command.py
  • tests/integration/commands/test_integration_oneoff_command.py
  • tests/integration/commands/test_integration_project_command.py
  • tests/integration/commands/test_integration_pwd_command.py
  • tests/integration/commands/test_integration_set_command.py
  • tests/integration/commands/test_integration_temperature_command.py
  • tests/integration/commands/test_integration_unset_command.py
  • tests/integration/conftest.py
  • tests/integration/connectors/gemini_base/__init__.py
  • tests/integration/connectors/test_hybrid_backend_integration.py
  • tests/integration/core/domain/test_request_context_propagation.py
  • tests/integration/core/services/test_backend_cancellation.py
  • tests/integration/core/services/test_capture_boundary_contracts.py
  • tests/integration/core/services/test_capture_deterministic_serialization.py
  • tests/integration/core/services/test_client_termination_transports.py
  • tests/integration/core/services/test_end_of_session_wiring.py
  • tests/integration/core/services/test_eos_end_to_end.py
  • tests/integration/core/services/test_eos_subscribers_integration.py
  • tests/integration/core/services/test_usage_normalization_service_di.py
  • tests/integration/core/transport/test_transport_to_core_canonical_contracts.py
  • tests/integration/test_429_streaming_retry.py
  • tests/integration/test_access_mode_health_endpoint.py
  • tests/integration/test_agent_config_compatibility.py
  • tests/integration/test_anthropic_backend.py
  • tests/integration/test_anthropic_frontend_integration.py
  • tests/integration/test_anthropic_translation_integration.py
  • tests/integration/test_app.py
  • tests/integration/test_backend_completion_collaborator_wiring.py
  • tests/integration/test_backend_probing.py
  • tests/integration/test_backend_request_manager_e2e.py
  • tests/integration/test_boundary_coercion.py
  • tests/integration/test_cli_parameter_override_integration.py
  • tests/integration/test_codex_backend_wiring.py
  • tests/integration/test_codex_compatibility_flows.py
  • tests/integration/test_codex_executor_path.py
  • tests/integration/test_codex_kilo_compatibility_e2e.py
  • tests/integration/test_codex_streaming_retry_parity.py
  • tests/integration/test_concurrent_oauth_rate_limit_with_replacement_integration.py
  • tests/integration/test_concurrent_streaming_isolation.py
  • tests/integration/test_content_rewriting_middleware.py
  • tests/integration/test_cross_api_codex_routing.py
  • tests/integration/test_cross_protocol_routing_consistency.py
  • tests/integration/test_custom_model_parameters.py
  • tests/integration/test_dangerous_command_middleware_integration.py
  • tests/integration/test_database_disposal_on_app_shutdown.py
  • tests/integration/test_database_engine_disposal.py
  • tests/integration/test_di_container_integrity.py
  • tests/integration/test_di_extracted_services.py
  • tests/integration/test_direct_controllers.py
  • tests/integration/test_edit_precision_e2e_di.py
  • tests/integration/test_edit_precision_e2e_di_stream.py
  • tests/integration/test_empty_response_handling.py
  • tests/integration/test_end_to_end_loop_detection.py
  • tests/integration/test_expected_json_gate.py
  • tests/integration/test_failover_routes_integration.py
  • tests/integration/test_file_sandboxing_integration.py
  • tests/integration/test_gemini_client_integration.py
  • tests/integration/test_gemini_edit_precision.py
  • tests/integration/test_gemini_end_to_end.py
  • tests/integration/test_hello_command_integration.py
  • tests/integration/test_history_compaction_integration.py
  • tests/integration/test_hybrid_reasoning_override.py
  • tests/integration/test_integration_helpers.py
  • tests/integration/test_json_repair_pipeline.py
  • tests/integration/test_loop_detection_session_isolation_e2e.py
  • tests/integration/test_models_endpoints.py
  • tests/integration/test_multimodal_integration.py
  • tests/integration/test_new_architecture.py
  • tests/integration/test_non_forwardable_backend_flow.py
  • tests/integration/test_non_forwardable_entry_points.py
  • tests/integration/test_nvidia_backend_http_e2e.py
  • tests/integration/test_nvidia_connector_in_process_respx.py
  • tests/integration/test_oneoff_command_integration.py
  • tests/integration/test_oneoff_commands_minimal.py
  • tests/integration/test_parallel_agent_session_isolation.py
  • tests/integration/test_processing_order.py
  • tests/integration/test_project_directory_resolution_integration.py
  • tests/integration/test_prompt_prefix_suffix.py
  • tests/integration/test_protocol_response_behavior.py
  • tests/integration/test_pwd_command_integration.py
  • tests/integration/test_real_world_loop_detection.py
  • tests/integration/test_reasoning_aliases_end_to_end.py
  • tests/integration/test_reasoning_aliases_integration.py
  • tests/integration/test_reasoning_backend_integration.py
  • tests/integration/test_reasoning_effort.py
  • tests/integration/test_reasoning_parameters.py
  • tests/integration/test_redaction_integration.py
  • tests/integration/test_replacement_concurrent_sessions.py
  • tests/integration/test_replacement_full_flow.py
  • tests/integration/test_replacement_metrics_integration.py
  • tests/integration/test_replacement_multi_turn.py
  • tests/integration/test_replacement_opt_out.py
  • tests/integration/test_replacement_same_model_skip.py
  • tests/integration/test_responses_api_frontend_integration.py
  • tests/integration/test_responses_api_integration.py
  • tests/integration/test_responses_api_translation_scenarios.py
  • tests/integration/test_retry_on_swallow_integration.py
  • tests/integration/test_simple_gemini_client.py
  • tests/integration/test_sso_authentication_integration.py
  • tests/integration/test_sso_reauth_token_linking.py
  • tests/integration/test_sso_saml_integration.py
  • tests/integration/test_sso_startup_validation_integration.py
  • tests/integration/test_streaming_compatibility.py
  • tests/integration/test_streaming_error_status_codes.py
  • tests/integration/test_streaming_json_repair_integration.py
  • tests/integration/test_streaming_performance.py
  • tests/integration/test_streaming_pipeline_integration.py
  • tests/integration/test_test_execution_reminder_integration.py
  • tests/integration/test_think_tags_fix_integration.py
  • tests/integration/test_tool_access_control_cli_overrides.py
  • tests/integration/test_tool_access_control_e2e.py
  • tests/integration/test_tool_access_control_handler_registration.py
  • tests/integration/test_tool_access_control_telemetry.py
  • tests/integration/test_tool_call_buffering_integration.py
  • tests/integration/test_tool_call_loop_detection.py
  • tests/integration/test_tool_call_processing_e2e.py
  • tests/integration/test_tool_call_reactor_no_globals.py
  • tests/integration/test_tool_filtering_compatibility.py
  • tests/integration/test_uri_parameters_e2e.py
  • tests/integration/test_usage_accounting_compatibility.py
  • tests/integration/test_versioned_api.py
  • tests/integration/test_vtc_response_wrapper_integration.py
  • tests/integration/test_vtc_roundtrip.py
  • tests/integration/test_windows_double_ampersand_streaming_propagation.py
  • tests/integration/test_wire_capture_compatibility.py
  • tests/integration/test_xml_leakage_fix.py
  • tests/integration/test_zai_real_integration.py
  • tests/integration/transport/fastapi/test_response_adapters_integration.py
  • tests/integration_demo.py
  • tests/k_asyncio_plugin.py
  • tests/live/conftest.py
  • tests/live/test_backend_contracts.py
  • tests/live/test_e2e_flows.py
  • tests/mocks/backend_factory.py
  • tests/mocks/connection_manager.py
  • tests/mocks/mock_backend.py
  • tests/mocks/mock_backend_service.py
  • tests/mocks/mock_http_client.py
  • tests/mocks/mock_regression_backend.py
  • tests/performance/__init__.py
  • tests/performance/test_backend_stage_startup_performance.py
  • tests/performance/test_replacement_performance.py
  • tests/property/MIDDLEWARE_PROPERTIES_SUMMARY.md
  • tests/property/codebuff/__init__.py
  • tests/property/codebuff/test_authentication_properties.py
  • tests/property/codebuff/test_connection_properties.py
  • tests/property/codebuff/test_exception_hierarchy_properties.py
  • tests/property/codebuff/test_init_handler_properties.py
  • tests/property/codebuff/test_logging_properties.py
  • tests/property/codebuff/test_message_routing_properties.py
  • tests/property/codebuff/test_message_schema_validation_properties.py
  • tests/property/codebuff/test_prompt_handler_properties.py
  • tests/property/codebuff/test_streaming_properties.py
  • tests/property/conftest.py
  • tests/property/core/__init__.py
  • tests/property/core/cli_support/__init__.py
  • tests/property/core/cli_support/test_configuration_applicator_property.py
  • tests/property/core/cli_support/test_domain_applicators_property.py
  • tests/property/core/cli_support/test_error_handler_property.py
  • tests/property/core/cli_support/test_logging_configurator_property.py
  • tests/property/core/cli_support/test_privilege_checker_property.py
  • tests/property/core/cli_support/test_public_api_property.py
  • tests/property/core/services/test_access_mode_validator_auth_enforcement_property.py
  • tests/property/core/services/test_access_mode_validator_cli_flags_property.py
  • tests/property/core/services/test_access_mode_validator_error_guidance_property.py
  • tests/property/core/services/test_access_mode_validator_localhost_property.py
  • tests/property/core/services/test_access_mode_validator_non_localhost_auth_property.py
  • tests/property/core/test_backend_service_api_preservation.py
  • tests/property/core/test_exception_normalizer_properties.py
  • tests/property/core/test_model_alias_resolver_properties.py
  • tests/property/core/test_planning_phase_manager_properties.py
  • tests/property/core/test_reasoning_config_applicator_properties.py
  • tests/property/core/test_stream_formatting_service_properties.py
  • tests/property/core/test_uri_parameter_applicator_properties.py
  • tests/property/core/test_usage_normalization_properties.py
  • tests/property/core/test_usage_tracking_wrapper_properties.py
  • tests/property/memory/__init__.py
  • tests/property/memory/test_buffer_size_enforcement_properties.py
  • tests/property/memory/test_memory_availability_gating_properties.py
  • tests/property/memory/test_memory_config_precedence_properties.py
  • tests/property/memory/test_retention_enforcement_properties.py
  • tests/property/memory/test_session_state_isolation_properties.py
  • tests/property/memory/test_summary_storage_completeness_properties.py
  • tests/property/test_agent_config_compatibility_property.py
  • tests/property/test_all_language_test_runner_detection_properties.py
  • tests/property/test_backend_validation.py
  • tests/property/test_content_accumulation_properties.py
  • tests/property/test_disabled_feature_properties.py
  • tests/property/test_documentation_structure.py
  • tests/property/test_file_modification_detection_properties.py
  • tests/property/test_javascript_test_runner_detection_properties.py
  • tests/property/test_opt_out_header.py
  • tests/property/test_pattern_priority_properties.py
  • tests/property/test_python_test_runner_detection_properties.py
  • tests/property/test_replacement_config_properties.py
  • tests/property/test_replacement_session_management.py
  • tests/property/test_replacement_state_serialization.py
  • tests/property/test_replacement_state_transitions.py
  • tests/property/test_replacement_triggering.py
  • tests/property/test_replacement_turn_completion.py
  • tests/property/test_request_processor_integration.py
  • tests/property/test_session_isolation_properties.py
  • tests/property/test_sso_auth_middleware_properties.py
  • tests/property/test_sso_authorization_enterprise_properties.py
  • tests/property/test_sso_authorization_properties.py
  • tests/property/test_sso_authorization_service_properties.py
  • tests/property/test_sso_config_properties.py
  • tests/property/test_sso_database_properties.py
  • tests/property/test_sso_login_token_properties.py
  • tests/property/test_sso_provider_selection_properties.py
  • tests/property/test_sso_rate_limit_properties.py
  • tests/property/test_sso_sandbox_properties.py
  • tests/property/test_sso_startup_properties.py
  • tests/property/test_sso_startup_validation_properties.py
  • tests/property/test_stop_chunk_with_usage_properties.py
  • tests/property/test_streaming_async_properties.py
  • tests/property/test_streaming_content_roundtrip.py
  • tests/property/test_streaming_context_association.py
  • tests/property/test_streaming_contract_properties.py
  • tests/property/test_streaming_error_handling.py

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-timing-attack-token-validation-11785717866638839489

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3c0ef80f0a

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +225 to +226
for valid_key in all_valid_keys:
if isinstance(valid_key, str) and secrets.compare_digest(
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore O(1) API key lookup path

Replacing api_key in all_valid_keys with a full for loop over every key makes authentication cost grow linearly with the number of configured keys on every request; this can become a noticeable throughput regression (and CPU amplification vector) in deployments that keep many tenant keys in memory. The same pattern appears in both the dispatch and ASGI __call__ paths, so all API-key-protected traffic pays this cost. Consider preserving constant-time comparison semantics without scanning the entire key set per request.

Useful? React with 👍 / 👎.

"""Test string representation."""
state = EndpointHealthState(api_url="https://api.openai.com/v1")
repr_str = repr(state)
assert "api.openai.com" in repr_str
)

assert config.type == "oauth2"
assert "amazonaws.com" in config.discovery_url
follow_redirects=False,
)
assert response.status_code == 302
assert "accounts.google.com" in response.headers["location"]

def _find_free_port():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(("", 0))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants