背景与价值密钥泄露常见于日志与代码库。统一扫描、掩码与白名单治理可在提交与构建阶段阻断风险并提升可审计性。统一规范白名单:仅允许必要的环境变量暴露到构建与运行态。扫描规则:覆盖常见API Key、私钥与访问令牌模式。掩码策略:日志与告警中统一部分掩码,保留必要的定位信息。阈值门禁:检测超阈值即阻断构建与发布。核心实现检测器与掩码type Detection = { type: string; value: string; index: number }
const detectors: { type: string; re: RegExp }[] = [
{ type: 'stripe_sk', re: /sk_(live|test)_[A-Za-z0-9]{24,}/g },
{ type: 'aws_access_key', re: /AKIA[0-9A-Z]{16}/g },
{ type: 'github_pat', re: /ghp_[A-Za-z0-9]{36}/g },
{ type: 'private_key', re: /-----BEGIN (RSA |EC |)PRIVATE KEY-----[\s\S]*?-----END (RSA |EC |)PRIVATE KEY-----/g }
]
function mask(s: string): string {
if (s.length <= 8) return '***'
const head = s.slice(0, 4)
const tail = s.slice(-4)
return head + '***' + tail
}
function scanText(text: string): Detection[] {
const out: Detection[] = []
for (const d of detectors) {
d.re.lastIndex = 0
let m: RegExpExecArray | null
while ((m = d.re.exec(text))) out.push({ type: d.type, value: m[0], index: m.index })
}
return out
}
环境变量白名单与门禁const envAllow = new Set([
'NODE_ENV',
'CI',
'BUILD_ID',
'DEPLOY_TARGET'
])
type Env = Record<string, string | undefined>
function validateEnv(env: Env): boolean {
for (const k of Object.keys(env)) if (!envAllow.has(k)) return false
return true
}
function gateByDetections(d: Detection[], maxAllowed: number): boolean {
return d.length <= maxAllowed
}
构建阶段集成范式type Policy = { maxDetections: number; requireEnvWhitelist: boolean }
function auditBuild(texts: string[], env: Env, policy: Policy): { ok: boolean; detections: Detection[] } {
const all: Detection[] = []
for (const t of texts) all.push(...scanText(t))
if (policy.requireEnvWhitelist && !validateEnv(env)) return { ok: false, detections: all }
const ok = gateByDetections(all, policy.maxDetections)
return { ok, detections: all }
}
落地建议将检测器集成到提交钩子与CI流水线,默认阈值为0,检测即阻断。日志与告警统一执行掩码,保留头尾以便快速定位并避免泄露。以白名单方式暴露环境变量,构建产线与运行态分别维护最小集合。定期轮换与吊销密钥,结合集中式密钥管理系统与细粒度访问策略。验证清单是否在提交与构建阶段执行检测并阻断超阈值情况。日志输出是否全部执行掩码且不泄露明文。环境变量暴露是否严格命中白名单。

发表评论 取消回复