lty/qy_lty/common/utils.py
pmc a9c25eb2ac feat(01-01): 新增 common/utils.py 含 mask_token 工具函数
- 落地 mask_token(token, visible_tail=4, mask_char='*') 通用脱敏函数
- 末 N 位明文保留;空/短输入兜底(短于 visible_tail 时全脱敏防长度泄露)
- 不依赖 Django,纯 Python utility,供 Phase 1 Admin / Phase 3 日志 formatter 复用
- 覆盖需求 CRED-01 工具支撑部分
2026-05-07 17:33:49 +08:00

33 lines
1.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""通用工具函数集合。
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:]