Skip to content

Commit ce8b448

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 9407148 commit ce8b448

File tree

3 files changed

+140
-9
lines changed

3 files changed

+140
-9
lines changed

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

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
@@ -167,6 +168,41 @@ def is_annotated(type_annotation: Type[object]) -> bool:
167168
return origin is Annotated
168169

169170

171+
def is_optional(type_annotation: Type[object]) -> bool:
172+
origin = get_origin(type_annotation)
173+
type_args = get_args(type_annotation)
174+
return origin is Union and type(None) in type_args and len(type_args) == 2
175+
176+
177+
API_PARAM_CONFIG_USAGE_HINT = f"""
178+
Detected incorrect usage of Annotated types for parameter {{param_name}}!
179+
Check the placement of the {ApiParamConfig.__name__} object in the type annotation:
180+
181+
{{param_name}}: {{param_type}}
182+
183+
The Annotated[T, ...] type annotation containing the
184+
{ApiParamConfig.__name__} object should not be nested inside another type.
185+
186+
Correct examples:
187+
188+
# Using Optional inside Annotated
189+
param: Annotated[Optional[int], ApiParamConfig(...)]
190+
param: Annotated[Optional[int], ApiParamConfig(...)]] = None
191+
192+
# Not using Optional when the default is not None
193+
param: Annotated[int, ApiParamConfig(...)]
194+
195+
Incorrect examples:
196+
197+
# Nesting Annotated inside Optional
198+
param: Optional[Annotated[int, ApiParamConfig(...)]]
199+
param: Optional[Annotated[int, ApiParamConfig(...)]] = None
200+
201+
# Nesting the Annotated type carrying ApiParamConfig inside other types like Union
202+
param: Union[str, Annotated[int, ApiParamConfig(...)]]
203+
"""
204+
205+
170206
def parse_single_parameter(
171207
param_name: str, param_type: Type[T], parameter: inspect.Parameter
172208
) -> FuncParam[T]:
@@ -181,13 +217,24 @@ def parse_single_parameter(
181217
# otherwise causes undesired behaviors that the annotated metadata gets
182218
# lost. This is fixed in Python 3.11:
183219
# https://github.com/python/cpython/issues/90353
184-
if param_default is None:
185-
origin = get_origin(param_type)
220+
if (
221+
sys.version_info < (3, 11) and param_default is None
222+
): # nocoverage # We lose coverage of this with Python 3.11+ only
186223
type_args = get_args(param_type)
187-
if origin is Union and type(None) in type_args and len(type_args) == 2:
188-
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
189-
if is_annotated(inner_type):
190-
param_type = inner_type
224+
assert is_optional(param_type)
225+
inner_type = type_args[0] if type_args[1] is type(None) else type_args[1]
226+
if is_annotated(inner_type):
227+
annotated_type, *annotations = get_args(inner_type)
228+
has_api_param_config = any(
229+
isinstance(annotation, ApiParamConfig) for annotation in annotations
230+
)
231+
# This prohibits the use of `Optional[Annotated[T, ApiParamConfig(...)]] = None`
232+
# and encourage `Annotated[Optional[T], ApiParamConfig(...)] = None`
233+
# to avoid confusion when the parameter metadata is unintentionally nested.
234+
assert not has_api_param_config or is_optional(
235+
annotated_type
236+
), API_PARAM_CONFIG_USAGE_HINT.format(param_name=param_name, param_type=param_type)
237+
param_type = inner_type
191238

192239
param_config: Optional[ApiParamConfig] = None
193240
json_wrapper = False
@@ -196,14 +243,22 @@ def parse_single_parameter(
196243
# metadata attached to Annotated. Note that we do not transform
197244
# param_type to its underlying type because the Annotated metadata might
198245
# still be needed by other parties like Pydantic.
199-
_, *annotations = get_args(param_type)
246+
ignored_type, *annotations = get_args(param_type)
200247
for annotation in annotations:
201248
if type(annotation) is Json:
202249
json_wrapper = True
203250
if not isinstance(annotation, ApiParamConfig):
204251
continue
205252
assert param_config is None, "ApiParamConfig can only be defined once per parameter"
206253
param_config = annotation
254+
else:
255+
# When no parameter configuration is found, assert that there is none
256+
# nested somewhere in a Union type to avoid silently ignoring it. If it
257+
# does present in the stringified parameter type, it is very likely a
258+
# programming error.
259+
assert ApiParamConfig.__name__ not in str(param_type), API_PARAM_CONFIG_USAGE_HINT.format(
260+
param_name=param_name, param_type=param_type
261+
)
207262
# Set param_config to a default early to avoid additional None-checks.
208263
if param_config is None:
209264
param_config = ApiParamConfig()

zerver/tests/test_typed_endpoint.py

+55-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
typed_endpoint_without_parameters,
2324
)
@@ -36,6 +37,16 @@ def call_endpoint(
3637

3738

3839
class TestEndpoint(ZulipTestCase):
40+
def test_is_optional(self) -> None:
41+
"""This test is only needed because we don't
42+
have coverage of is_optional in Python 3.11.
43+
"""
44+
type = cast(Type[Optional[str]], Optional[str])
45+
self.assertTrue(is_optional(type))
46+
47+
type = str
48+
self.assertFalse(is_optional(str))
49+
3950
def test_coerce(self) -> None:
4051
@typed_endpoint
4152
def view(request: HttpRequest, *, strict_int: int) -> int:
@@ -409,6 +420,48 @@ def view3(
409420
)
410421
self.assertFalse(result)
411422

423+
# Not nesting the Annotated type with the ApiParamConfig inside Optional is fine
424+
@typed_endpoint
425+
def no_nesting(
426+
request: HttpRequest,
427+
*,
428+
bar: Annotated[
429+
Optional[str],
430+
StringConstraints(strip_whitespace=True, max_length=3),
431+
ApiParamConfig("test"),
432+
] = None,
433+
) -> None:
434+
raise AssertionError
435+
436+
with self.assertRaisesMessage(ApiParamValidationError, "test is too long"):
437+
call_endpoint(no_nesting, HostRequestMock({"test": "long"}))
438+
439+
# Nesting Annotated with ApiParamConfig inside Optional is not fine
440+
def nesting_with_config(
441+
request: HttpRequest,
442+
*,
443+
invalid_param: Optional[Annotated[str, ApiParamConfig("test")]] = None,
444+
) -> None:
445+
raise AssertionError
446+
447+
with self.assertRaisesRegex(
448+
AssertionError,
449+
"Detected incorrect usage of Annotated types for parameter invalid_param!",
450+
):
451+
typed_endpoint(nesting_with_config)
452+
453+
# Nesting Annotated inside Optional, when ApiParamConfig is not also nested is fine
454+
@typed_endpoint
455+
def nesting_without_config(
456+
request: HttpRequest,
457+
*,
458+
bar: Optional[Annotated[str, StringConstraints(max_length=3)]] = None,
459+
) -> None:
460+
raise AssertionError
461+
462+
with self.assertRaisesMessage(ApiParamValidationError, "bar is too long"):
463+
call_endpoint(nesting_without_config, HostRequestMock({"bar": "long"}))
464+
412465
def test_aliases(self) -> None:
413466
@typed_endpoint
414467
def foo(

0 commit comments

Comments
 (0)