From a9c25eb2ac785c46c6ebf7c9ad99afa72186619b Mon Sep 17 00:00:00 2001 From: pmc <740076875@qq.com> Date: Thu, 7 May 2026 17:33:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(01-01):=20=E6=96=B0=E5=A2=9E=20common/util?= =?UTF-8?q?s.py=20=E5=90=AB=20mask=5Ftoken=20=E5=B7=A5=E5=85=B7=E5=87=BD?= =?UTF-8?q?=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 落地 mask_token(token, visible_tail=4, mask_char='*') 通用脱敏函数 - 末 N 位明文保留;空/短输入兜底(短于 visible_tail 时全脱敏防长度泄露) - 不依赖 Django,纯 Python utility,供 Phase 1 Admin / Phase 3 日志 formatter 复用 - 覆盖需求 CRED-01 工具支撑部分 --- qy_lty/common/utils.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 qy_lty/common/utils.py diff --git a/qy_lty/common/utils.py b/qy_lty/common/utils.py new file mode 100644 index 0000000..66e6bd7 --- /dev/null +++ b/qy_lty/common/utils.py @@ -0,0 +1,32 @@ +"""通用工具函数集合。 + +注:common/ 不是 Django app(无 apps.py、未注册到 INSTALLED_APPS), +仅作为跨 app 的纯函数 utility 命名空间使用。 + +不要在此放 Django Model / Manager / 任何依赖 app registry 的对象。 +""" + + +def mask_token(token: str, visible_tail: int = 4, mask_char: str = '*') -> str: + """脱敏长 token / secret,仅保留末 N 位明文。 + + 设计动机:CredentialSlot.access_token 在 Admin 列表 / 查看态需仅显示末 4 位; + Phase 3 阿里云日志 formatter 也将复用本函数。 + + Args: + token: 待脱敏字符串;空字符串 / None 直接返回 '' + visible_tail: 末尾保留明文的字符数(默认 4) + mask_char: 掩码字符(默认 *) + + Returns: + 脱敏后的字符串。例: + 'sk-abcdef1234' -> '*********1234' + '' -> '' + None -> '' + 'abc' -> '***' # 短于 visible_tail 时全部脱敏,不暴露长度信号 + """ + if not token: + return '' + if len(token) <= visible_tail: + return mask_char * len(token) + return mask_char * (len(token) - visible_tail) + token[-visible_tail:]