Files
ai-video-fullstack/backend/services/masking.py
Xin Wang 90e3e8a0c0 Refactor backend to support interface-definition driven model resources
- Introduce a new model structure for managing interface definitions and model resources, enhancing the backend's capability to handle various service integrations.
- Update the Makefile to reflect changes in database seeding and resource management commands.
- Remove the deprecated credentials management routes and replace them with a unified model registry API.
- Modify existing routes and schemas to align with the new model structure, ensuring seamless integration with the frontend.
- Enhance database seeding scripts to populate new model resources and their configurations.
- Update README documentation to reflect the new architecture and usage instructions for model resources and interface definitions.
2026-06-14 19:36:12 +08:00

48 lines
1.6 KiB
Python

"""API Key 打码 / 写时哨兵(抄 dograh masking.py + merge.py 思路)。
- mask:返回前端时把真 key 变成 sk-****1234,真 key 永不出后端
- is_masked:判断前端回传的是不是打码占位符
- resolve_incoming_key:前端回传若是占位符 → 保留旧值;否则用新值
"""
MASK_VISIBLE_TAIL = 4
def mask(api_key: str) -> str:
if not api_key:
return ""
if len(api_key) <= MASK_VISIBLE_TAIL:
return "****"
return f"{api_key[:2]}****{api_key[-MASK_VISIBLE_TAIL:]}"
def is_masked(value: str) -> bool:
return "****" in (value or "")
def resolve_incoming_key(incoming: str | None, stored: str) -> str:
"""写入时决定最终 key:占位符/空 → 保留旧;否则用新。"""
if incoming is None or incoming == "" or is_masked(incoming):
return stored
return incoming
def mask_secrets(value):
"""Recursively mask every scalar in a model resource secrets object."""
if isinstance(value, dict):
return {key: mask_secrets(item) for key, item in value.items()}
if isinstance(value, list):
return [mask_secrets(item) for item in value]
return mask(str(value)) if value is not None else ""
def merge_secrets(incoming: dict, stored: dict) -> dict:
"""Merge secret fields while treating masked/empty values as keep-existing."""
result = dict(stored or {})
for key, value in (incoming or {}).items():
if isinstance(value, dict) and isinstance(result.get(key), dict):
result[key] = merge_secrets(value, result[key])
elif value not in (None, "") and not is_masked(str(value)):
result[key] = value
return result