pytest-api-framework-alpha 1.0.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- framework/__init__.py +1 -0
- framework/assertion/__init__.py +3 -0
- framework/assertion/retry_assert.py +67 -0
- framework/assertion/webhook_assert.py +129 -0
- framework/client/__init__.py +3 -0
- framework/client/crrm_client.py +155 -0
- framework/client/http_client.py +340 -0
- framework/client/mq_client.py +178 -0
- framework/client/websocket_client.py +414 -0
- framework/conftest.py +526 -0
- framework/core/__init__.py +3 -0
- framework/core/base_class.py +871 -0
- framework/core/extract.py +185 -0
- framework/core/global_attribute.py +187 -0
- framework/core/hooks/__init__.py +3 -0
- framework/core/hooks/filters.py +217 -0
- framework/core/hooks/reporter.py +228 -0
- framework/core/hooks/session.py +345 -0
- framework/core/hooks/sorting.py +84 -0
- framework/core/models.py +82 -0
- framework/core/render_data.py +309 -0
- framework/core/validate.py +648 -0
- framework/db/__init__.py +3 -0
- framework/db/mysql_db.py +226 -0
- framework/db/redis_db.py +319 -0
- framework/exceptions.py +22 -0
- framework/exit_code.py +20 -0
- framework/gen/__init__.py +3 -0
- framework/gen/case_gen.py +1268 -0
- framework/gen/create_app.py +265 -0
- framework/report.py +111 -0
- framework/script.py +35 -0
- framework/settings.py +93 -0
- framework/utils/__init__.py +3 -0
- framework/utils/cognito_util.py +348 -0
- framework/utils/common.py +298 -0
- framework/utils/date_util.py +218 -0
- framework/utils/encrypt.py +448 -0
- framework/utils/lark_util.py +167 -0
- framework/utils/log_util.py +10 -0
- framework/utils/mock_util.py +236 -0
- framework/utils/yaml_util.py +169 -0
- framework/ws_server.py +167 -0
- pytest_api_framework_alpha-1.0.5.dist-info/METADATA +98 -0
- pytest_api_framework_alpha-1.0.5.dist-info/RECORD +48 -0
- pytest_api_framework_alpha-1.0.5.dist-info/WHEEL +5 -0
- pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE +21 -0
- pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""
|
|
2
|
+
AWS Cognito User Pool 登录工具模块。
|
|
3
|
+
|
|
4
|
+
实现 `USER_AUTH` + `PASSWORD_SRP` 认证流程(Cognito 新版选择式登录),完整覆盖三次请求:
|
|
5
|
+
|
|
6
|
+
1. InitiateAuth AuthFlow=USER_AUTH, PREFERRED_CHALLENGE=PASSWORD_SRP → 返回 PASSWORD_VERIFIER 挑战
|
|
7
|
+
2. RespondToAuthChallenge ChallengeName=PASSWORD_VERIFIER,提交 SRP 密码证明 → 返回 token 或 MFA 挑战
|
|
8
|
+
3. RespondToAuthChallenge ChallengeName=SOFTWARE_TOKEN_MFA,提交 TOTP 动态码 → 返回 token
|
|
9
|
+
|
|
10
|
+
access token 默认只有 15 分钟有效期,长流程用例跑一半就会过期,所以另外提供了三个方法:
|
|
11
|
+
`refresh()` 用 refresh token 换新令牌(不需要密码和 MFA),`revoke()` 作废单个 refresh token,
|
|
12
|
+
`sign_out()` 把该用户在本用户池下的所有 refresh token 一次性作废。
|
|
13
|
+
|
|
14
|
+
SRP 的密码学运算全部委托给 `pycognito.aws_srp.AWSSRP`(Python 生态的事实标准实现),
|
|
15
|
+
API 调用走 boto3 的 cognito-idp 客户端。本模块只负责 USER_AUTH 流程编排、MFA 应答和错误翻译。
|
|
16
|
+
|
|
17
|
+
pycognito 自带的 `authenticate_user()` 走的是经典 `USER_SRP_AUTH`,不支持 USER_AUTH 的
|
|
18
|
+
PREFERRED_CHALLENGE,所以这里自己驱动 initiate_auth / respond_to_auth_challenge,
|
|
19
|
+
但复用它的 `get_auth_params()` 和 `process_challenge()`。
|
|
20
|
+
|
|
21
|
+
登录接口是匿名接口,boto3 客户端用 UNSIGNED 配置,不需要任何 AWS 凭证。
|
|
22
|
+
|
|
23
|
+
典型用法(test_case/conftest.py)::
|
|
24
|
+
|
|
25
|
+
class CampLogin(HttpLogin):
|
|
26
|
+
|
|
27
|
+
def login(self, username, password, mfa_secret=None, **kwargs):
|
|
28
|
+
auth = CognitoAuth(user_pool_id="ap-southeast-1_xxxxxxxxx",
|
|
29
|
+
client_id="3rvhpl9p4u9l9ftt5rehh35cg6")
|
|
30
|
+
tokens = auth.login(username, password, mfa_secret=mfa_secret)
|
|
31
|
+
client = HttpClient()
|
|
32
|
+
client.update_headers({"Authorization": tokens.authorization})
|
|
33
|
+
return client
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import json
|
|
37
|
+
import time
|
|
38
|
+
import base64
|
|
39
|
+
import threading
|
|
40
|
+
from typing import Any
|
|
41
|
+
from dataclasses import dataclass
|
|
42
|
+
|
|
43
|
+
import boto3
|
|
44
|
+
import pyotp
|
|
45
|
+
from botocore import UNSIGNED
|
|
46
|
+
from botocore.config import Config
|
|
47
|
+
from botocore.exceptions import BotoCoreError, ClientError
|
|
48
|
+
from pycognito.aws_srp import AWSSRP
|
|
49
|
+
|
|
50
|
+
from framework.exceptions import LoginException
|
|
51
|
+
from framework.utils.log_util import logger
|
|
52
|
+
|
|
53
|
+
# 常见错误码的排查方向,直接拼进异常信息,省得每次翻文档
|
|
54
|
+
ERROR_HINTS = {
|
|
55
|
+
"NotAuthorizedException": "密码错误、签名不符或时间戳格式不对,Cognito 对这几种情况返回同一个错误;"
|
|
56
|
+
"连续失败会触发临时锁定(指数退避,最长约 15 分钟)。"
|
|
57
|
+
"刷新令牌时则是 refresh token 已过期、已被吊销,或用错了 App Client:"
|
|
58
|
+
"只有签发它的那个 client_id 能拿它换 token",
|
|
59
|
+
"CodeMismatchException": "动态码不匹配,检查 mfa_secret 是否是该账号当前绑定的那一个,以及本机时钟是否准确",
|
|
60
|
+
"UserNotFoundException": "该用户池中不存在此用户",
|
|
61
|
+
"InternalErrorException": "用户可能不在该用户池中,检查 user_pool_id 与用户名是否对应",
|
|
62
|
+
"InvalidParameterException": "请求参数不合法,常见于 App Client 未开启 ALLOW_USER_AUTH;"
|
|
63
|
+
"刷新令牌时则检查有没有开启 ALLOW_REFRESH_TOKEN_AUTH",
|
|
64
|
+
"ExpiredCodeException": "Session 已过期,SECRET_BLOCK 有效期只有几分钟,需要重新走登录流程",
|
|
65
|
+
"UnsupportedOperationException": "吊销令牌时:App Client 未开启令牌吊销(token revocation),"
|
|
66
|
+
"开启后签发的 token 才带 origin_jti,才能被吊销;"
|
|
67
|
+
"刷新令牌时:该 App Client 开/关了刷新令牌轮换,"
|
|
68
|
+
"两种刷新接口只能二选一,见 _refresh_call()",
|
|
69
|
+
"UnsupportedTokenTypeException": "RevokeToken 只接受 refresh token,access token 和 id token 吊销不了",
|
|
70
|
+
"RefreshTokenReuseException": "这个 refresh token 已经被用过了。App Client 开了刷新令牌轮换,"
|
|
71
|
+
"每刷新一次旧的就作废,必须拿返回值里的新 refresh token 替换手里的",
|
|
72
|
+
"TooManyRequestsException": "请求过于频繁,被 Cognito 限流了,稍后重试",
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
# TOTP 动态码在同一时间窗内不可重复使用,这里按 secret 记录上次用过的码
|
|
76
|
+
_totp_lock = threading.Lock()
|
|
77
|
+
_totp_used: dict[str, str] = {}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class CognitoTokens:
|
|
82
|
+
"""Cognito 登录成功后返回的令牌集合。"""
|
|
83
|
+
|
|
84
|
+
access_token: str
|
|
85
|
+
id_token: str
|
|
86
|
+
refresh_token: str = ""
|
|
87
|
+
expires_in: int = 0
|
|
88
|
+
token_type: str = "Bearer"
|
|
89
|
+
username: str = "" # 用户在 Cognito 中的唯一标识(sub)
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def authorization(self) -> str:
|
|
93
|
+
"""拼好的 Authorization 头部值,如 'Bearer eyJ...'。"""
|
|
94
|
+
return f"{self.token_type} {self.access_token}"
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _totp_code(secret: str, interval: int = 30) -> str:
|
|
98
|
+
"""生成 TOTP 动态码。
|
|
99
|
+
|
|
100
|
+
Cognito 会拒绝同一个时间窗内重复提交的动态码(报 "Invalid code received for user"),
|
|
101
|
+
自动化里连续登录很容易撞上,所以这里检测到重复就等到下一个时间窗再取。
|
|
102
|
+
|
|
103
|
+
@param secret: TOTP 密钥(Base32)
|
|
104
|
+
@param interval: TOTP 时间窗长度,单位秒
|
|
105
|
+
@return: 6 位动态码
|
|
106
|
+
"""
|
|
107
|
+
totp = pyotp.TOTP(secret, interval=interval)
|
|
108
|
+
with _totp_lock:
|
|
109
|
+
code = totp.now()
|
|
110
|
+
if _totp_used.get(secret) == code:
|
|
111
|
+
wait = interval - int(time.time()) % interval + 1
|
|
112
|
+
logger.info(f"TOTP 动态码 {code} 已使用过,等待 {wait}s 进入下一个时间窗")
|
|
113
|
+
time.sleep(wait)
|
|
114
|
+
code = totp.now()
|
|
115
|
+
_totp_used[secret] = code
|
|
116
|
+
return code
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _token_username(access_token: str) -> str:
|
|
120
|
+
"""从 access token 的负载里取出 username 声明(Cognito 里就是用户的 sub)。
|
|
121
|
+
|
|
122
|
+
刷新令牌的响应不像登录那样带 ChallengeParameters,拿不到用户标识,只能从 token 自己身上读。
|
|
123
|
+
这里只解析负载、不校验签名 —— token 刚从 Cognito 经 TLS 取回来,没有伪造的余地,
|
|
124
|
+
而且这个值只用于日志和 CognitoTokens.username,不参与任何鉴权判断。
|
|
125
|
+
|
|
126
|
+
@param access_token: JWT 格式的 access token
|
|
127
|
+
@return: username,解析失败时返回空串
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
payload = access_token.split(".")[1]
|
|
131
|
+
payload += "=" * (-len(payload) % 4) # base64url 去掉了填充,补回来才能解码
|
|
132
|
+
return json.loads(base64.urlsafe_b64decode(payload)).get("username", "")
|
|
133
|
+
except Exception as e:
|
|
134
|
+
logger.warning(f"解析 access token 的 username 失败: {type(e).__name__}: {e}")
|
|
135
|
+
return ""
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class CognitoAuth(object):
|
|
139
|
+
"""Cognito User Pool SRP 登录客户端。
|
|
140
|
+
|
|
141
|
+
一个实例对应一个用户池 + 一个 App Client,可重复用于多个账号登录。
|
|
142
|
+
每次调用 login() 都会新建一个 AWSSRP(重新生成 SRP 私钥 a),互不影响。
|
|
143
|
+
"""
|
|
144
|
+
|
|
145
|
+
def __init__(self, user_pool_id: str, client_id: str, timeout: int = 30) -> None:
|
|
146
|
+
"""
|
|
147
|
+
@param user_pool_id: 用户池 ID,形如 'ap-southeast-1_xxxxxxxxx',区域从前缀解析
|
|
148
|
+
@param client_id: App Client ID(公开信息,前端可见)
|
|
149
|
+
@param timeout: 单次请求超时时间,单位秒
|
|
150
|
+
"""
|
|
151
|
+
if "_" not in user_pool_id:
|
|
152
|
+
raise LoginException(f"user_pool_id 格式错误: {user_pool_id},应形如 'ap-southeast-1_xxxxxxxxx'")
|
|
153
|
+
self.user_pool_id = user_pool_id
|
|
154
|
+
self.client_id = client_id
|
|
155
|
+
self.region = user_pool_id.split("_", 1)[0]
|
|
156
|
+
# 登录是匿名接口,UNSIGNED 让 botocore 跳过签名,无需任何 AWS 凭证
|
|
157
|
+
self.client = boto3.client(
|
|
158
|
+
"cognito-idp",
|
|
159
|
+
region_name=self.region,
|
|
160
|
+
config=Config(signature_version=UNSIGNED, connect_timeout=timeout, read_timeout=timeout),
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
def login(self, username: str, password: str, mfa_secret: str | None = None) -> CognitoTokens:
|
|
164
|
+
"""执行完整登录流程,返回令牌。
|
|
165
|
+
|
|
166
|
+
@param username: 登录名(邮箱/手机号/用户名,取决于用户池配置)
|
|
167
|
+
@param password: 明文密码,仅在本地参与 SRP 运算,不会发送到服务端
|
|
168
|
+
@param mfa_secret: TOTP 密钥(Base32),账号开启了 MFA 时必传
|
|
169
|
+
@return: CognitoTokens
|
|
170
|
+
@raises LoginException: 任意一步失败时抛出
|
|
171
|
+
"""
|
|
172
|
+
srp = AWSSRP(username=username, password=password, pool_id=self.user_pool_id,
|
|
173
|
+
client_id=self.client_id, client=self.client)
|
|
174
|
+
|
|
175
|
+
# 第 1 步:InitiateAuth。USERNAME / SRP_A 由 pycognito 生成,
|
|
176
|
+
# 这里只补上 USER_AUTH 流程特有的 PREFERRED_CHALLENGE
|
|
177
|
+
auth_params = srp.get_auth_params()
|
|
178
|
+
auth_params["PREFERRED_CHALLENGE"] = "PASSWORD_SRP"
|
|
179
|
+
logger.info(f"⮕ Cognito.InitiateAuth: USER_AUTH/PASSWORD_SRP user={username}")
|
|
180
|
+
result = self._call(self.client.initiate_auth, AuthFlow="USER_AUTH",
|
|
181
|
+
ClientId=self.client_id, AuthParameters=auth_params)
|
|
182
|
+
|
|
183
|
+
challenge = result.get("ChallengeName")
|
|
184
|
+
if challenge == "SELECT_CHALLENGE":
|
|
185
|
+
raise LoginException(f"{username} 不支持 PASSWORD_SRP,"
|
|
186
|
+
f"可用认证方式: {result.get('AvailableChallenges')}")
|
|
187
|
+
if challenge != "PASSWORD_VERIFIER":
|
|
188
|
+
raise LoginException(f"InitiateAuth 返回了预期之外的挑战: {challenge},原始响应: {result}")
|
|
189
|
+
|
|
190
|
+
# 第 2 步:密码证明整段交给 pycognito 计算(salt/B/secret_block → 签名 + 时间戳)
|
|
191
|
+
params = result["ChallengeParameters"]
|
|
192
|
+
challenge_responses = srp.process_challenge(params, auth_params)
|
|
193
|
+
username_for_srp = challenge_responses["USERNAME"]
|
|
194
|
+
logger.info(f"⮕ Cognito.RespondToAuthChallenge: PASSWORD_VERIFIER user={username_for_srp}")
|
|
195
|
+
result = self._respond("PASSWORD_VERIFIER", challenge_responses, result.get("Session"))
|
|
196
|
+
|
|
197
|
+
# 第 3 步:按服务端返回的挑战继续应答(MFA 等),直到拿到令牌
|
|
198
|
+
result = self._resolve_challenges(result, username_for_srp, mfa_secret)
|
|
199
|
+
return self._to_tokens(result, params.get("USER_ID_FOR_SRP", username_for_srp))
|
|
200
|
+
|
|
201
|
+
def refresh(self, refresh_token: str) -> CognitoTokens:
|
|
202
|
+
"""用 refresh token 换一组新的 access / id token,不需要密码,也不会触发 MFA。
|
|
203
|
+
|
|
204
|
+
access token 默认 15 分钟就过期,用例跑长流程时用这个续期,比重新登录快得多,
|
|
205
|
+
也不用担心 TOTP 动态码在同一时间窗内撞车。
|
|
206
|
+
|
|
207
|
+
三个注意点:
|
|
208
|
+
|
|
209
|
+
- 必须用签发这个 refresh token 的 App Client,换别的 client_id 会报 NotAuthorizedException;
|
|
210
|
+
- App Client 开了刷新令牌轮换(refresh token rotation)时,响应会下发一个新的 refresh token,
|
|
211
|
+
旧的过了宽限期就作废,所以每次刷新后都要拿返回值里的 refresh_token 覆盖手里那个;
|
|
212
|
+
- 没开轮换时响应里不带 refresh token,这时返回值沿用传进来的那个,照上面那样用也不会出错。
|
|
213
|
+
|
|
214
|
+
@param refresh_token: 登录时拿到的 refresh token,默认有效期 30 天
|
|
215
|
+
@return: CognitoTokens,其中 refresh_token 字段是"下一次该用的那个"
|
|
216
|
+
@raises LoginException: refresh token 过期、被吊销,或 App Client 未开启 ALLOW_REFRESH_TOKEN_AUTH
|
|
217
|
+
"""
|
|
218
|
+
result = self._refresh_call(refresh_token)
|
|
219
|
+
tokens = self._to_tokens(result, "")
|
|
220
|
+
tokens.refresh_token = tokens.refresh_token or refresh_token
|
|
221
|
+
tokens.username = _token_username(tokens.access_token)
|
|
222
|
+
return tokens
|
|
223
|
+
|
|
224
|
+
def _refresh_call(self, refresh_token: str) -> dict[str, Any]:
|
|
225
|
+
"""发起刷新请求,返回原始响应。
|
|
226
|
+
|
|
227
|
+
Cognito 现在有两个刷新接口,而且互斥:App Client 开了刷新令牌轮换的,只能用
|
|
228
|
+
GetTokensFromRefreshToken,走经典的 InitiateAuth 会被拒("This API does not support
|
|
229
|
+
refresh token rotation")。所以这里优先用新接口,老用户池不认时再退回 InitiateAuth。
|
|
230
|
+
"""
|
|
231
|
+
logger.info("⮕ Cognito.GetTokensFromRefreshToken")
|
|
232
|
+
try:
|
|
233
|
+
return self.client.get_tokens_from_refresh_token(
|
|
234
|
+
ClientId=self.client_id, RefreshToken=refresh_token)
|
|
235
|
+
except ClientError as e:
|
|
236
|
+
if e.response.get("Error", {}).get("Code") != "UnsupportedOperationException":
|
|
237
|
+
raise self._translate(e) from e
|
|
238
|
+
logger.info("用户池不支持 GetTokensFromRefreshToken,回退到 REFRESH_TOKEN_AUTH")
|
|
239
|
+
except BotoCoreError as e:
|
|
240
|
+
raise self._translate(e) from e
|
|
241
|
+
|
|
242
|
+
logger.info("⮕ Cognito.InitiateAuth: REFRESH_TOKEN_AUTH")
|
|
243
|
+
return self._call(self.client.initiate_auth, AuthFlow="REFRESH_TOKEN_AUTH",
|
|
244
|
+
ClientId=self.client_id,
|
|
245
|
+
AuthParameters={"REFRESH_TOKEN": refresh_token})
|
|
246
|
+
|
|
247
|
+
def revoke(self, refresh_token: str) -> None:
|
|
248
|
+
"""作废一个 refresh token,以及用它换出来的所有 access token。
|
|
249
|
+
|
|
250
|
+
要求 App Client 开启了令牌吊销,否则报 UnsupportedOperationException。
|
|
251
|
+
重复吊销同一个 token 不会报错,所以可以放心写在用例的清理步骤里。
|
|
252
|
+
|
|
253
|
+
注意吊销只在 Cognito 侧生效:调 Cognito 接口会立刻被拒,但业务服务如果是本地验签
|
|
254
|
+
(只看签名和 exp,不回查 Cognito),那个 access token 在剩下的有效期内仍然能用。
|
|
255
|
+
想验证"token 失效"这种场景,别只看吊销有没有成功,要看被测服务自己怎么校验。
|
|
256
|
+
|
|
257
|
+
@param refresh_token: 待作废的 refresh token
|
|
258
|
+
@raises LoginException: App Client 未开启令牌吊销,或传入的不是 refresh token
|
|
259
|
+
"""
|
|
260
|
+
logger.info("⮕ Cognito.RevokeToken")
|
|
261
|
+
self._call(self.client.revoke_token, Token=refresh_token, ClientId=self.client_id)
|
|
262
|
+
|
|
263
|
+
def sign_out(self, access_token: str) -> None:
|
|
264
|
+
"""全局登出:作废该用户在本用户池下签发的所有 refresh token。
|
|
265
|
+
|
|
266
|
+
比 revoke() 范围大 —— revoke() 只作废指定的那一个,这个方法把该用户所有设备、
|
|
267
|
+
所有 App Client 上的 refresh token 全部作废,适合多账号并发的用例做收尾清理。
|
|
268
|
+
|
|
269
|
+
access token 同样不会立刻失效,原因见 revoke() 的说明。
|
|
270
|
+
|
|
271
|
+
@param access_token: 该用户当前有效的 access token,过期的用不了
|
|
272
|
+
@raises LoginException: access token 已过期或已被吊销
|
|
273
|
+
"""
|
|
274
|
+
logger.info("⮕ Cognito.GlobalSignOut")
|
|
275
|
+
self._call(self.client.global_sign_out, AccessToken=access_token)
|
|
276
|
+
|
|
277
|
+
@staticmethod
|
|
278
|
+
def _translate(e: Exception) -> LoginException:
|
|
279
|
+
"""把 botocore 异常翻译成带排查提示的 LoginException。"""
|
|
280
|
+
if isinstance(e, ClientError):
|
|
281
|
+
err = e.response.get("Error", {})
|
|
282
|
+
code = err.get("Code", "UnknownError")
|
|
283
|
+
hint = ERROR_HINTS.get(code)
|
|
284
|
+
return LoginException(f"Cognito 调用失败: {code}: {err.get('Message') or e}"
|
|
285
|
+
+ (f" —— {hint}" if hint else ""))
|
|
286
|
+
return LoginException(f"Cognito 请求失败: {type(e).__name__}: {e}")
|
|
287
|
+
|
|
288
|
+
@staticmethod
|
|
289
|
+
def _call(api: Any, **kwargs: Any) -> dict[str, Any]:
|
|
290
|
+
"""调用 boto3 接口,把 botocore 异常翻译成带排查提示的 LoginException。"""
|
|
291
|
+
try:
|
|
292
|
+
return api(**kwargs)
|
|
293
|
+
except (ClientError, BotoCoreError) as e:
|
|
294
|
+
raise CognitoAuth._translate(e) from e
|
|
295
|
+
|
|
296
|
+
def _respond(self, challenge_name: str, responses: dict[str, str],
|
|
297
|
+
session: str | None) -> dict[str, Any]:
|
|
298
|
+
"""提交一次挑战应答。"""
|
|
299
|
+
kwargs: dict[str, Any] = {
|
|
300
|
+
"ClientId": self.client_id,
|
|
301
|
+
"ChallengeName": challenge_name,
|
|
302
|
+
"ChallengeResponses": responses,
|
|
303
|
+
}
|
|
304
|
+
if session:
|
|
305
|
+
kwargs["Session"] = session
|
|
306
|
+
return self._call(self.client.respond_to_auth_challenge, **kwargs)
|
|
307
|
+
|
|
308
|
+
def _resolve_challenges(self, result: dict[str, Any], username: str,
|
|
309
|
+
mfa_secret: str | None) -> dict[str, Any]:
|
|
310
|
+
"""循环处理密码校验之后的后续挑战(MFA 等),直到返回令牌。"""
|
|
311
|
+
while "AuthenticationResult" not in result:
|
|
312
|
+
challenge = result.get("ChallengeName")
|
|
313
|
+
if challenge == "SOFTWARE_TOKEN_MFA":
|
|
314
|
+
if not mfa_secret:
|
|
315
|
+
raise LoginException("账号开启了 TOTP MFA,请在账号配置中补充 mfa_secret")
|
|
316
|
+
logger.info("⮕ Cognito.RespondToAuthChallenge: SOFTWARE_TOKEN_MFA")
|
|
317
|
+
result = self._respond(challenge, {
|
|
318
|
+
"USERNAME": username,
|
|
319
|
+
"SOFTWARE_TOKEN_MFA_CODE": _totp_code(mfa_secret),
|
|
320
|
+
}, result.get("Session"))
|
|
321
|
+
elif challenge == "NEW_PASSWORD_REQUIRED":
|
|
322
|
+
raise LoginException(f"{username} 处于首次登录状态,需要先修改初始密码")
|
|
323
|
+
elif challenge == "MFA_SETUP":
|
|
324
|
+
raise LoginException(f"{username} 尚未绑定 MFA,请先完成绑定并把 TOTP 密钥配到 mfa_secret")
|
|
325
|
+
else:
|
|
326
|
+
# SMS_MFA / EMAIL_OTP / SMS_OTP 等需要人工取码,自动化跑不了
|
|
327
|
+
raise LoginException(f"暂不支持的认证挑战: {challenge},原始响应: {result}")
|
|
328
|
+
return result
|
|
329
|
+
|
|
330
|
+
@staticmethod
|
|
331
|
+
def _to_tokens(result: dict[str, Any], username: str) -> CognitoTokens:
|
|
332
|
+
"""把 AuthenticationResult 转成 CognitoTokens。"""
|
|
333
|
+
auth_result = result.get("AuthenticationResult")
|
|
334
|
+
if not auth_result:
|
|
335
|
+
raise LoginException(f"响应中没有 AuthenticationResult: {result}")
|
|
336
|
+
return CognitoTokens(
|
|
337
|
+
access_token=auth_result["AccessToken"],
|
|
338
|
+
id_token=auth_result.get("IdToken", ""),
|
|
339
|
+
refresh_token=auth_result.get("RefreshToken", ""),
|
|
340
|
+
expires_in=auth_result.get("ExpiresIn", 0),
|
|
341
|
+
token_type=auth_result.get("TokenType", "Bearer"),
|
|
342
|
+
username=username,
|
|
343
|
+
)
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
if __name__ == '__main__':
|
|
347
|
+
f = CognitoAuth("ap-southeast-1_edLQ0pSM0","3rvhpl9p4u9l9ftt5rehh35cg6")
|
|
348
|
+
f.login("payment-partner01@yopmail.net","Password11@","VMD4VZKST4AT3YILODJ7GCCHR4E2WC25D5NKYWLCA7LKLZS7PWIQ")
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
"""
|
|
2
|
+
通用工具模块
|
|
3
|
+
|
|
4
|
+
提供项目中常用的通用工具函数和类,包括:
|
|
5
|
+
- 单例模式的 Faker 封装
|
|
6
|
+
- 验证码生成(2FA)
|
|
7
|
+
- 数字/字符串格式判断与转换(中文数字、特殊符号清理)
|
|
8
|
+
- 时间戳获取与转换
|
|
9
|
+
- 进制转换(16进制与字节互转)
|
|
10
|
+
- URL 编解码
|
|
11
|
+
- 单例装饰器
|
|
12
|
+
- 字符串命名格式转换
|
|
13
|
+
- 应用列表获取等
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
import base64
|
|
20
|
+
import binascii
|
|
21
|
+
from datetime import datetime,timezone,timedelta
|
|
22
|
+
from urllib.parse import unquote, quote, quote_plus, unquote_plus
|
|
23
|
+
|
|
24
|
+
import pyotp
|
|
25
|
+
import cn2an as c2a
|
|
26
|
+
from typing import Any, Callable
|
|
27
|
+
from faker import Faker
|
|
28
|
+
from framework.settings import CASES_DIR
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SingletonFaker(object):
|
|
32
|
+
"""单例模式的 Faker 封装,确保全局只有一个 Faker 实例"""
|
|
33
|
+
|
|
34
|
+
instance = None
|
|
35
|
+
init_flag = False
|
|
36
|
+
|
|
37
|
+
def __init__(self, locale: str) -> None:
|
|
38
|
+
"""
|
|
39
|
+
初始化 Faker 实例(单例模式,仅首次调用时创建)
|
|
40
|
+
@param locale: 语言区域设置,如 'zh_CN'
|
|
41
|
+
"""
|
|
42
|
+
if self.init_flag:
|
|
43
|
+
return # 已初始化,跳过
|
|
44
|
+
self.faker = Faker(locale)
|
|
45
|
+
|
|
46
|
+
def __new__(cls, *args: Any, **kwargs: Any) -> "SingletonFaker":
|
|
47
|
+
"""确保只创建一个实例(单例模式)"""
|
|
48
|
+
if cls.instance is None:
|
|
49
|
+
cls.instance = super().__new__(cls)
|
|
50
|
+
return cls.instance
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def generate_2fa_code(secret_key: str) -> str:
|
|
54
|
+
"""
|
|
55
|
+
获取基于 TOTP 的 2FA 验证码
|
|
56
|
+
@param secret_key: 密钥字符串
|
|
57
|
+
@return: 当前时间步的 2FA 验证码
|
|
58
|
+
"""
|
|
59
|
+
current_time = int(time.time()) # 当前秒级时间戳
|
|
60
|
+
totp = pyotp.TOTP(secret_key)
|
|
61
|
+
google_code = totp.at(current_time)
|
|
62
|
+
|
|
63
|
+
return google_code
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def is_digit(string: str) -> re.Match | None:
|
|
67
|
+
"""
|
|
68
|
+
判断字符串是否为数字(支持负数和小数)
|
|
69
|
+
@param string: 待检测字符串
|
|
70
|
+
@return: 匹配成功返回 re.Match 对象,否则返回 None
|
|
71
|
+
"""
|
|
72
|
+
digit_re = re.compile(r'^-?[0-9.]+$')
|
|
73
|
+
return digit_re.search(string)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def an2cn(integer: int) -> str:
|
|
77
|
+
"""
|
|
78
|
+
阿拉伯数字转中文数字
|
|
79
|
+
@param integer: 阿拉伯数字
|
|
80
|
+
@return: 中文数字字符串
|
|
81
|
+
"""
|
|
82
|
+
return c2a.an2cn(integer)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def cn2an(string: str) -> int | float:
|
|
86
|
+
"""
|
|
87
|
+
中文数字转阿拉伯数字
|
|
88
|
+
@param string: 中文数字字符串
|
|
89
|
+
@return: 阿拉伯数字
|
|
90
|
+
"""
|
|
91
|
+
return c2a.cn2an(string)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def clean_symbol(text: str) -> str:
|
|
95
|
+
"""
|
|
96
|
+
清除字符串中的特殊符号
|
|
97
|
+
@param text: 原始字符串
|
|
98
|
+
@return: 去除特殊符号后的字符串
|
|
99
|
+
"""
|
|
100
|
+
return re.sub('[’!"#$`%&\':|*+~·,-./:;<=「」>@,。?★、…—?“”‘![\\]^_{}~]+', "", text)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def get_long_timestamp(int_type: bool = False) -> int | str:
|
|
104
|
+
"""
|
|
105
|
+
获取毫秒级时间戳
|
|
106
|
+
@param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
|
|
107
|
+
@return: 毫秒级时间戳
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
if int_type:
|
|
111
|
+
return int(time.time() * 1000)
|
|
112
|
+
return str(int(time.time() * 1000))
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_short_timestamp(int_type: bool = False) -> int | str:
|
|
116
|
+
"""
|
|
117
|
+
获取秒级时间戳
|
|
118
|
+
@param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
|
|
119
|
+
@return: 秒级时间戳
|
|
120
|
+
"""
|
|
121
|
+
if int_type:
|
|
122
|
+
return int(time.time())
|
|
123
|
+
return str(int(time.time()))
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def get_current_datetime() -> str:
|
|
127
|
+
"""
|
|
128
|
+
获取当前日期和时间字符串,格式为 2023-02-19 08:31:51
|
|
129
|
+
@return: 格式化的日期时间字符串
|
|
130
|
+
"""
|
|
131
|
+
return time.strftime("%Y-%m-%d %X")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def get_current_date() -> str:
|
|
135
|
+
"""
|
|
136
|
+
获取当前日期字符串,格式为 2023-02-19
|
|
137
|
+
@return: 格式化的日期字符串
|
|
138
|
+
"""
|
|
139
|
+
return time.strftime("%Y-%m-%d")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def timestamp2datetime(timestamp: int | str) -> datetime:
|
|
143
|
+
"""
|
|
144
|
+
时间戳转日期时间对象
|
|
145
|
+
@param timestamp: 时间戳(int 或 str 类型)
|
|
146
|
+
@return: datetime 对象
|
|
147
|
+
"""
|
|
148
|
+
if isinstance(timestamp, int):
|
|
149
|
+
timestamp = str(timestamp) # 统一转字符串处理
|
|
150
|
+
timestamp = timestamp[:10] # 截取前10位(秒级)
|
|
151
|
+
return datetime.fromtimestamp(int(timestamp))
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def timestamp2date(timestamp: int | str) -> str:
|
|
155
|
+
"""
|
|
156
|
+
时间戳转日期字符串
|
|
157
|
+
@param timestamp: 时间戳(int 或 str 类型)
|
|
158
|
+
@return: 格式化日期字符串,如 2023-02-19
|
|
159
|
+
"""
|
|
160
|
+
if isinstance(timestamp, int):
|
|
161
|
+
timestamp = str(timestamp) # 统一转字符串处理
|
|
162
|
+
timestamp = timestamp[:10] # 截取前10位(秒级)
|
|
163
|
+
return time.strftime("%Y-%m-%d", time.localtime(int(timestamp)))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def valid_hex_format(s: str) -> bool:
|
|
167
|
+
"""
|
|
168
|
+
判断字符串是否为合法的 16 进制格式
|
|
169
|
+
@param s: 待检测字符串
|
|
170
|
+
@return: 合法返回 True,否则返回 False
|
|
171
|
+
"""
|
|
172
|
+
hex_re = re.compile(r"^[0-9a-fA-F]+$")
|
|
173
|
+
if hex_re.match(s):
|
|
174
|
+
return True
|
|
175
|
+
return False
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def valid_b64_format(s: str) -> bool:
|
|
179
|
+
"""
|
|
180
|
+
判断字符串是否为合法的 Base64 编码格式
|
|
181
|
+
|
|
182
|
+
通过 base64.b64decode 的 validate 参数严格校验
|
|
183
|
+
@param s: 待检测字符串
|
|
184
|
+
@return: 合法返回 True,否则返回 False
|
|
185
|
+
"""
|
|
186
|
+
try:
|
|
187
|
+
if not isinstance(s, str):
|
|
188
|
+
return False
|
|
189
|
+
base64.b64decode(s, validate=True)
|
|
190
|
+
return True
|
|
191
|
+
except (binascii.Error, ValueError):
|
|
192
|
+
# 捕获 base64 解码异常和值错误
|
|
193
|
+
return False
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def hex_to_bytes(hex_str: str) -> bytes:
|
|
197
|
+
"""
|
|
198
|
+
16 进制字符串转字节串
|
|
199
|
+
@param hex_str: 16 进制字符串
|
|
200
|
+
@return: 字节串
|
|
201
|
+
"""
|
|
202
|
+
return binascii.a2b_hex(hex_str).strip()
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def bytes_to_hex(byte: bytes) -> bytes:
|
|
206
|
+
"""
|
|
207
|
+
字节串转 16 进制字符串
|
|
208
|
+
@param byte: 字节串
|
|
209
|
+
@return: 16 进制格式的字节串
|
|
210
|
+
"""
|
|
211
|
+
return binascii.b2a_hex(byte)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def url_encode(string: str, use_quote_plus: bool = False, encoding: str = "utf-8") -> str:
|
|
215
|
+
"""
|
|
216
|
+
URL 编码
|
|
217
|
+
@param string: 待编码的字符串
|
|
218
|
+
@param use_quote_plus: 若为 True,使用 quote_plus 编码(空格转为 +)
|
|
219
|
+
@param encoding: 编码格式,默认 utf-8
|
|
220
|
+
@return: URL 编码后的字符串
|
|
221
|
+
"""
|
|
222
|
+
if use_quote_plus:
|
|
223
|
+
return quote_plus(string, encoding=encoding)
|
|
224
|
+
return quote(string, encoding=encoding)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def url_decode(string: str, use_unquote_plus: bool = False, encoding: str = "utf-8") -> str:
|
|
228
|
+
"""
|
|
229
|
+
URL 解码
|
|
230
|
+
@param string: 待解码的字符串
|
|
231
|
+
@param use_unquote_plus: 若为 True,使用 unquote_plus 解码(+ 转为空格)
|
|
232
|
+
@param encoding: 编码格式,默认 utf-8
|
|
233
|
+
@return: URL 解码后的字符串
|
|
234
|
+
"""
|
|
235
|
+
if use_unquote_plus:
|
|
236
|
+
return unquote_plus(string, encoding=encoding)
|
|
237
|
+
return unquote(string, encoding=encoding)
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def singleton(cls: type) -> Callable[..., Any]:
|
|
241
|
+
"""
|
|
242
|
+
单例模式装饰器
|
|
243
|
+
|
|
244
|
+
用字典保存每个类的唯一实例,确保一个类在整个进程中只被实例化一次
|
|
245
|
+
@param cls: 需要单例化的类
|
|
246
|
+
@return: 返回内部函数 get_instance
|
|
247
|
+
"""
|
|
248
|
+
instances = {}
|
|
249
|
+
|
|
250
|
+
def get_instance(*args, **kwargs):
|
|
251
|
+
"""获取类的单例实例"""
|
|
252
|
+
if cls not in instances:
|
|
253
|
+
instances[cls] = cls(*args, **kwargs) # 首次创建实例
|
|
254
|
+
return instances[cls]
|
|
255
|
+
|
|
256
|
+
return get_instance
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def snake_to_pascal(name: str) -> str:
|
|
260
|
+
"""
|
|
261
|
+
蛇形命名(snake_case)转帕斯卡命名(PascalCase)
|
|
262
|
+
|
|
263
|
+
将字符串按照下划线分割,然后将每个单词的首字母大写,最后连接起来
|
|
264
|
+
@param name: 蛇形命名字符串,如 'hello_world'
|
|
265
|
+
@return: 帕斯卡命名字符串,如 'HelloWorld'
|
|
266
|
+
"""
|
|
267
|
+
return ''.join(word.capitalize() for word in name.split('_'))
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def get_apps() -> list[str]:
|
|
271
|
+
"""
|
|
272
|
+
获取 CASES_DIR 目录下所有应用子目录(排除 __ 和 . 开头的目录)
|
|
273
|
+
|
|
274
|
+
以「有没有用例」而不是「有没有配置目录」来定义 app:config/ 下还放着
|
|
275
|
+
跟 app 无关、只按环境区分的配置(crrm 之类),那些不该被当成被测应用,
|
|
276
|
+
否则会白白走一遍登录初始化、占一个 ${app.} 前缀。
|
|
277
|
+
|
|
278
|
+
@return: 应用名称列表
|
|
279
|
+
"""
|
|
280
|
+
return [name for name in os.listdir(CASES_DIR) if
|
|
281
|
+
os.path.isdir(os.path.join(CASES_DIR, name)) and not name.startswith(("__", "."))]
|
|
282
|
+
|
|
283
|
+
def remove_spaces(s: str) -> str:
|
|
284
|
+
"""
|
|
285
|
+
去掉字符串中的所有空格
|
|
286
|
+
@param s: 原始字符串
|
|
287
|
+
@return: 去掉空格后的字符串
|
|
288
|
+
"""
|
|
289
|
+
return s.replace(" ", "")
|
|
290
|
+
|
|
291
|
+
def now_iso8601(tz_offset_hours: int = 8) -> str:
|
|
292
|
+
"""
|
|
293
|
+
获取当前时间的 ISO8601 格式字符串(带时区偏移)
|
|
294
|
+
@param tz_offset_hours: 时区偏移小时数,默认东八区(+8)
|
|
295
|
+
@return: ISO8601 格式时间字符串,如 2023-02-19T08:31:51+08:00
|
|
296
|
+
"""
|
|
297
|
+
tz = timezone(timedelta(hours=tz_offset_hours))
|
|
298
|
+
return datetime.now(tz).isoformat(timespec='seconds')
|