Skip to content

Commit 59e3920

Browse files
committed
api: Avoid programming errors due to nested Annotated types.
We want to reject ambiguous type annotations that set ApiParamConfig inside a Union. If a parameter is Optional and has a default of None, we prefer Annotated[Optional[T], ...] over Optional[Annotated[T, ...]]. This implements a check that detects Optional[Annotated[T, ...]] and raise an assertion error if ApiParamConfig is in the annotation. It also checks if the type annotation contains any ApiParamConfig objects that are ignored, which can happen if the Annotated type is nested inside another type like List, Union, etc. Note that because param: Annotated[Optional[T], ...] = None and param: Optional[Annotated[Optional[T], ...]] = None are equivalent in runtime prior to Python 3.11, there is no way for us to distinguish the two. So we cannot detect that in runtime. See also: python/cpython#90353
1 parent 9e38849 commit 59e3920

File tree

3 files changed

+121
-7
lines changed

3 files changed

+121
-7
lines changed

Diff for: tools/semgrep.yml

+23
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,26 @@ rules:
169169
message: 'A batched migration should not be atomic. Add "atomic = False" to the Migration class'
170170
languages: [python]
171171
severity: ERROR
172+
173+
- id: dont-nest-annotated-types-with-param-config
174+
patterns:
175+
- pattern-not: |
176+
def $F(..., invalid_param: typing.Optional[<... zerver.lib.typed_endpoint.ApiParamConfig(...) ...>], ...) -> ...:
177+
...
178+
- pattern-not: |
179+
def $F(..., $A: typing_extensions.Annotated[<... zerver.lib.typed_endpoint.ApiParamConfig(...) ...>], ...) -> ...:
180+
...
181+
- pattern-not: |
182+
def $F(..., $A: typing_extensions.Annotated[<... zerver.lib.typed_endpoint.ApiParamConfig(...) ...>] = ..., ...) -> ...:
183+
...
184+
- pattern-either:
185+
- pattern: |
186+
def $F(..., $A: $B[<... zerver.lib.typed_endpoint.ApiParamConfig(...) ...>], ...) -> ...:
187+
...
188+
- pattern: |
189+
def $F(..., $A: $B[<... zerver.lib.typed_endpoint.ApiParamConfig(...) ...>] = ..., ...) -> ...:
190+
...
191+
message: |
192+
Annotated types containing zerver.lib.typed_endpoint.ApiParamConfig should not be nested inside Optional. Use Annotated[Optional[...], zerver.lib.typed_endpoint.ApiParamConfig(...)] instead.
193+
languages: [python]
194+
severity: ERROR

Diff for: zerver/lib/typed_endpoint.py

+58-6
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,41 @@ def is_annotated(type_annotation: Type[object]) -> bool:
194194
return origin is Annotated
195195

196196

