From b8741d6bf4dd0db4da1080179ced3c388b1841f3 Mon Sep 17 00:00:00 2001 From: Arnaud Durand Date: Tue, 4 Jul 2023 01:32:48 +0200 Subject: [PATCH] Fix scopes on security sub-dependant --- fastapi/dependencies/utils.py | 10 +++++----- tests/test_dependency_cache.py | 21 +++++++++++++++++++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/fastapi/dependencies/utils.py b/fastapi/dependencies/utils.py index f131001ce..3ff2874c3 100644 --- a/fastapi/dependencies/utils.py +++ b/fastapi/dependencies/utils.py @@ -145,14 +145,14 @@ def get_sub_dependant( security_scopes: Optional[List[str]] = None, ) -> Dependant: security_requirement = None - security_scopes = security_scopes or [] + use_scopes: List[str] = [] if isinstance(depends, params.Security): + use_scopes = security_scopes or [] dependency_scopes = depends.scopes - security_scopes.extend(dependency_scopes) + use_scopes.extend(dependency_scopes) if isinstance(dependency, SecurityBase): - use_scopes: List[str] = [] if isinstance(dependency, (OAuth2, OpenIdConnect)): - use_scopes = security_scopes + use_scopes = security_scopes or [] security_requirement = SecurityRequirement( security_scheme=dependency, scopes=use_scopes ) @@ -160,7 +160,7 @@ def get_sub_dependant( path=path, call=dependency, name=name, - security_scopes=security_scopes, + security_scopes=use_scopes, use_cache=depends.use_cache, ) if security_requirement: diff --git a/tests/test_dependency_cache.py b/tests/test_dependency_cache.py index 08fb9b74f..518990358 100644 --- a/tests/test_dependency_cache.py +++ b/tests/test_dependency_cache.py @@ -48,6 +48,17 @@ async def get_scope_counter( } +@app.get("/scope-sub-counter") +async def get_scope_counter_sub( + count: int = Security(dep_counter), + scope_subcount: int = Security(super_dep, scopes=["scope"]), +): + return { + "counter": count, + "scope_counter": scope_subcount, + } + + client = TestClient(app) @@ -89,3 +100,13 @@ def test_security_cache(): response = client.get("/scope-counter/") assert response.status_code == 200, response.text assert response.json() == {"counter": 3, "scope_counter_1": 4, "scope_counter_2": 4} + + +def test_security_cache_sub(): + counter_holder["counter"] = 0 + response = client.get("/scope-sub-counter/") + assert response.status_code == 200, response.text + assert response.json() == {"counter": 1, "scope_counter": 1} + response = client.get("/scope-sub-counter/") + assert response.status_code == 200, response.text + assert response.json() == {"counter": 2, "scope_counter": 2}