API 密钥安全管理(专业版)
输入
| 字段 | 必填 | 说明 |
|---|---|---|
| context | 是 | 密钥所在文本/使用描述 |
| location | 是 | code/frontend/log/package/env |
| last_rotate_days | 否 | 距上次轮换天数 |
输出
风险评分(0-100) + 风险项清单 + 建议
Python 引擎(可独立运行)
# -*- coding: utf-8 -*-
import re
LEAK_PREFIX = ["sk_", "skh_", "ghp_", "AKIA", "xoxb-", "sk-", "Bearer "]
def leak_pattern(text):
found = [p for p in LEAK_PREFIX if p in text]
return found
def assess_key(context, location, last_rotate_days=None):
score = 0
risks = []
leaks = leak_pattern(context)
if leaks:
score += 60
risks.append(f"检测到密钥前缀泄露: {len(leaks)}处(仅提示,不展示密钥)")
loc_risk = {"frontend": 80, "code": 60, "log": 90, "package": 70, "env": 10, "vault": 0}
if location in loc_risk:
score += loc_risk[location]
if loc_risk[location] >= 60:
risks.append(f"存储位置高风险({location}),建议改后端环境变量或密钥管理服务")
if last_rotate_days and last_rotate_days > 90:
score += 20
risks.append("密钥超过90天未轮换,建议按平台周期轮换")
score = min(score, 100)
return score, risks
def min_privilege_check(scopes, needed):
extra = [s for s in scopes if s not in needed]
if extra:
return False, f"存在多余权限scope: {extra},建议收紧"
return True, "最小权限符合"
硬性规则
- 不打印/不展示密钥本体,只给结论
- 只做合规治理,不提供绕过/破解
- 轮换周期以平台文档为准
示例
assess_key("my token: skh_abc", "code", 120) → score≥60(泄露)+60(code)+20(轮换),min()截100上限,risks含泄露+高风险位置+轮换建议