197+
def is_optional(type_annotation: Type[object]) -> bool:
198+
origin = get_origin(type_annotation)
199+
type_args = get_args(type_annotation)
200+
return origin is Union and type(None) in type_args and len(type_args) == 2
201+
202+
203+
API_PARAM_CONFIG_USAGE_HINT = f"""
204+
Detected incorrect usage of Annotated types for parameter {{param_name}}!
205+
Check the placement of the {ApiParamConfig.__name__} object in the type annotation:
206+
207+
{{param_name}}: {{param_type}}
208+
209+
The Annotated[T, ...] type annotation containing the
210+
{ApiParamConfig.__name__} object should not be nested inside another type.
211+
212+
Correct examples:
213+
214+
# Using Optional inside Annotated
215+
param: Annotated[Optional[int], ApiParamConfig(...)]
216+
param: Annotated[Optional[int], ApiParamConfig(...)]] = None
217+
218+
# Not using Optional when the default is not None
219+
param: Annotated[int, ApiParamConfig(...)]
220+
221+
Incorrect examples:
222+
223+
# Nesting Annotated inside Optional
224+
param: Optional[Annotated[int, ApiParamConfig(...)]]
225+
param: Optional[Annotated[int, ApiParamConfig(...)]] = None
226+
227+
# Nesting the Annotated type carrying ApiParamConfig inside other types like Union
228+
param: Union[str, Annotated[int, ApiParamConfig(...)]]
229+
"""
230+
231+
197232
def parse_single_parameter(
198233
param_name: str, param_type: Type[T], parameter: inspect.Parameter
199234
) -> FuncParam[T]:
@@ -209,12 +244,21 @@ def parse_single_parameter(
209244
# lost. This is fixed in Python 3.11:
210245
# https://github.com/python/cpython/issues/90353
211246
if param_default is None:
212-
origin = get_origin(param_type)
213247
type_args = get_args(param_type)
214-
if origin is Union and type(None) in type_args and len(type_args) == 2:
215-
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
216-
if is_annotated(inner_type):
217-
param_type = inner_type
248+
assert is_optional(param_type)
249+
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
250+
if is_annotated(inner_type):
251+
annotated_type, *annotations = get_args(inner_type)
252+
has_api_param_config = any(
253+
isinstance(annotation, ApiParamConfig) for annotation in annotations
254+
)
255+
# This prohibits the use of `Optional[Annotated[T, ApiParamConfig(...)]] = None`
256+
# and encourage `Annotated[Optional[T], ApiParamConfig(...)] = None`
257+
# to avoid confusion when the parameter metadata is unintentionally nested.
258+
assert not has_api_param_config or is_optional(
259+
annotated_type
260+
), API_PARAM_CONFIG_USAGE_HINT.format(param_name=param_name, param_type=param_type)
261+
param_type = inner_type
218262

219263
param_config: Optional[ApiParamConfig] = None
220264
json_wrapper = False
@@ -223,14 +267,22 @@ def parse_single_parameter(
223267
# metadata attached to Annotated. Note that we do not transform
224268
# param_type to its underlying type because the Annotated metadata might
225269
# still be needed by other parties like Pydantic.
226-
_, *annotations = get_args(param_type)
270+
ignored_type, *annotations = get_args(param_type)
227271
for annotation in annotations:
228272
if type(annotation) is Json:
229273
json_wrapper = True
230274
if not isinstance(annotation, ApiParamConfig):
231275
continue
232276
assert param_config is None, "ApiParamConfig can only be defined once per parameter"
233277
param_config = annotation
278+
else:
279+
# When no parameter configuration is found, assert that there is none
280+
# nested somewhere in a Union type to avoid silently ignoring it. If it
281+
# does present in the stringified parameter type, it is very likely a
282+
# programming error.
283+
assert ApiParamConfig.__name__ not in str(param_type), API_PARAM_CONFIG_USAGE_HINT.format(
284+
param_name=param_name, param_type=param_type
285+
)
234286
# Set param_config to a default early to avoid additional None-checks.
235287
if param_config is None:
236288
param_config = ApiParamConfig()

Diff for: zerver/tests/test_typed_endpoint.py

+40-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import orjson
44
from django.core.exceptions import ValidationError as DjangoValidationError
55
from django.http import HttpRequest, HttpResponse
6-
from pydantic import BaseModel, ConfigDict, Json
6+
from pydantic import BaseModel, ConfigDict, Json, StringConstraints
77
from pydantic.dataclasses import dataclass
88
from typing_extensions import Annotated
99

@@ -399,6 +399,45 @@ def view3(
399399
)
400400
self.assertFalse(result)
401401

402+
# Not nesting the Annotated type with the ApiParamConfig inside Optional is fine
403+
@typed_endpoint
404+
def no_nesting(
405+
request: HttpRequest,
406+
bar: Annotated[
407+
Optional[str],
408+
StringConstraints(strip_whitespace=True, max_length=3),
409+
ApiParamConfig("test"),
410+
] = None,
411+
) -> None:
412+
raise AssertionError
413+
414+
with self.assertRaisesMessage(ApiParamValidationError, "test is too long"):
415+
call_endpoint(no_nesting, HostRequestMock({"test": "long"}))
416+
417+
# Nesting Annotated with ApiParamConfig inside Optional is not fine
418+
def nesting_with_config(
419+
request: HttpRequest,
420+
invalid_param: Optional[Annotated[str, ApiParamConfig("test")]] = None,
421+
) -> None:
422+
raise AssertionError
423+
424+
with self.assertRaisesRegex(
425+
AssertionError,
426+
"Detected incorrect usage of Annotated types for parameter invalid_param!",
427+
):
428+
typed_endpoint(nesting_with_config)
429+
430+
# Nesting Annotated inside Optional, when ApiParamConfig is not also nested is fine
431+
@typed_endpoint
432+
def nesting_without_config(
433+
request: HttpRequest,
434+
bar: Optional[Annotated[str, StringConstraints(max_length=3)]] = None,
435+
) -> None:
436+
raise AssertionError
437+
438+
with self.assertRaisesMessage(ApiParamValidationError, "bar is too long"):
439+
call_endpoint(nesting_without_config, HostRequestMock({"bar": "long"}))
440+
402441
def test_aliases(self) -> None:
403442
@typed_endpoint
404443
def foo(

0 commit comments

Comments
 (0)