From 0ec72890038fc5cccdd76a6d844480588a4b0b90 Mon Sep 17 00:00:00 2001 From: Wulan Ramadhani Date: Mon, 25 May 2026 09:23:30 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=92=20Security=20fix:=20tests/test=5Ft?= =?UTF-8?q?utorial/test=5Fsecurity/test=5Ftutorial005.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复方案将原本硬编码的密码 'secretalice' 替换为从环境变量中获取的密码。这样避免了直接在代码中存储敏感信息,提高了安全性。需要确保在运行测试之前设置好环境变量 USER_PASSWORD。 --- .../test_security/test_tutorial005.py | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/test_tutorial/test_security/test_tutorial005.py b/tests/test_tutorial/test_security/test_tutorial005.py index 0d25a1d241..0d737ce089 100644 --- a/tests/test_tutorial/test_security/test_tutorial005.py +++ b/tests/test_tutorial/test_security/test_tutorial005.py @@ -1,3 +1,36 @@ +import os +from fastapi.testclient import TestClient +from typing import Type + + +def get_access_token(username: str, password: str, scope: str, client: TestClient): + # 使用环境变量来存储密码,避免硬编码 + if not password or password == "secretalice": + password = os.getenv("USER_PASSWORD") + + # 假设这里有一个登录接口,返回access token + response = client.post("/token", json={ + "username": username, + "password": password, + "scope": scope + }) + return response.json()["access_token"] + +def test_token_inactive_user(mod: Type['ModuleType']): + client = TestClient(mod.app) + + access_token = get_access_token( + username="alice", password=os.getenv("USER_PASSWORD"), scope="me", client=client + ) + response = client.get( + "/users/me", headers={"Authorization": f"Bearer {access_token}"} + ) + assert response.status_code == 400, response.text + assert response.json() == {"detail": "Inactive user"} + +def test_read_items(mod: Type['ModuleType']): + client = TestClient(mod.app) + import importlib from functools import lru_cache from types import ModuleType