Fix: Return error from attempted security scheme instead of first defined scheme#1135
Conversation
There was a problem hiding this comment.
Pull request overview
This PR adjusts the OpenAPI security middleware’s error selection when multiple OR security schemes are defined, so that the returned error reflects the scheme that was actually attempted (i.e., had credentials provided) rather than always returning the first scheme’s missing-credentials error.
Changes:
- Add an
attemptedflag to security handler results and prefer attempted-scheme errors when choosing which error to return. - Track whether
AuthValidatorpassed before invoking a handler to determine “attempted”. - Add a regression test and a new OpenAPI path (
/bearer_or_apikey) to validate the behavior.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
src/middlewares/openapi.security.ts |
Adds attempted tracking and updates error selection to prefer attempted-scheme failures. |
test/security.handlers.spec.ts |
Adds an integration test covering bearer-vs-apikey OR error selection. |
test/resources/security.yaml |
Adds /bearer_or_apikey path with OR security requirements for the new test. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 3 out of 3 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
Co-authored-by: Copilot <[email protected]>
|
@cdimascio I have made all the necessary changes. Is there anything else to do? |
Problem
When multiple security schemes are defined (e.g.,
BearerAuth OR ApiKeyAuth) and a user provides credentials for only one scheme, the error returned was always from the first defined security scheme rather than the one actually attempted.Example
Given this OpenAPI security configuration:
Before this fix
User sends request with an invalid ApiKey but no Bearer token.
ApiKey validation runs and fails with "Invalid API key".
❌ Error returned: "Authorization header required" (from BearerAuth, which wasn't attempted).
After this fix
User sends request with an invalid ApiKey but no Bearer token.
ApiKey validation runs and fails with "Invalid API key"
✅ Error returned: "Invalid API key provided" (from ApiKeyAuth, which was actually attempted)
Solution
Added an attempted flag to track which security schemes received credentials. The error selection logic now prioritizes errors from schemes where authentication was actually attempted over schemes where credentials were missing.
Closes #1118