โ† eval_submission_analyzer

fastapi_14455

failed WRONG_FIX wrong_fix ยท 25 tool calls ยท 163 s ยท fastapi/fastapi

Task input

๐Ÿ› Fix OpenAPI security scheme OAuth2 scopes declaration, deduplicate security schemes with different scopes

๐Ÿ› Fix OpenAPI security scheme OAuth2 scopes declaration, deduplicate security schemes with different scopes

This should fix https://github.com/fastapi/fastapi/issues/14454

Tool calls (26)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"securitySchemes\" fastapi/openapi/"
}
{"status": "ok", "stdout": "fastapi/openapi/models.py:422: securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None\nfastapi/openapi/utils.
full
{"status": "ok", "stdout": "fastapi/openapi/models.py:422:    securitySchemes: Optional[Dict[str, Union[SecurityScheme, Reference]]] = None\nfastapi/openapi/utils.py:523:                    components.setdefault(\"securitySchemes\", {}).update(\nfastapi/openapi/utils.py:542:                    components.setdefault(\"securitySchemes\", {}).update(\n", "exit_code": 0}
2read_file
{
 "end_line": 560,
 "filepath": "fastapi/openapi/utils.py",
 "start_line": 510
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": " if isinstance(route, routing.APIRoute):\n result = get_openapi_path(\n route=route,\n oper
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "        if isinstance(route, routing.APIRoute):\n            result = get_openapi_path(\n                route=route,\n                operation_ids=operation_ids,\n                model_name_map=model_name_map,\n                field_mapping=field_mapping,\n                separate_input_output_schemas=separate_input_output_schemas,\n            )\n            if result:\n                path, security_schemes, path_definitions = result\n                if path:\n                    paths.setdefault(route.path_format, {}).update(path)\n                if security_schemes:\n                    components.setdefault(\"securitySchemes\", {}).update(\n                        security_schemes\n                    )\n                if path_definitions:\n                    definitions.update(path_definitions)\n    for webhook in webhooks or []:\n        if isinstance(webhook, routing.APIRoute):\n            result = get_openapi_path(\n                route=webhook,\n                operation_ids=operation_ids,\n                model_name_map=model_name_map,\n                field_mapping=field_mapping,\n                separate_input_output_schemas=separate_input_output_schemas,\n            )\n            if result:\n                path, security_schemes, path_definitions = result\n                if path:\n                    webhook_paths.setdefault(webhook.path_format, {}).update(path)\n                if security_schemes:\n                    components.setdefault(\"securitySchemes\", {}).update(\n                        security_schemes\n                    )\n                if path_definitions:\n                    definitions.update(path_definitions)\n    if definitions:\n        components[\"schemas\"] = {k: definitions[k] for k in sorted(definitions)}\n    if components:\n        output[\"components\"] = components\n    output[\"paths\"] = paths\n    if webhook_paths:\n        output[\"webh
3run_command
{
 "command": "grep<|tool_call>call:run_command{command:"
}
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "/bin/bash: -c: line 1
full
{"status": "error", "error_type": "CommandError", "error_message": "Command failed with exit code 2", "details": {"stdout": "", "stderr": "/bin/bash: -c: line 1: syntax error near unexpected token `|'\n/bin/bash: -c: line 1: `grep<|tool_call>call:run_command{command:'\n", "exit_code": 2}}
4run_command
{
 "command": "grep -rn \"get_openapi_path\" fastapi/openapi/utils.py"
}
{"status": "ok", "stdout": "250:def get_openapi_path(\n321: ) = get_openapi_path(\n511: result = get_openapi_path(\n530: result = get_openapi_path(\n", "exit_co
full
{"status": "ok", "stdout": "250:def get_openapi_path(\n321:                        ) = get_openapi_path(\n511:            result = get_openapi_path(\n530:            result = get_openapi_path(\n", "exit_code": 0}
5read_file
{
 "end_line": 350,
 "filepath": "fastapi/openapi/utils.py",
 "start_line": 250
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "def get_openapi_path(\n *,\n route: routing.APIRoute,\n operation_ids: Set[str],\n model_na
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "def get_openapi_path(\n    *,\n    route: routing.APIRoute,\n    operation_ids: Set[str],\n    model_name_map: ModelNameMap,\n    field_mapping: Dict[\n        Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n    ],\n    separate_input_output_schemas: bool = True,\n) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:\n    path = {}\n    security_schemes: Dict[str, Any] = {}\n    definitions: Dict[str, Any] = {}\n    assert route.methods is not None, \"Methods must be a list\"\n    if isinstance(route.response_class, DefaultPlaceholder):\n        current_response_class: Type[Response] = route.response_class.value\n    else:\n        current_response_class = route.response_class\n    assert current_response_class, \"A response class is needed to generate OpenAPI\"\n    route_response_media_type: Optional[str] = current_response_class.media_type\n    if route.include_in_schema:\n        for method in route.methods:\n            operation = get_openapi_operation_metadata(\n                route=route, method=method, operation_ids=operation_ids\n            )\n            parameters: List[Dict[str, Any]] = []\n            flat_dependant = get_flat_dependant(route.dependant, skip_repeats=True)\n            security_definitions, operation_security = get_openapi_security_definitions(\n                flat_dependant=flat_dependant\n            )\n            if operation_security:\n                operation.setdefault(\"security\", []).extend(operation_security)\n            if security_definitions:\n                security_schemes.update(security_definitions)\n            operation_parameters = _get_openapi_operation_parameters(\n                dependant=route.dependant,\n                model_name_map=model_name_map,\n                field_mapping=field_mapping,\n                separate_input_output_schemas=separate_input_output_schemas,\n            )\n           
6run_command
{
 "command": "grep -rn \"get_openapi_security_definitions\" fastapi/openapi/utils.py"
}
{"status": "ok", "stdout": "78:def get_openapi_security_definitions(\n277: security_definitions, operation_security = get_openapi_security_definitions(\n", "exi
full
{"status": "ok", "stdout": "78:def get_openapi_security_definitions(\n277:            security_definitions, operation_security = get_openapi_security_definitions(\n", "exit_code": 0}
7read_file
{
 "end_line": 120,
 "filepath": "fastapi/openapi/utils.py",
 "start_line": 78
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "def get_openapi_security_definitions(\n flat_dependant: Dependant,\n) -> Tuple[Dict[str, An
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "def get_openapi_security_definitions(\n    flat_dependant: Dependant,\n) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:\n    security_definitions = {}\n    operation_security = []\n    for security_requirement in flat_dependant.security_requirements:\n        security_definition = jsonable_encoder(\n            security_requirement.security_scheme.model,\n            by_alias=True,\n            exclude_none=True,\n        )\n        security_name = security_requirement.security_scheme.scheme_name\n        security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})\n    return security_definitions, operation_security\n\n\ndef _get_openapi_operation_parameters(\n    *,\n    dependant: Dependant,\n    model_name_map: ModelNameMap,\n    field_mapping: Dict[\n        Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n    ],\n    separate_input_output_schemas: bool = True,\n) -> List[Dict[str, Any]]:\n    parameters = []\n    flat_dependant = get_flat_dependant(dependant, skip_repeats=True)\n    path_params = _get_flat_fields_from_params(flat_dependant.path_params)\n    query_params = _get_flat_fields_from_params(flat_dependant.query_params)\n    header_params = _get_flat_fields_from_params(flat_dependant.header_params)\n    cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)\n    parameter_groups = [\n        (ParamTypes.path, path_params),\n        (ParamTypes.query, query_params),\n        (ParamTypes.header, header_params),\n        (ParamTypes.cookie, cookie_params),\n    ]\n    default_convert_underscores = True\n    if len(flat_dependant.header_params) == 1:\n        first_field = flat_dependant.header_params[0]\n        if lenient_issubclass(first_field.type_, BaseModel):\n            default_convert_underscores = getattr(\n", "start_line": 78, "end_line": 120, "tota
8read_file
{
 "filepath": "fastapi/openapi/utils.py",
 "start_line": 70,
 "end_line": 110
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": " \"2XX\": \"Success\",\n \"3XX\": \"Redirection\",\n \"4XX\": \"Client Error\",\n \"5XX\":
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "    \"2XX\": \"Success\",\n    \"3XX\": \"Redirection\",\n    \"4XX\": \"Client Error\",\n    \"5XX\": \"Server Error\",\n    \"DEFAULT\": \"Default Response\",\n}\n\n\ndef get_openapi_security_definitions(\n    flat_dependant: Dependant,\n) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:\n    security_definitions = {}\n    operation_security = []\n    for security_requirement in flat_dependant.security_requirements:\n        security_definition = jsonable_encoder(\n            security_requirement.security_scheme.model,\n            by_alias=True,\n            exclude_none=True,\n        )\n        security_name = security_requirement.security_scheme.scheme_name\n        security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})\n    return security_definitions, operation_security\n\n\ndef _get_openapi_operation_parameters(\n    *,\n    dependant: Dependant,\n    model_name_map: ModelNameMap,\n    field_mapping: Dict[\n        Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n    ],\n    separate_input_output_schemas: bool = True,\n) -> List[Dict[str, Any]]:\n    parameters = []\n    flat_dependant = get_flat_dependant(dependant, skip_repeats=True)\n    path_params = _get_flat_fields_from_params(flat_dependant.path_params)\n    query_params = _get_flat_fields_from_params(flat_dependant.query_params)\n    header_params = _get_flat_fields_from_params(flat_dependant.header_params)\n    cookie_params = _get_flat_fields_from_params(flat_dependant.cookie_params)\n    parameter_groups = [\n", "start_line": 70, "end_line": 110, "total_lines": 558, "is_truncated": false}
9run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'})\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'})\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nprint(json.dumps(app.openapi(), indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"openapi\": \"3.1.0\",\n \"info\": {\n \"title\": \"FastAPI\",\n \"version\": \"0.1.0\"\n },\n \"paths\": {\n \"/\": {\n \"get\
full
{"status": "ok", "stdout": "{\n  \"openapi\": \"3.1.0\",\n  \"info\": {\n    \"title\": \"FastAPI\",\n    \"version\": \"0.1.0\"\n  },\n  \"paths\": {\n    \"/\": {\n      \"get\": {\n        \"summary\": \"Root\",\n        \"operationId\": \"root__get\",\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful Response\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {}\n              }\n            }\n          }\n        },\n        \"security\": [\n          {\n            \"OAuth2PasswordBearer\": []\n          },\n          {\n            \"OAuth2PasswordBearer\": []\n          }\n        ]\n      }\n    }\n  },\n  \"components\": {\n    \"securitySchemes\": {\n      \"OAuth2PasswordBearer\": {\n        \"type\": \"oauth2\",\n        \"flows\": {\n          \"password\": {\n            \"scopes\": {\n              \"user\": \"User scope\"\n            },\n            \"tokenUrl\": \"token\"\n          }\n        }\n      }\n    }\n  }\n}\n", "exit_code": 0}
10run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'})\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'})\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/']['get']['security'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2PasswordBearer\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"user\": \"User scope\"\
full
{"status": "ok", "stdout": "{\n  \"OAuth2PasswordBearer\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"user\": \"User scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n[\n  {\n    \"OAuth2PasswordBearer\": []\n  },\n  {\n    \"OAuth2PasswordBearer\": []\n  }\n]\n", "exit_code": 0}
11read_file
{
 "end_line": 100,
 "filepath": "fastapi/security/oauth2.py",
 "start_line": 1
}
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": "from typing import Any, Dict, List, Optional, Union, cast\n\nfrom annotated_doc import Do
full
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": "from typing import Any, Dict, List, Optional, Union, cast\n\nfrom annotated_doc import Doc\nfrom fastapi.exceptions import HTTPException\nfrom fastapi.openapi.models import OAuth2 as OAuth2Model\nfrom fastapi.openapi.models import OAuthFlows as OAuthFlowsModel\nfrom fastapi.param_functions import Form\nfrom fastapi.security.base import SecurityBase\nfrom fastapi.security.utils import get_authorization_scheme_param\nfrom starlette.requests import Request\nfrom starlette.status import HTTP_401_UNAUTHORIZED\n\n# TODO: import from typing when deprecating Python 3.9\nfrom typing_extensions import Annotated\n\n\nclass OAuth2PasswordRequestForm:\n    \"\"\"\n    This is a dependency class to collect the `username` and `password` as form data\n    for an OAuth2 password flow.\n\n    The OAuth2 specification dictates that for a password flow the data should be\n    collected using form data (instead of JSON) and that it should have the specific\n    fields `username` and `password`.\n\n    All the initialization parameters are extracted from the request.\n\n    Read more about it in the\n    [FastAPI docs for Simple OAuth2 with Password and Bearer](https://fastapi.tiangolo.com/tutorial/security/simple-oauth2/).\n\n    ## Example\n\n    ```python\n    from typing import Annotated\n\n    from fastapi import Depends, FastAPI\n    from fastapi.security import OAuth2PasswordRequestForm\n\n    app = FastAPI()\n\n\n    @app.post(\"/login\")\n    def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):\n        data = {}\n        data[\"scopes\"] = []\n        for scope in form_data.scopes:\n            data[\"scopes\"].append(scope)\n        if form_data.client_id:\n            data[\"client_id\"] = form_data.client_id\n        if form_data.client_secret:\n            data[\"client_secret\"] = form_data.client_secret\n        return data\n    ```\n\n    Note that for OAuth2 the scope `items:read` i
12read_file
{
 "end_line": 300,
 "filepath": "fastapi/security/oauth2.py",
 "start_line": 101
}
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": " \"\"\"\n A single string with actually several scopes separated by spaces. Each\n scope
full
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": "                \"\"\"\n                A single string with actually several scopes separated by spaces. Each\n                scope is also a string.\n\n                For example, a single string with:\n\n                ```python\n                \"items:read items:write users:read profile openid\"\n                ````\n\n                would represent the scopes:\n\n                * `items:read`\n                * `items:write`\n                * `users:read`\n                * `profile`\n                * `openid`\n                \"\"\"\n            ),\n        ] = \"\",\n        client_id: Annotated[\n            Union[str, None],\n            Form(),\n            Doc(\n                \"\"\"\n                If there's a `client_id`, it can be sent as part of the form fields.\n                But the OAuth2 specification recommends sending the `client_id` and\n                `client_secret` (if any) using HTTP Basic auth.\n                \"\"\"\n            ),\n        ] = None,\n        client_secret: Annotated[\n            Union[str, None],\n            Form(json_schema_extra={\"format\": \"password\"}),\n            Doc(\n                \"\"\"\n                If there's a `client_password` (and a `client_id`), they can be sent\n                as part of the form fields. But the OAuth2 specification recommends\n                sending the `client_id` and `client_secret` (if any) using HTTP Basic\n                auth.\n                \"\"\"\n            ),\n        ] = None,\n    ):\n        self.grant_type = grant_type\n        self.username = username\n        self.password = password\n        self.scopes = scope.split()\n        self.client_id = client_id\n        self.client_secret = client_secret\n\n\nclass OAuth2PasswordRequestFormStrict(OAuth2PasswordRequestForm):\n    \"\"\"\n    This is a dependency class to collect the `username` and `password` as form data\n    fo
13read_file
{
 "end_line": 666,
 "filepath": "fastapi/security/oauth2.py",
 "start_line": 301
}
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": " username=username,\n password=password,\n scope=scope,\n client_id=client_id,\n client_s
full
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": "            username=username,\n            password=password,\n            scope=scope,\n            client_id=client_id,\n            client_secret=client_secret,\n        )\n\n\nclass OAuth2(SecurityBase):\n    \"\"\"\n    This is the base class for OAuth2 authentication, an instance of it would be used\n    as a dependency. All other OAuth2 classes inherit from it and customize it for\n    each OAuth2 flow.\n\n    You normally would not create a new class inheriting from it but use one of the\n    existing subclasses, and maybe compose them if you want to support multiple flows.\n\n    Read more about it in the\n    [FastAPI docs for Security](https://fastapi.tiangolo.com/tutorial/security/).\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        flows: Annotated[\n            Union[OAuthFlowsModel, Dict[str, Dict[str, Any]]],\n            Doc(\n                \"\"\"\n                The dictionary of OAuth2 flows.\n                \"\"\"\n            ),\n        ] = OAuthFlowsModel(),\n        scheme_name: Annotated[\n            Optional[str],\n            Doc(\n                \"\"\"\n                Security scheme name.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                \"\"\"\n            ),\n        ] = None,\n        description: Annotated[\n            Optional[str],\n            Doc(\n                \"\"\"\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                \"\"\"\n            ),\n        ] = None,\n        auto_error: Annotated[\n            bool,\n            Doc(\n                \"\"\"\n                By default, if no HTTP Authorization header is provided, required for\n                OAuth2 authentication, it will automatically cancel the request and\n                send the client an error.\n\n       
14read_file
{
 "end_line": 500,
 "filepath": "fastapi/security/oauth2.py",
 "start_line": 451
}
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": " description: Annotated[\n Optional[str],\n Doc(\n \"\"\"\n Security scheme description.\
full
{"status": "ok", "filepath": "fastapi/security/oauth2.py", "content": "        description: Annotated[\n            Optional[str],\n            Doc(\n                \"\"\"\n                Security scheme description.\n\n                It will be included in the generated OpenAPI (e.g. visible at `/docs`).\n                \"\"\"\n            ),\n        ] = None,\n        auto_error: Annotated[\n            bool,\n            Doc(\n                \"\"\"\n                By default, if no HTTP Authorization header is provided, required for\n                OAuth2 authentication, it will automatically cancel the request and\n                send the client an error.\n\n                If `auto_error` is set to `False`, when the HTTP Authorization header\n                is not available, instead of erroring out, the dependency result will\n                be `None`.\n\n                This is useful when you want to have optional authentication.\n\n                It is also useful when you want to have authentication that can be\n                provided in one of multiple optional ways (for example, with OAuth2\n                or in a cookie).\n                \"\"\"\n            ),\n        ] = True,\n        refreshUrl: Annotated[\n            Optional[str],\n            Doc(\n                \"\"\"\n                The URL to refresh the token and obtain a new one.\n                \"\"\"\n            ),\n        ] = None,\n    ):\n        if not scopes:\n            scopes = {}\n        flows = OAuthFlowsModel(\n            password=cast(\n                Any,\n                {\n                    \"tokenUrl\": tokenUrl,\n                    \"refreshUrl\": refreshUrl,\n                    \"scopes\": scopes,\n                },\n            )\n", "start_line": 451, "end_line": 500, "total_lines": 666, "is_truncated": false}
15run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2Admin')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2User')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/']['get']['security'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2Admin\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\"\n },\n
full
{"status": "ok", "stdout": "{\n  \"OAuth2Admin\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  },\n  \"OAuth2User\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"user\": \"User scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n[\n  {\n    \"OAuth2Admin\": []\n  },\n  {\n    \"OAuth2User\": []\n  }\n]\n", "exit_code": 0}
16run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\n# Same scheme_name, different scopes\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/']['get']['security'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"user\": \"User scope\"\n },\n \"token
full
{"status": "ok", "stdout": "{\n  \"OAuth2\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"user\": \"User scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n[\n  {\n    \"OAuth2\": []\n  },\n  {\n    \"OAuth2\": []\n  }\n]\n", "exit_code": 0}
17run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends, Security\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\noauth2_scheme = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope', 'user': 'User scope'})\n\n@app.get('/')\nasync def root(token: str = Security(oauth2_scheme, scopes=['admin'])):\n    return {'message': 'Hello World'}\n\n@app.get('/user')\nasync def user(token: str = Security(oauth2_scheme, scopes=['user'])):\n    return {'message': 'Hello User'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/']['get']['security'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/user']['get']['security'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2PasswordBearer\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\
full
{"status": "ok", "stdout": "{\n  \"OAuth2PasswordBearer\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\",\n          \"user\": \"User scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n[\n  {\n    \"OAuth2PasswordBearer\": [\n      \"admin\"\n    ]\n  }\n]\n[\n  {\n    \"OAuth2PasswordBearer\": [\n      \"user\"\n    ]\n  }\n]\n", "exit_code": 0}
18read_file
{
 "end_line": 100,
 "filepath": "fastapi/openapi/utils.py",
 "start_line": 70
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": " \"2XX\": \"Success\",\n \"3XX\": \"Redirection\",\n \"4XX\": \"Client Error\",\n \"5XX\":
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "content": "    \"2XX\": \"Success\",\n    \"3XX\": \"Redirection\",\n    \"4XX\": \"Client Error\",\n    \"5XX\": \"Server Error\",\n    \"DEFAULT\": \"Default Response\",\n}\n\n\ndef get_openapi_security_definitions(\n    flat_dependant: Dependant,\n) -> Tuple[Dict[str, Any], List[Dict[str, Any]]]:\n    security_definitions = {}\n    operation_security = []\n    for security_requirement in flat_dependant.security_requirements:\n        security_definition = jsonable_encoder(\n            security_requirement.security_scheme.model,\n            by_alias=True,\n            exclude_none=True,\n        )\n        security_name = security_requirement.security_scheme.scheme_name\n        security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})\n    return security_definitions, operation_security\n\n\ndef _get_openapi_operation_parameters(\n    *,\n    dependant: Dependant,\n    model_name_map: ModelNameMap,\n    field_mapping: Dict[\n        Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n", "start_line": 70, "end_line": 100, "total_lines": 558, "is_truncated": false}
19edit_file
{
 "filepath": "fastapi/openapi/utils.py",
 "new_string": "        security_name = security_requirement.security_scheme.scheme_name\n        if security_name not in security_definitions:\n            security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})",
 "old_string": "        security_name = security_requirement.security_scheme.scheme_name\n        security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})"
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/openapi/utils.py\n+++ b/fastapi/openapi/u
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/openapi/utils.py\n+++ b/fastapi/openapi/utils.py\n@@ -87,7 +87,8 @@\n             exclude_none=True,\n         )\n         security_name = security_requirement.security_scheme.scheme_name\n-        security_definitions[security_name] = security_definition\n+        if security_name not in security_definitions:\n+            security_definitions[security_name] = security_definition\n         operation_security.append({security_name: security_requirement.scopes})\n     return security_definitions, operation_security\n \n", "is_truncated": false}
20run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\n# Same scheme_name, different scopes\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\nprint(json.dumps(openapi_schema['paths']['/']['get']['security'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\"\n },\n \"tok
full
{"status": "ok", "stdout": "{\n  \"OAuth2\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n[\n  {\n    \"OAuth2\": []\n  },\n  {\n    \"OAuth2\": []\n  }\n]\n", "exit_code": 0}
21run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\n# Same scheme_name, different scopes\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\n# We expect the FIRST one to be preserved now.\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\"\n },\n \"tok
full
{"status": "ok", "stdout": "{\n  \"OAuth2\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n", "exit_code": 0}
22run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\n# Same scheme_name, different scopes\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\n# The problem is that if we have the same scheme_name but different scopes, \n# they should probably be merged if they are the same scheme, or kept separate if they are different.\n# But in OAuth2, the scopes are part of the flow definition.\n# If the user uses the same scheme_name, they are telling FastAPI it's the same scheme.\n# If they have different scopes in the flow, it's a conflict.\n# The issue description says 'deduplicate security schemes with different scopes'.\n# This might mean that if the scopes are different, they should be treated as different schemes, \n# OR that the scopes should be merged.\n\""
}
{"status": "ok", "stdout": "", "exit_code": 0}
full
{"status": "ok", "stdout": "", "exit_code": 0}
23run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\"\n },\n \"tok
full
{"status": "ok", "stdout": "{\n  \"OAuth2\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n", "exit_code": 0}
24edit_file
{
 "filepath": "fastapi/openapi/utils.py",
 "new_string": "        security_name = security_requirement.security_scheme.scheme_name\n        if security_name in security_definitions:\n            # If it's an OAuth2 scheme, we should merge the scopes\n            security_definition_existing = security_definitions[security_name]\n            if (\n                security_definition_existing.get(\"type\") == \"oauth2\"\n                and security_definition.get(\"type\") == \"oauth2\"\n            ):\n                flows_existing = security_definition_existing.get(\"flows\", {})\n                flows_new = security_definition.get(\"flows\", {})\n                for flow_name, flow_details in flows_new.items():\n                    if flow_name in flows_existing:\n                        scopes_existing = flows_existing[flow_name].get(\"scopes\", {})\n                        scopes_new = flow_details.get(\"scopes\", {})\n                        flows_existing[flow_name][\"scopes\"] = {\n                            **scopes_existing,\n                            **scopes_new,\n                        }\n                    else:\n                        flows_existing[flow_name] = flow_details\n            else:\n                # For non-OAuth2 schemes, we just keep the first one\n                pass\n        else:\n            security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})",
 "old_string": "        security_name = security_requirement.security_scheme.scheme_name\n        if security_name not in security_definitions:\n            security_definitions[security_name] = security_definition\n        operation_security.append({security_name: security_requirement.scopes})"
}
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/openapi/utils.py\n+++ b/fastapi/openapi/u
full
{"status": "ok", "filepath": "fastapi/openapi/utils.py", "occurrences": 1, "strategy": "exact", "diff": "--- a/fastapi/openapi/utils.py\n+++ b/fastapi/openapi/utils.py\n@@ -87,7 +87,29 @@\n             exclude_none=True,\n         )\n         security_name = security_requirement.security_scheme.scheme_name\n-        if security_name not in security_definitions:\n+        if security_name in security_definitions:\n+            # If it's an OAuth2 scheme, we should merge the scopes\n+            security_definition_existing = security_definitions[security_name]\n+            if (\n+                security_definition_existing.get(\"type\") == \"oauth2\"\n+                and security_definition.get(\"type\") == \"oauth2\"\n+            ):\n+                flows_existing = security_definition_existing.get(\"flows\", {})\n+                flows_new = security_definition.get(\"flows\", {})\n+                for flow_name, flow_details in flows_new.items():\n+                    if flow_name in flows_existing:\n+                        scopes_existing = flows_existing[flow_name].get(\"scopes\", {})\n+                        scopes_new = flow_details.get(\"scopes\", {})\n+                        flows_existing[flow_name][\"scopes\"] = {\n+                            **scopes_existing,\n+                            **scopes_new,\n+                        }\n+                    else:\n+                        flows_existing[flow_name] = flow_details\n+            else:\n+                # For non-OAuth2 schemes, we just keep the first one\n+                pass\n+        else:\n             security_definitions[security_name] = security_definition\n         operation_security.append({security_name: security_requirement.scopes})\n     return security_definitions, operation_security\n", "is_truncated": false}
25run_command
{
 "command": "python3 -c \"\nfrom fastapi import FastAPI, Depends\nfrom fastapi.security import OAuth2PasswordBearer\n\napp = FastAPI()\n# Same scheme_name, different scopes\noauth2_scheme_1 = OAuth2PasswordBearer(tokenUrl='token', scopes={'admin': 'Admin scope'}, scheme_name='OAuth2')\noauth2_scheme_2 = OAuth2PasswordBearer(tokenUrl='token', scopes={'user': 'User scope'}, scheme_name='OAuth2')\n\n@app.get('/')\nasync def root(token1: str = Depends(oauth2_scheme_1), token2: str = Depends(oauth2_scheme_2)):\n    return {'message': 'Hello World'}\n\nimport json\nopenapi_schema = app.openapi()\nprint(json.dumps(openapi_schema['components']['securitySchemes'], indent=2))\n\""
}
{"status": "ok", "stdout": "{\n \"OAuth2\": {\n \"type\": \"oauth2\",\n \"flows\": {\n \"password\": {\n \"scopes\": {\n \"admin\": \"Admin scope\",\n \"user\":
full
{"status": "ok", "stdout": "{\n  \"OAuth2\": {\n    \"type\": \"oauth2\",\n    \"flows\": {\n      \"password\": {\n        \"scopes\": {\n          \"admin\": \"Admin scope\",\n          \"user\": \"User scope\"\n        },\n        \"tokenUrl\": \"token\"\n      }\n    }\n  }\n}\n", "exit_code": 0}
26submit_patch
[]
{"status": "ok", "patch_size": 1799, "files_changed": 1}
full
{"status": "ok", "patch_size": 1799, "files_changed": 1}

Patch

diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py
index dbc93d28..2037cae3 100644
--- a/fastapi/openapi/utils.py
+++ b/fastapi/openapi/utils.py
@@ -87,7 +87,30 @@ def get_openapi_security_definitions(
             exclude_none=True,
         )
         security_name = security_requirement.security_scheme.scheme_name
-        security_definitions[security_name] = security_definition
+        if security_name in security_definitions:
+            # If it's an OAuth2 scheme, we should merge the scopes
+            security_definition_existing = security_definitions[security_name]
+            if (
+                security_definition_existing.get("type") == "oauth2"
+                and security_definition.get("type") == "oauth2"
+            ):
+                flows_existing = security_definition_existing.get("flows", {})
+                flows_new = security_definition.get("flows", {})
+                for flow_name, flow_details in flows_new.items():
+                    if flow_name in flows_existing:
+                        scopes_existing = flows_existing[flow_name].get("scopes", {})
+                        scopes_new = flow_details.get("scopes", {})
+                        flows_existing[flow_name]["scopes"] = {
+                            **scopes_existing,
+                            **scopes_new,
+                        }
+                    else:
+                        flows_existing[flow_name] = flow_details
+            else:
+                # For non-OAuth2 schemes, we just keep the first one
+                pass
+        else:
+            security_definitions[security_name] = security_definition
         operation_security.append({security_name: security_requirement.scopes})
     return security_definitions, operation_security
 

Test output

show
      โ”‚
โ”‚ {"OAuth2AuthorizationCodeBearer": ["read", "write"]}],                       โ”‚
โ”‚                      },                                                      โ”‚
โ”‚                  },                                                          โ”‚
โ”‚              },                                                              โ”‚
โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
These changes are not applied.
Use --inline-snapshot=fix to apply them, or use the interactive mode with 
--inline-snapshot=review

โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ Problems โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
inline-snapshot is not able to format your code.
This issue can be solved by:
 * installing inline-snapshot[black] which gives you the same formatting like in
older versions
 * adding a `format-command` to your pyproject.toml (see 
https://15r10nk.github.io/inline-snapshot/latest/configuration/#format-command 
for more information).



==================================== ERRORS ====================================
___________________ ERROR at teardown of test_openapi_schema ___________________
some snapshots in this test have incorrect values.
If you just created this value with --inline-snapshot=create, the value is now created and you can ignore this message.
=================================== FAILURES ===================================
_____________________________ test_openapi_schema ______________________________

    def test_openapi_schema():
        response = client.get("/openapi.json")
        assert response.status_code == 200, response.text
>       assert response.json() == snapshot(
            {
                "openapi": "3.1.0",
                "info": {"title": "FastAPI", "version": "0.1.0"},
                "paths": {
                    "/": {
                        "get": {
                            "summary": "Root",
                            "operationId": "root__get",
                            "responses": {
                                "200": {
                                    "description": "Successful Response",
                                    "content": {"application/json": {"schema": {}}},
                                }
                            },
                            "security": [{"OAuth2AuthorizationCodeBearer": []}],
                        }
                    },
                    "/items/": {
                        "get": {
                            "summary": "Read Items",
                            "operationId": "read_items_items__get",
                            "responses": {
                                "200": {
                                    "description": "Successful Response",
                                    "content": {"application/json": {"schema": {}}},
                                }
                            },
                            "security": [
                                {"OAuth2AuthorizationCodeBearer": ["read"]},
                            ],
                        },
                        "post": {
                            "summary": "Create Item",
                            "operationId": "create_item_items__post",
                            "responses": {
                                "200": {
                                    "description": "Successful Response",
                                    "content": {"application/json": {"schema": {}}},
                                }
                            },
                            "security": [
                                {"OAuth2AuthorizationCodeBearer": ["read", "write"]},
                            ],
                        },
                    },
                },
                "components": {
                    "securitySchemes": {
                        "OAuth2AuthorizationCodeBearer": {
                            "type": "oauth2",
                            "flows": {
                                "authorizationCode": {
                                    "scopes": {
                                        "read": "Read access",
                                        "write": "Write access",
                                    },
                                    "authorizationUrl": "authorize",
                                    "tokenUrl": "token",
                                }
                            },
                        }
                    }
                },
            }
        )
E       AssertionError: assert {'openapi': '... 'token'}}}}}} == {'openapi': '... 'token'}}}}}}
E         
E         Omitting 3 identical items, use -vv to show
E         Differing items:
E         {'paths': {'/': {'get': {'summary': 'Root', 'operationId': 'root__get', 'responses': {'200': {'description': 'Successf...2AuthorizationCodeBearer': []}, {'OAuth2AuthorizationCodeBearer': [...]}, {'OAuth2AuthorizationCodeBearer': [...]}]}}}} != {'paths': {'/': {'get': {'summary': 'Root', 'operationId': 'root__get', 'responses': {'200': {'description': 'Successf...: {'description': 'Successful Response', 'content': {...}}}, 'security': [{'OAuth2AuthorizationCodeBearer': [...]}]}}}}
E         Use -v to get more diff

tests/test_security_oauth2_authorization_code_bearer_scopes_openapi.py:66: AssertionError
=============================== warnings summary ===============================
../../../../../../kaggle/tmp/envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45
  /kaggle/tmp/envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.
    _PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 2 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 failed, 3 passed, 1 warning, 1 error in 0.82s