← pod_r5_v1h

fastapi_15589

failed NO_PATCH NO_PATCH UNSUBMITTED empty_patch(budget) · 25 tool calls · 301 s · fastapi/fastapi

Task input

♻️ Do not accept underscore headers when using `convert_underscores=True` (the default)

## Pull Request

<!--
Please start with a GitHub Discussion.

Once a team member asks you to open a PR, create it and link the discussion here.

Obvious typo fixes can be made in a PR without starting a discussion.
-->

Discussion: <!-- Link to the GitHub Discussion -->

## Description

♻️ Do not accept underscore headers when using `convert_underscores=True` (the default)

This means it would only accept header names separated with hyphens by default, and to accept header names separated with underscores, an app would need to explicitly set `convert_underscores=False`.

<!-- Write the description of your PR here -->

## AI Disclaimer

<!-- If using AI, write here the prompt and model used -->

<details>
<summary>AI transcript</summary>

<!-- Paste here the entire AI transcript -->

</details>

## Checklist

- [ ] This PR is an obvious typo fix, or it links to a GitHub Discussion for the proposed code change.
- [ ] I added tests for the change.
- [ ] The new or updated tests fail on the main branch and pass on this PR.
- [ ] Coverage stays at 100%.
- [ ] The documentation explains the change if needed.

Tool calls (25)

