Skip to content

Commit edab85d

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 cb137fb commit edab85d

File tree

3 files changed

+137
-9
lines changed

3 files changed

+137
-9
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

+62-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import inspect
22
import json
3+
import sys
34
from dataclasses import dataclass
45
from enum import Enum, auto
56
from functools import wraps
@@ -175,6 +176,41 @@ def is_annotated(type_annotation: Type[object]) -> bool:
175176
return origin is Annotated
176177

177178

179+
def is_optional(type_annotation: Type[object]) -> bool:
180+
origin = get_origin(type_annotation)
181+
type_args = get_args(type_annotation)
182+
return origin is Union and type(None) in type_args and len(type_args) == 2
183+
184+
185+
API_PARAM_CONFIG_USAGE_HINT = f"""
186+
Detected incorrect usage of Annotated types for parameter {{param_name}}!
187+
Check the placement of the {ApiParamConfig.__name__} object in the type annotation:
188+
189+
{{param_name}}: {{param_type}}
190+
191+
The Annotated[T, ...] type annotation containing the
192+
{ApiParamConfig.__name__} object should not be nested inside another type.
193+
194+
Correct examples:
195+
196+
# Using Optional inside Annotated
197+
param: Annotated[Optional[int], ApiParamConfig(...)]
198+
param: Annotated[Optional[int], ApiParamConfig(...)]] = None
199+
200+
# Not using Optional when the default is not None
201+
param: Annotated[int, ApiParamConfig(...)]
202+
203+
Incorrect examples:
204+
205+
# Nesting Annotated inside Optional
206+
param: Optional[Annotated[int, ApiParamConfig(...)]]
207+
param: Optional[Annotated[int, ApiParamConfig(...)]] = None
208+
209+
# Nesting the Annotated type carrying ApiParamConfig inside other types like Union
210+
param: Union[str, Annotated[int, ApiParamConfig(...)]]
211+
"""
212+
213+
178214
def parse_single_parameter(
179215
param_name: str, param_type: Type[T], parameter: inspect.Parameter
180216
) -> FuncParam[T]:
@@ -189,13 +225,24 @@ def parse_single_parameter(
189225
# otherwise causes undesired behaviors that the annotated metadata gets
190226
# lost. This is fixed in Python 3.11:
191227
# https://github.com/python/cpython/issues/90353
192-
if param_default is None:
193-
origin = get_origin(param_type)
228+
if (
229+
sys.version_info < (3, 11) and param_default is None
230+
): # nocoverage # We lose coverage of this with Python 3.11+ only
194231
type_args = get_args(param_type)
195-
if origin is Union and type(None) in type_args and len(type_args) == 2:
196-
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
197-
if is_annotated(inner_type):
198-
param_type = inner_type
232+
assert is_optional(param_type)
233+
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
234+
if is_annotated(inner_type):
235+
annotated_type, *annotations = get_args(inner_type)
236+
has_api_param_config = any(
237+
isinstance(annotation, ApiParamConfig) for annotation in annotations
238+
)
239+
# This prohibits the use of `Optional[Annotated[T, ApiParamConfig(...)]] = None`
240+
# and encourage `Annotated[Optional[T], ApiParamConfig(...)] = None`
241+
# to avoid confusion when the parameter metadata is unintentionally nested.
242+
assert not has_api_param_config or is_optional(
243+
annotated_type
244+
), API_PARAM_CONFIG_USAGE_HINT.format(param_name=param_name, param_type=param_type)
245+
param_type = inner_type
199246

200247
param_config: Optional[ApiParamConfig] = None
201248
json_wrapper = False
@@ -204,14 +251,22 @@ def parse_single_parameter(
204251
# metadata attached to Annotated. Note that we do not transform
205252
# param_type to its underlying type because the Annotated metadata might
206253
# still be needed by other parties like Pydantic.
207-
_, *annotations = get_args(param_type)
254+
ignored_type, *annotations = get_args(param_type)
208255
for annotation in annotations:
209256
if type(annotation) is Json:
210257
json_wrapper = True
211258
if not isinstance(annotation, ApiParamConfig):
212259
continue
213260
assert param_config is None, "ApiParamConfig can only be defined once per parameter"
214261
param_config = annotation
262+
else:
263+
# When no parameter configuration is found, assert that there is none
264+
# nested somewhere in a Union type to avoid silently ignoring it. If it
265+
# does present in the stringified parameter type, it is very likely a
266+
# programming error.
267+
assert ApiParamConfig.__name__ not in str(param_type), API_PARAM_CONFIG_USAGE_HINT.format(
268+
param_name=param_name, param_type=param_type
269+
)
215270
# Set param_config to a default early to avoid additional None-checks.
216271
if param_config is None:
217272
param_config = ApiParamConfig()

Diff for: zerver/tests/test_typed_endpoint.py

+52-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from typing import Any, Callable, Dict, List, Literal, Optional, TypeVar, Union
1+
from typing import Any, Callable, Dict, List, Literal, Optional, Type, TypeVar, Union, cast
22

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

@@ -18,6 +18,7 @@
1818
PathOnly,
1919
RequiredStringConstraint,
2020
WebhookPayload,
21+
is_optional,
2122
typed_endpoint,
2223
)
2324
from zerver.lib.validator import WildValue, check_bool
@@ -35,6 +36,16 @@ def call_endpoint(
3536

3637

3738
class TestEndpoint(ZulipTestCase):
39+
def test_is_optional(self) -> None:
40+
"""This test is only needed because we don't
41+
have coverage of is_optional in Python 3.11.
42+
"""
43+
type = cast(Type[Optional[str]], Optional[str])
44+
self.assertTrue(is_optional(type))
45+
46+
type = str
47+
self.assertFalse(is_optional(str))
48+
3849
def test_coerce(self) -> None:
3950
@typed_endpoint
4051
def view(request: HttpRequest, loose_int: int) -> int:
@@ -399,6 +410,45 @@ def view3(
399410
)
400411
self.assertFalse(result)
401412

413+
# Not nesting the Annotated type with the ApiParamConfig inside Optional is fine
414+
@typed_endpoint
415+
def no_nesting(
416+
request: HttpRequest,
417+
bar: Annotated[
418+
Optional[str],
419+
StringConstraints(strip_whitespace=True, max_length=3),
420+
ApiParamConfig("test"),
421+
] = None,
422+
) -> None:
423+
raise AssertionError
424+
425+
with self.assertRaisesMessage(ApiParamValidationError, "test is too long"):
426+
call_endpoint(no_nesting, HostRequestMock({"test": "long"}))
427+
428+
# Nesting Annotated with ApiParamConfig inside Optional is not fine
429+
def nesting_with_config(
430+
request: HttpRequest,
431+
invalid_param: Optional[Annotated[str, ApiParamConfig("test")]] = None,
432+
) -> None:
433+
raise AssertionError
434+
435+
with self.assertRaisesRegex(
436+
AssertionError,
437+
"Detected incorrect usage of Annotated types for parameter invalid_param!",
438+
):
439+
typed_endpoint(nesting_with_config)
440+
441+
# Nesting Annotated inside Optional, when ApiParamConfig is not also nested is fine
442+
@typed_endpoint
443+
def nesting_without_config(
444+
request: HttpRequest,
445+
bar: Optional[Annotated[str, StringConstraints(max_length=3)]] = None,
446+
) -> None:
447+
raise AssertionError
448+
449+
with self.assertRaisesMessage(ApiParamValidationError, "bar is too long"):
450+
call_endpoint(nesting_without_config, HostRequestMock({"bar": "long"}))
451+
402452
def test_aliases(self) -> None:
403453
@typed_endpoint
404454
def foo(

0 commit comments

Comments
 (0)