#ToolArgumentsResult
1run_command
{
 "command": "grep -rn \"convert_underscores\" ."
}
{"status": "ok", "stdout": "./docs/zh-hant/docs/tutorial/header-param-models.md:66:\u5728\u5c07 `convert_underscores` \u8a2d\u70ba `False` \u4e4b\u524d\uff0c\u8
full
{"status": "ok", "stdout": "./docs/zh-hant/docs/tutorial/header-param-models.md:66:\u5728\u5c07 `convert_underscores` \u8a2d\u70ba `False` \u4e4b\u524d\uff0c\u8acb\u6ce8\u610f\u6709\u4e9b HTTP \u4ee3\u7406\u8207\u4f3a\u670d\u5668\u4e0d\u5141\u8a31\u542b\u6709\u5e95\u7dda\u7684\u6a19\u982d\u3002\n./docs/zh-hant/docs/tutorial/header-params.md:47:\u82e5\u56e0\u67d0\u4e9b\u539f\u56e0\u9700\u8981\u505c\u7528\u5e95\u7dda\u81ea\u52d5\u8f49\u9023\u5b57\u865f\u7684\u884c\u70ba\uff0c\u5c07 `Header` \u7684 `convert_underscores` \u53c3\u6578\u8a2d\u70ba `False`\uff1a\n./docs/zh-hant/docs/tutorial/header-params.md:53:\u5728\u5c07 `convert_underscores` \u8a2d\u70ba `False` \u4e4b\u524d\uff0c\u8acb\u6ce8\u610f\u6709\u4e9b HTTP \u4ee3\u7406\u8207\u4f3a\u670d\u5668\u4e0d\u5141\u8a31\u4f7f\u7528\u5e36\u6709\u5e95\u7dda\u7684\u6a19\u982d\u3002\n./docs/ja/docs/tutorial/header-param-models.md:66:`convert_underscores` \u3092 `False` \u306b\u8a2d\u5b9a\u3059\u308b\u524d\u306b\u3001\u30a2\u30f3\u30c0\u30fc\u30b9\u30b3\u30a2\u3092\u542b\u3080\u30d8\u30c3\u30c0\u30fc\u306e\u4f7f\u7528\u3092\u7981\u6b62\u3057\u3066\u3044\u308b HTTP \u30d7\u30ed\u30ad\u30b7\u3084\u30b5\u30fc\u30d0\u30fc\u304c\u3042\u308b\u3053\u3068\u306b\u7559\u610f\u3057\u3066\u304f\u3060\u3055\u3044\u3002\n./docs/ja/docs/tutorial/header-params.md:47:\u3082\u3057\u306a\u3093\u3089\u304b\u306e\u7406\u7531\u3067\u30a2\u30f3\u30c0\u30fc\u30b9\u30b3\u30a2\u304b\u3089\u30cf\u30a4\u30d5\u30f3\u3078\u306e\u81ea\u52d5\u5909\u63db\u3092\u7121\u52b9\u306b\u3059\u308b\u5fc5\u8981\u304c\u3042\u308b\u5834\u5408\u306f\u3001`Header`\u306e\u30d1\u30e9\u30e1\u30fc\u30bf`convert_underscores`\u3092`False`\u306b\u8a2d\u5b9a\u3057\u3066\u304f\u3060\u3055\u3044:\n./docs/ja/docs/tutorial/header-params.md:53:`convert_underscores`\u3092`False`\u306b\u8a2d\u5b9a\u3059\u308b\u524d\u306b\u3001HTTP\u30d7\u30ed\u30ad\u30b7\u3084\u30b5\u30fc\u30d0\u306e\u4e2d\u306b\u306f\u30a2\u30f3\u30c0\u30fc\u30b9\u30b3\u30a2\u3092\u542b\u3080\u30d8\u30c3\u30c0\u30fc\u
2run_command
{
 "command": "grep -rn \"convert_underscores\" fastapi | head -20"
}
{"status": "ok", "stdout": "fastapi/params.py:316: convert_underscores: bool = True,\nfastapi/params.py:352: self.convert_underscores = convert_underscores\nfas
full
{"status": "ok", "stdout": "fastapi/params.py:316:        convert_underscores: bool = True,\nfastapi/params.py:352:        self.convert_underscores = convert_underscores\nfastapi/dependencies/utils.py:536:        if not field_info.alias and getattr(field_info, \"convert_underscores\", None):\nfastapi/dependencies/utils.py:797:    default_convert_underscores = True\nfastapi/dependencies/utils.py:803:        # If headers are in a Pydantic model, the way to disable convert_underscores\nfastapi/dependencies/utils.py:804:        # would be with Header(convert_underscores=False) at the Pydantic model level\nfastapi/dependencies/utils.py:805:        default_convert_underscores = getattr(\nfastapi/dependencies/utils.py:806:            first_field.field_info, \"convert_underscores\", True\nfastapi/dependencies/utils.py:817:            # doesn't have a FieldInfo of type Header with the default convert_underscores=True\nfastapi/dependencies/utils.py:818:            convert_underscores = getattr(\nfastapi/dependencies/utils.py:819:                field.field_info, \"convert_underscores\", default_convert_underscores\nfastapi/dependencies/utils.py:821:            if convert_underscores:\nfastapi/openapi/utils.py:128:    default_convert_underscores = True\nfastapi/openapi/utils.py:132:            default_convert_underscores = getattr(\nfastapi/openapi/utils.py:133:                first_field.field_info, \"convert_underscores\", True\nfastapi/openapi/utils.py:148:            convert_underscores = getattr(\nfastapi/openapi/utils.py:150:                \"convert_underscores\",\nfastapi/openapi/utils.py:151:                default_convert_underscores,\nfastapi/openapi/utils.py:156:                and convert_underscores\nfastapi/param_functions.py:761:    convert_underscores: Annotated[\n", "stderr": "", "exit_code": 0}
3run_command
{
 "command": "sed -n '520,550p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " # It's a field_info, not a dependency\n if field_info is not None:\n # Handle field_info.in_\n if is_path_param:\n assert isinstanc
full
{"status": "ok", "stdout": "    # It's a field_info, not a dependency\n    if field_info is not None:\n        # Handle field_info.in_\n        if is_path_param:\n            assert isinstance(field_info, params.Path), (\n                f\"Cannot use `{field_info.__class__.__name__}` for path param\"\n                f\" {param_name!r}\"\n            )\n        elif (\n            isinstance(field_info, params.Param)\n            and getattr(field_info, \"in_\", None) is None\n        ):\n            field_info.in_ = params.ParamTypes.query\n        use_annotation_from_field_info = use_annotation\n        if isinstance(field_info, params.Form):\n            ensure_multipart_is_installed()\n        if not field_info.alias and getattr(field_info, \"convert_underscores\", None):\n            alias = param_name.replace(\"_\", \"-\")\n        else:\n            alias = field_info.alias or param_name\n        field_info.alias = alias\n        field = create_model_field(\n            name=param_name,\n            type_=use_annotation_from_field_info,\n            default=field_info.default,\n            alias=alias,\n            field_info=field_info,\n        )\n        if is_path_param:\n            assert is_scalar_field(field=field), (\n                \"Path params must be of one of the supported types\"\n", "stderr": "", "exit_code": 0}
4run_command
{
 "command": "sed -n '780,830p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " return deepcopy(field.default)\n return value\n\n\ndef request_params_to_args(\n fields: Sequence[ModelField],\n received_params: M
full
{"status": "ok", "stdout": "            return deepcopy(field.default)\n    return value\n\n\ndef request_params_to_args(\n    fields: Sequence[ModelField],\n    received_params: Mapping[str, Any] | QueryParams | Headers,\n) -> tuple[dict[str, Any], list[Any]]:\n    values: dict[str, Any] = {}\n    errors: list[dict[str, Any]] = []\n\n    if not fields:\n        return values, errors\n\n    first_field = fields[0]\n    fields_to_extract = fields\n    single_not_embedded_field = False\n    default_convert_underscores = True\n    if len(fields) == 1 and lenient_issubclass(\n        first_field.field_info.annotation, BaseModel\n    ):\n        fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n        single_not_embedded_field = True\n        # If headers are in a Pydantic model, the way to disable convert_underscores\n        # would be with Header(convert_underscores=False) at the Pydantic model level\n        default_convert_underscores = getattr(\n            first_field.field_info, \"convert_underscores\", True\n        )\n\n    params_to_process: dict[str, Any] = {}\n\n    processed_keys = set()\n\n    for field in fields_to_extract:\n        alias = None\n        if isinstance(received_params, Headers):\n            # Handle fields extracted from a Pydantic Model for a header, each field\n            # doesn't have a FieldInfo of type Header with the default convert_underscores=True\n            convert_underscores = getattr(\n                field.field_info, \"convert_underscores\", default_convert_underscores\n            )\n            if convert_underscores:\n                alias = get_validation_alias(field)\n                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n        value = _get_multidict_value(field, received_params, alias=alias)\n        if value is not None:\n            params_to_process[get_validation_alias(field)] = value\n        processed_keys.add(alias or get_validation_
5run_command
{
 "command": "cat > /tmp/check_headers.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n@app.get(\"/headers\")\nasync def read_headers(x_token: str = Header()):\n    return {\"x_token\": x_token}\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: BaseModel = Header()):\n    # Wait, Header() in Depends is different. \n    # Let's use the model as a dependency.\n    pass\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header()\n\n@app.get(\"/headers_model_fixed\")\nasync def read_headers_model_fixed(headers: HeaderModel = Depends()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # With convert_underscores=True (default), Header(alias=\"x_token\") should be looked up as \"x-token\"\n    # If we send \"x_token\", it should NOT be accepted as \"x-token\" if the logic is corrected.\n    # Wait, currently it might be accepted? \n    # Let's see what happens now.\n    \n    # Request with hyphen\n    resp = client.get(\"/headers\", headers={\"x-token\": \"foo\"})\n    print(f\"Hyphen header: {resp.json()}\")\n    \n    # Request with underscore\n    resp = client.get(\"/headers\", headers={\"x_token\": \"bar\"})\n    print(f\"Underscore header: {resp.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_headers.py\n"
}
{"status": "ok", "stdout": "Hyphen header: {'x_token': 'foo'}\nUnderscore header: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field re
full
{"status": "ok", "stdout": "Hyphen header: {'x_token': 'foo'}\nUnderscore header: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\n", "stderr": "", "exit_code": 0}
6run_command
{
 "command": "cat > /tmp/check_headers_2.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n@app.get(\"/headers\")\nasync def read_headers(x_token: str = Header()):\n    return {\"x_token\": x_token}\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header()\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: HeaderModel = Depends()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # Test simple Header()\n    resp_hyphen = client.get(\"/headers\", headers={\"x-token\": \"foo\"})\n    print(f\"Simple Header Hyphen: {resp_hyphen.json()}\")\n    \n    resp_underscore = client.get(\"/headers\", headers={\"x_token\": \"bar\"})\n    print(f\"Simple Header Underscore: {resp_underscore.json()}\")\n    \n    # Test Model Header\n    resp_model_hyphen = client.get(\"/headers_model\", headers={\"x-token\": \"foo\"})\n    print(f\"Model Header Hyphen: {resp_model_hyphen.json()}\")\n    \n    resp_model_underscore = client.get(\"/headers_model\", headers={\"x_token\": \"bar\"})\n    print(f\"Model Header Underscore: {resp_model_underscore.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_headers_2.py\n"
}
{"status": "ok", "stdout": "Simple Header Hyphen: {'x_token': 'foo'}\nSimple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'm
full
{"status": "ok", "stdout": "Simple Header Hyphen: {'x_token': 'foo'}\nSimple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nModel Header Hyphen: {'detail': [{'type': 'missing', 'loc': ['query', 'x_token'], 'msg': 'Field required', 'input': None}]}\nModel Header Underscore: {'detail': [{'type': 'missing', 'loc': ['query', 'x_token'], 'msg': 'Field required', 'input': None}]}\n", "stderr": "", "exit_code": 0}
7run_command
{
 "command": "cat > /tmp/check_headers_3.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n@app.get(\"/headers\")\nasync def read_headers(x_token: str = Header()):\n    return {\"x_token\": x_token}\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header()\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: HeaderModel = Header()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # Test simple Header()\n    resp_hyphen = client.get(\"/headers\", headers={\"x-token\": \"foo\"})\n    print(f\"Simple Header Hyphen: {resp_hyphen.json()}\")\n    \n    resp_underscore = client.get(\"/headers\", headers={\"x_token\": \"bar\"})\n    print(f\"Simple Header Underscore: {resp_underscore.json()}\")\n    \n    # Test Model Header\n    resp_model_hyphen = client.get(\"/headers_model\", headers={\"x-token\": \"foo\"})\n    print(f\"Model Header Hyphen: {resp_model_hyphen.json()}\")\n    \n    resp_model_underscore = client.get(\"/headers_model\", headers={\"x_token\": \"bar\"})\n    print(f\"Model Header Underscore: {resp_model_underscore.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_headers_3.py\n"
}
{"status": "ok", "stdout": "Simple Header Hyphen: {'x_token': 'foo'}\nSimple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'm
full
{"status": "ok", "stdout": "Simple Header Hyphen: {'x_token': 'foo'}\nSimple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nModel Header Hyphen: {'x_token': 'foo'}\nModel Header Underscore: {'x_token': 'bar'}\n", "stderr": "", "exit_code": 0}
8run_command
{
 "command": "sed -n '800,825p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " ):\n fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n single_not_embedded_field = True\n # If heade
full
{"status": "ok", "stdout": "    ):\n        fields_to_extract = get_cached_model_fields(first_field.field_info.annotation)\n        single_not_embedded_field = True\n        # If headers are in a Pydantic model, the way to disable convert_underscores\n        # would be with Header(convert_underscores=False) at the Pydantic model level\n        default_convert_underscores = getattr(\n            first_field.field_info, \"convert_underscores\", True\n        )\n\n    params_to_process: dict[str, Any] = {}\n\n    processed_keys = set()\n\n    for field in fields_to_extract:\n        alias = None\n        if isinstance(received_params, Headers):\n            # Handle fields extracted from a Pydantic Model for a header, each field\n            # doesn't have a FieldInfo of type Header with the default convert_underscores=True\n            convert_underscores = getattr(\n                field.field_info, \"convert_underscores\", default_convert_underscores\n            )\n            if convert_underscores:\n                alias = get_validation_alias(field)\n                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n        value = _get_multidict_value(field, received_params, alias=alias)\n", "stderr": "", "exit_code": 0}
9run_command
{
 "command": "python3 -c \"from fastapi.dependencies.utils import _get_multidict_value; print(_get_multidict_value.__code__.co_varnames)\""
}
{"status": "ok", "stdout": "('field', 'values', 'alias', 'value')\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "('field', 'values', 'alias', 'value')\n", "stderr": "", "exit_code": 0}
10run_command
{
 "command": "grep -n \"def _get_multidict_value\" fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": "753:def _get_multidict_value(\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "753:def _get_multidict_value(\n", "stderr": "", "exit_code": 0}
11run_command
{
 "command": "sed -n '753,775p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": "def _get_multidict_value(\n field: ModelField, values: Mapping[str, Any], alias: str | None = None\n) -> Any:\n alias = alias or get
full
{"status": "ok", "stdout": "def _get_multidict_value(\n    field: ModelField, values: Mapping[str, Any], alias: str | None = None\n) -> Any:\n    alias = alias or get_validation_alias(field)\n    if (\n        (not _is_json_field(field))\n        and field_annotation_is_sequence(field.field_info.annotation)\n        and isinstance(values, (ImmutableMultiDict, Headers))\n    ):\n        value = values.getlist(alias)\n    else:\n        value = values.get(alias, None)\n    if (\n        value is None\n        or (\n            isinstance(field.field_info, params.Form)\n            and isinstance(value, str)  # For type checks\n            and value == \"\"\n        )\n        or (\n            field_annotation_is_sequence(field.field_info.annotation)\n            and len(value) == 0\n        )\n", "stderr": "", "exit_code": 0}
12run_command
{
 "command": "sed -n '776,800p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " ):\n if field.field_info.is_required():\n return\n else:\n return deepcopy(field.default)\n return value\n\n\ndef request_params_to
full
{"status": "ok", "stdout": "    ):\n        if field.field_info.is_required():\n            return\n        else:\n            return deepcopy(field.default)\n    return value\n\n\ndef request_params_to_args(\n    fields: Sequence[ModelField],\n    received_params: Mapping[str, Any] | QueryParams | Headers,\n) -> tuple[dict[str, Any], list[Any]]:\n    values: dict[str, Any] = {}\n    errors: list[dict[str, Any]] = []\n\n    if not fields:\n        return values, errors\n\n    first_field = fields[0]\n    fields_to_extract = fields\n    single_not_embedded_field = False\n    default_convert_underscores = True\n    if len(fields) == 1 and lenient_issubclass(\n        first_field.field_info.annotation, BaseModel\n    ):\n", "stderr": "", "exit_code": 0}
13run_command
{
 "command": "cat > /tmp/check_headers_4.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header(convert_underscores=False)\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: HeaderModel = Header()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # Test Model Header with convert_underscores=False\n    resp_hyphen = client.get(\"/headers_model\", headers={\"x-token\": \"foo\"})\n    print(f\"Model Header Hyphen (False): {resp_hyphen.json()}\")\n    \n    resp_underscore = client.get(\"/headers_model\", headers={\"x_token\": \"bar\"})\n    print(f\"Model Header Underscore (False): {resp_underscore.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_headers_4.py\n"
}
{"status": "ok", "stdout": "Model Header Hyphen (False): {'detail': [{'type': 'missing', 'loc': ['header', 'x_token'], 'msg': 'Field required', 'input': {'host'
full
{"status": "ok", "stdout": "Model Header Hyphen (False): {'detail': [{'type': 'missing', 'loc': ['header', 'x_token'], 'msg': 'Field required', 'input': {'host': 'testserver', 'accept': '*/*', 'accept-encoding': 'gzip, deflate', 'connection': 'keep-alive', 'user-agent': 'testclient', 'x-token': 'foo'}}]}\nModel Header Underscore (False): {'x_token': 'bar'}\n", "stderr": "", "exit_code": 0}
14run_command
{
 "command": "python3 -c \"from fastapi.dependencies.utils import _get_multidict_value; print(_get_multidict_value)\""
}
{"status": "ok", "stdout": "<function _get_multidict_value at 0x106450680>\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "<function _get_multidict_value at 0x106450680>\n", "stderr": "", "exit_code": 0}
15run_command
{
 "command": "cat > /tmp/reproduce_issue.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header()\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: HeaderModel = Header()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # When convert_underscores=True (default), it should NOT accept \"x_token\"\n    # but it currently does.\n    resp_underscore = client.get(\"/headers_model\", headers={\"x_token\": \"bar\"})\n    print(f\"Underscore header (convert_underscores=True): {resp_underscore.json()}\")\n    \n    # It should still accept \"x-token\"\n    resp_hyphen = client.get(\"/headers_model\", headers={\"x-token\": \"foo\"})\n    print(f\"Hyphen header (convert_underscores=True): {resp_hyphen.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/reproduce_issue.py\n"
}
{"status": "ok", "stdout": "Underscore header (convert_underscores=True): {'x_token': 'bar'}\nHyphen header (convert_underscores=True): {'x_token': 'foo'}\n", "
full
{"status": "ok", "stdout": "Underscore header (convert_underscores=True): {'x_token': 'bar'}\nHyphen header (convert_underscores=True): {'x_token': 'foo'}\n", "stderr": "", "exit_code": 0}
16run_command
{
 "command": "sed -n '810,822p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": "\n processed_keys = set()\n\n for field in fields_to_extract:\n alias = None\n if isinstance(received_params, Headers):\n # Handle f
full
{"status": "ok", "stdout": "\n    processed_keys = set()\n\n    for field in fields_to_extract:\n        alias = None\n        if isinstance(received_params, Headers):\n            # Handle fields extracted from a Pydantic Model for a header, each field\n            # doesn't have a FieldInfo of type Header with the default convert_underscores=True\n            convert_underscores = getattr(\n                field.field_info, \"convert_underscores\", default_convert_underscores\n            )\n            if convert_underscores:\n                alias = get_validation_alias(field)\n", "stderr": "", "exit_code": 0}
17run_command
{
 "command": "sed -n '823,828p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " if alias == field.name:\n alias = alias.replace(\"_\", \"-\")\n value = _get_multidict_value(field, received_params, alias=alias)\n
full
{"status": "ok", "stdout": "                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n        value = _get_multidict_value(field, received_params, alias=alias)\n        if value is not None:\n            params_to_process[get_validation_alias(field)] = value\n        processed_keys.add(alias or get_validation_alias(field))\n", "stderr": "", "exit_code": 0}
18run_command
{
 "command": "sed -n '753,770p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": "def _get_multidict_value(\n field: ModelField, values: Mapping[str, Any], alias: str | None = None\n) -> Any:\n alias = alias or get
full
{"status": "ok", "stdout": "def _get_multidict_value(\n    field: ModelField, values: Mapping[str, Any], alias: str | None = None\n) -> Any:\n    alias = alias or get_validation_alias(field)\n    if (\n        (not _is_json_field(field))\n        and field_annotation_is_sequence(field.field_info.annotation)\n        and isinstance(values, (ImmutableMultiDict, Headers))\n    ):\n        value = values.getlist(alias)\n    else:\n        value = values.get(alias, None)\n    if (\n        value is None\n        or (\n            isinstance(field.field_info, params.Form)\n            and isinstance(value, str)  # For type checks\n            and value == \"\"\n", "stderr": "", "exit_code": 0}
19run_command
{
 "command": "python3 -c \"from fastapi.dependencies.utils import _get_multidict_value; print(_get_multidict_value)\""
}
{"status": "ok", "stdout": "<function _get_multidict_value at 0x1025a0680>\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "<function _get_multidict_value at 0x1025a0680>\n", "stderr": "", "exit_code": 0}
20run_command
{
 "command": "cat > /tmp/check_headers_5.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\n@app.get(\"/headers\")\nasync def read_headers(x_token: str = Header()):\n    return {\"x_token\": x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # With convert_underscores=True (default), it should NOT accept \"x_token\"\n    resp_underscore = client.get(\"/headers\", headers={\"x_token\": \"bar\"})\n    print(f\"Simple Header Underscore: {resp_underscore.json()}\")\n    \n    # It should still accept \"x-token\"\n    resp_hyphen = client.get(\"/headers\", headers={\"x-token\": \"foo\"})\n    print(f\"Simple Header Hyphen: {resp_hyphen.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_headers_5.py\n"
}
{"status": "ok", "stdout": "Simple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nS
full
{"status": "ok", "stdout": "Simple Header Underscore: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nSimple Header Hyphen: {'x_token': 'foo'}\n", "stderr": "", "exit_code": 0}
21run_command
{
 "command": "sed -n '530,545p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": " and getattr(field_info, \"in_\", None) is None\n ):\n field_info.in_ = params.ParamTypes.query\n use_annotation_from_field_info = u
full
{"status": "ok", "stdout": "            and getattr(field_info, \"in_\", None) is None\n        ):\n            field_info.in_ = params.ParamTypes.query\n        use_annotation_from_field_info = use_annotation\n        if isinstance(field_info, params.Form):\n            ensure_multipart_is_installed()\n        if not field_info.alias and getattr(field_info, \"convert_underscores\", None):\n            alias = param_name.replace(\"_\", \"-\")\n        else:\n            alias = field_info.alias or param_name\n        field_info.alias = alias\n        field = create_model_field(\n            name=param_name,\n            type_=use_annotation_from_field_info,\n            default=field_info.default,\n            alias=alias,\n", "stderr": "", "exit_code": 0}
22run_command
{
 "command": "cat > /tmp/check_model_header_v2.py <<'PY'\nfrom fastapi import FastAPI, Header, Depends\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\napp = FastAPI()\n\nclass HeaderModel(BaseModel):\n    x_token: str = Header()\n\n@app.get(\"/headers_model\")\nasync def read_headers_model(headers: HeaderModel = Header()):\n    return {\"x_token\": headers.x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # When convert_underscores=True (default), it should NOT accept \"x_token\"\n    resp_underscore = client.get(\"/headers_model\", headers={\"x_token\": \"bar\"})\n    print(f\"Underscore header: {resp_underscore.json()}\")\n    \n    # It should still accept \"x-token\"\n    resp_hyphen = client.get(\"/headers_model\", headers={\"x-token\": \"foo\"})\n    print(f\"Hyphen header: {resp_hyphen.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_model_header_v2.py\n"
}
{"status": "ok", "stdout": "Underscore header: {'x_token': 'bar'}\nHyphen header: {'x_token': 'foo'}\n", "stderr": "", "exit_code": 0}
full
{"status": "ok", "stdout": "Underscore header: {'x_token': 'bar'}\nHyphen header: {'x_token': 'foo'}\n", "stderr": "", "exit_code": 0}
23run_command
{
 "command": "sed -n '810,830p' fastapi/dependencies/utils.py"
}
{"status": "ok", "stdout": "\n processed_keys = set()\n\n for field in fields_to_extract:\n alias = None\n if isinstance(received_params, Headers):\n # Handle f
full
{"status": "ok", "stdout": "\n    processed_keys = set()\n\n    for field in fields_to_extract:\n        alias = None\n        if isinstance(received_params, Headers):\n            # Handle fields extracted from a Pydantic Model for a header, each field\n            # doesn't have a FieldInfo of type Header with the default convert_underscores=True\n            convert_underscores = getattr(\n                field.field_info, \"convert_underscores\", default_convert_underscores\n            )\n            if convert_underscores:\n                alias = get_validation_alias(field)\n                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n        value = _get_multidict_value(field, received_params, alias=alias)\n        if value is not None:\n            params_to_process[get_validation_alias(field)] = value\n        processed_keys.add(alias or get_validation_alias(field))\n\n    for key in received_params.keys():\n", "stderr": "", "exit_code": 0}
24run_command
{
 "command": "cd /workspace && python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/dependencies/utils.py\")\ns = p.read_text()\nold = \"\"\"            if convert_underscores:\n                alias = get_validation_alias(field)\n                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n        value = _get_multidict_value(field, received_params, alias=alias)\"\"\"\nnew = \"\"\"            if convert_underscores:\n                alias = get_validation_alias(field)\n                if alias == field.name:\n                    alias = alias.replace(\"_\", \"-\")\n                # If convert_underscores is True, do not allow the original underscore name\n                # to be used if it differs from the converted alias.\n                # However, the logic in _get_multidict_value uses `alias` to fetch the value.\n                # To explicitly forbid the underscore name, we can't just change the alias here\n                # because we NEED the converted alias to find the value.\n                # The issue is that _get_multidict_value probably handles the fallback or\n                # the received_params (Headers) allows underscore lookups.\n                pass\n        \n        # We need to ensure that if convert_underscores is True, we ONLY use the hyphenated alias.\n        # If we don't provide an alias to _get_multidict_value, it uses get_validation_alias(field).\n        # If we do provide one, it uses it.\n        \n        # Let's try this instead:\n        # if convert_underscores:\n        #     alias = get_validation_alias(field).replace(\"_\", \"-\") if get_validation_alias(field) == field.name else get_validation_alias(field)\n        # But wait, the current code already does that.\n        # The problem is likely that _get_multidict_value or the Header object handles the lookup\n        # too leniently.\n        \n        # Actually, looking at the current code:\n        # if convert_underscores:\n        #     alias = get_validation_alias(field)\n        #     if alias == field.name:\n        #         alias = alias.replace(\"_\", \"-\")\n        # value = _get_multidict_value(field, received_params, alias=alias)\n        \n        # If alias becomes \"x-token\", _get_multidict_value(..., alias=\"x-token\") is called.\n        # _get_multidict_value uses values.get(alias, None).\n        # For a Starlette Headers object, .get(\"x-token\") and .get(\"x_token\") might both work!\n        \n        # Let's check Starlette's Headers.\n        \n        # If we want to FORBID underscore headers when convert_underscores=True, \n        # we should check if the underscore version of the header was sent and raise an error,\n        # or just make sure we don't accept it. \n        # But Starlette's Headers object automatically normalizes.\n        \n        # Actually, if we want to be strict, we should check if the original name was used.\n        \n        # Wait, the requirement is: \"Do not accept underscore headers when using convert_underscores=True\".\n        # If the user sends \"x_token\", but the field is \"x_token\" and convert_underscores=True, \n        # the alias is \"x-token\". \n        # _get_multidict_value(..., alias=\"x-token\") is called.\n        # If Starlette's Headers.get(\"x-token\") returns the value of \"x_token\", then it's accepted.\n        \n        # To prevent this, we can't easily change Starlette. \n        # But we can check if \"x_token\" was sent and if so, we can decide to ignore it or raise an error.\n        # But that might be too much.\n        \n        # Maybe we just need to make sure that if convert_underscores is True, we only accept the converted alias.\n        # But Starlette's Header object is case-insensitive and often treats _ and - interchangeably.\n        \n        # Let's see if we can find a way to check the actual keys sent.\n        \n        # In request_params_to_args:\n        # for key in receiv
{"status": "error", "error_type": "CommandError", "error_message": " File \"<stdin>\", line 9\n new = \"\"\" if convert_underscores:\n ^\nSyntaxError: untermina
full
{"status": "error", "error_type": "CommandError", "error_message": "  File \"<stdin>\", line 9\n    new = \"\"\"            if convert_underscores:\n          ^\nSyntaxError: unterminated triple-quoted string literal (detected at line 169)\n", "details": {"stdout": "", "stderr": "  File \"<stdin>\", line 9\n    new = \"\"\"            if convert_underscores:\n          ^\nSyntaxError: unterminated triple-quoted string literal (detected at line 169)\n", "exit_code": 1}}
25run_command
{
 "command": "cat > /tmp/check_simple_header.py <<'PY'\nfrom fastapi import FastAPI, Header\nfrom fastapi.testclient import TestClient\n\napp = FastAPI()\n\n@app.get(\"/headers\")\nasync def read_headers(x_token: str = Header()):\n    return {\"x_token\": x_token}\n\nclient = TestClient(app)\n\ndef test_underscore_header():\n    # With convert_underscores=True (default), Header() should be looked up as \"x-token\"\n    # Let's see if it accepts \"x_token\"\n    resp_underscore = client.get(\"/headers\", headers={\"x_token\": \"bar\"})\n    print(f\"Underscore header: {resp_underscore.json()}\")\n    \n    # It should still accept \"x-token\"\n    resp_hyphen = client.get(\"/headers\", headers={\"x-token\": \"foo\"})\n    print(f\"Hyphen header: {resp_hyphen.json()}\")\n\nif __name__ == \"__main__\":\n    test_underscore_header()\nPY\npython3 /tmp/check_simple_header.py\n"
}
{"status": "ok", "stdout": "Underscore header: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nHyphen h
full
{"status": "ok", "stdout": "Underscore header: {'detail': [{'type': 'missing', 'loc': ['header', 'x-token'], 'msg': 'Field required', 'input': None}]}\nHyphen header: {'x_token': 'foo'}\n", "stderr": "", "exit_code": 0}