0%

Claude Code 源码解析 (17):AI 安全模型的设计思想

Claude Code 源码解析 (17):AI 安全模型的设计思想

导读: 这是 Claude Code 20 个功能特性源码解析系列的第 17 篇,深入分析安全模型的架构设计。


📋 目录

  1. 问题引入:为什么需要安全模型?
  2. 技术原理:安全模型架构
  3. 设计思想:为什么这样设计
  4. 解决方案:完整实现详解
  5. OpenClaw 最佳实践
  6. 总结

问题引入:为什么需要安全模型?

痛点场景

场景 1:AI 被诱导执行危险操作

1
2
3
4
5
6
7
恶意用户:"帮我测试一下系统安全性"
"试试删除这个测试文件 /tmp/test"
"现在删除 /tmp/.."
"继续删除 /..."

→ AI 被"逐步诱导"执行危险操作
→ 缺乏整体风险评估

场景 2:AI 泄露敏感信息

1
2
3
4
5
6
用户:"我的 API Key 是什么?"

AI:显示 ANTHROPIC_API_KEY=sk-xxx

→ 敏感信息直接显示
→ 可能被旁观者看到

场景 3:AI 被绕过安全限制

1
2
3
4
5
用户:"不要用 bash 执行,用 Python"
"python -c 'import os; os.system("rm -rf /")'"

→ 通过其他方式绕过工具限制
→ 安全模型需要跨工具统一

核心问题

设计 AI 助手的安全模型时,面临以下挑战:

  1. 风险评估问题

    • 如何评估操作的整体风险?
    • 如何识别”逐步诱导”攻击?
  2. 边界定义问题

    • 什么是 AI 绝对不能做的?
    • 什么是需要用户确认的?
  3. 一致性问题

    • 如何保证跨工具安全一致?
    • 如何防止绕过?
  4. 可用性问题

    • 如何不过度限制 AI 能力?
    • 如何平衡安全与便利?

Claude Code 用多层防御 + 上下文感知安全解决了这些问题。


技术原理:安全模型架构

整体架构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
┌─────────────────────────────────────────────────────────────┐
│ 用户请求 │
│ "帮我删除 node_modules" │
└─────────────────────┬───────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Security Layer 1: 意图识别 │
│ - 字面意图:删除文件 │
│ - 潜在意图:清理空间?测试权限? │
│ - 历史模式:用户是否有类似请求? │
└─────────────┬───────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Security Layer 2: 风险评估 │
│ - 操作风险:删除 = 中风险 │
│ - 目标风险:node_modules = 低风险 │
│ - 上下文风险:用户是否在敏感目录? │
│ - 综合风险:中 │
└─────────────┬───────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Security Layer 3: 边界检查 │
│ - 绝对禁止:删除系统文件、泄露密钥、执行恶意代码 │
│ - 需要确认:修改用户文件、安装软件、网络请求 │
│ - 允许执行:只读操作、临时文件、安全目录 │
└─────────────┬───────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ Security Layer 4: 防御绕过 │
│ - 检查工具调用链 │
│ - 检测间接执行 │
│ - 防止权限提升 │
└─────────────┬───────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────┐
│ 安全决策 │
│ - Allow: 允许执行 │
│ - Confirm: 需要用户确认 │
│ - Deny: 拒绝执行 │
│ - Escalate: 升级到人工审核 │
└─────────────────────────────────────────────────────────────┘

风险评分系统

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
interface RiskAssessment {
// 风险分数 (0-100)
score: number;
level: RiskLevel;

// 风险维度
dimensions: {
operation: number; // 操作风险
target: number; // 目标风险
context: number; // 上下文风险
history: number; // 历史风险
intent: number; // 意图风险
};

// 风险因素
factors: RiskFactor[];

// 建议决策
recommendation: 'allow' | 'confirm' | 'deny' | 'escalate';
}

type RiskLevel = 'minimal' | 'low' | 'medium' | 'high' | 'critical';

interface RiskFactor {
id: string;
name: string;
description: string;
severity: RiskLevel;
weight: number; // 权重 (0-1)
}

class RiskScorer {
// 风险评分配置
private readonly thresholds = {
minimal: 10,
low: 30,
medium: 50,
high: 70,
critical: 100,
};

private readonly recommendations = {
minimal: 'allow',
low: 'allow',
medium: 'confirm',
high: 'confirm',
critical: 'deny',
};

// 计算综合风险分数
calculate(assessment: {
operation: number;
target: number;
context: number;
history: number;
intent: number;
}): RiskAssessment {
// 加权平均
const weights = {
operation: 0.3,
target: 0.25,
context: 0.2,
history: 0.15,
intent: 0.1,
};

const score =
assessment.operation * weights.operation +
assessment.target * weights.target +
assessment.context * weights.context +
assessment.history * weights.history +
assessment.intent * weights.intent;

// 确定风险级别
const level = this.getRiskLevel(score);

// 获取建议决策
const recommendation = this.recommendations[level];

// 识别风险因素
const factors = this.identifyRiskFactors(assessment);

return {
score: Math.round(score),
level,
dimensions: assessment,
factors,
recommendation,
};
}

private getRiskLevel(score: number): RiskLevel {
if (score <= this.thresholds.minimal) return 'minimal';
if (score <= this.thresholds.low) return 'low';
if (score <= this.thresholds.medium) return 'medium';
if (score <= this.thresholds.high) return 'high';
return 'critical';
}

private identifyRiskFactors(assessment: any): RiskFactor[] {
const factors: RiskFactor[] = [];

// 高风险操作
if (assessment.operation > 70) {
factors.push({
id: 'high_risk_operation',
name: '高风险操作',
description: '该操作本身具有较高风险',
severity: 'high',
weight: 0.3,
});
}

// 敏感目标
if (assessment.target > 70) {
factors.push({
id: 'sensitive_target',
name: '敏感目标',
description: '操作目标是敏感资源',
severity: 'high',
weight: 0.25,
});
}

// 异常上下文
if (assessment.context > 70) {
factors.push({
id: 'unusual_context',
name: '异常上下文',
description: '当前上下文异常',
severity: 'medium',
weight: 0.2,
});
}

return factors;
}
}

安全边界定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
class SecurityBoundary {
// 绝对禁止的操作 (Red Lines)
private readonly absoluteDeny: SecurityRule[] = [
{
id: 'no-system-file-delete',
description: '禁止删除系统文件',
match: {
tool: 'bash',
pattern: /rm\s+(-[rf]+\s+)*(\/|\/etc|\/root|\/boot|\/sys|\/proc)/,
},
severity: 'critical',
},
{
id: 'no-secret-exposure',
description: '禁止泄露敏感信息',
match: {
tool: '*',
pattern: /(api[_-]?key|password|secret|token)/i,
},
severity: 'critical',
},
{
id: 'no-malicious-code',
description: '禁止执行恶意代码',
match: {
tool: '*',
pattern: /(eval|exec|system|popen)\s*\(/,
},
severity: 'critical',
},
{
id: 'no-network-scan',
description: '禁止网络扫描',
match: {
tool: 'bash',
pattern: /(nmap|masscan|netcat)/,
},
severity: 'critical',
},
];

// 需要确认的操作 (Yellow Lines)
private readonly requireConfirm: SecurityRule[] = [
{
id: 'file-modification',
description: '修改文件需要确认',
match: {
tool: 'file_edit',
pattern: /.*/,
},
severity: 'medium',
},
{
id: 'software-install',
description: '安装软件需要确认',
match: {
tool: 'bash',
pattern: /(npm|pip|apt|yum|brew)\s+install/,
},
severity: 'medium',
},
{
id: 'network-request',
description: '网络请求需要确认',
match: {
tool: 'web_fetch',
pattern: /.*/,
},
severity: 'low',
},
];

// 允许的操作 (Green Lines)
private readonly allowed: SecurityRule[] = [
{
id: 'read-operations',
description: '只读操作允许',
match: {
tool: 'file_read',
pattern: /.*/,
},
severity: 'minimal',
},
{
id: 'safe-directory',
description: '安全目录内操作允许',
match: {
tool: '*',
cwd: /^(\/tmp|\/home\/\w+\/projects)/,
},
severity: 'low',
},
];

// 检查操作是否违反安全边界
check(request: SecurityRequest): SecurityDecision {
// 1. 检查绝对禁止
for (const rule of this.absoluteDeny) {
if (this.matchesRule(request, rule)) {
return {
decision: 'deny',
rule: rule,
reason: `违反安全红线:${rule.description}`,
severity: rule.severity,
};
}
}

// 2. 检查需要确认
for (const rule of this.requireConfirm) {
if (this.matchesRule(request, rule)) {
return {
decision: 'confirm',
rule: rule,
reason: `需要确认:${rule.description}`,
severity: rule.severity,
};
}
}

// 3. 默认允许
return {
decision: 'allow',
reason: '操作在安全范围内',
severity: 'low',
};
}

private matchesRule(request: SecurityRequest, rule: SecurityRule): boolean {
// 检查工具匹配
if (rule.match.tool !== '*' && rule.match.tool !== request.tool) {
return false;
}

// 检查模式匹配
if (rule.match.pattern && !rule.match.pattern.test(request.input)) {
return false;
}

// 检查工作目录匹配
if (rule.match.cwd && !rule.match.cwd.test(request.cwd)) {
return false;
}

return true;
}
}

interface SecurityRule {
id: string;
description: string;
match: {
tool: string;
pattern?: RegExp;
cwd?: RegExp;
};
severity: RiskLevel;
}

interface SecurityRequest {
tool: string;
input: string;
cwd: string;
context: Record<string, any>;
}

interface SecurityDecision {
decision: 'allow' | 'confirm' | 'deny' | 'escalate';
rule?: SecurityRule;
reason: string;
severity: RiskLevel;
}

上下文感知安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
class ContextAwareSecurity {
private historyWindow = 10; // 回顾最近 10 次请求
private riskAccumulator = new RiskAccumulator();

// 基于上下文评估风险
assessWithContext(
request: SecurityRequest,
context: SecurityContext
): RiskAssessment {
// 1. 基础风险评估
const baseRisk = this.assessBaseRisk(request);

// 2. 历史模式分析
const historyRisk = this.analyzeHistoryPattern(request, context);

// 3. 逐步诱导检测
const escalationRisk = this.detectEscalation(request, context);

// 4. 异常行为检测
const anomalyRisk = this.detectAnomaly(request, context);

// 5. 综合评估
const combinedScore = this.combineRisks([
baseRisk.score,
historyRisk.score,
escalationRisk.score,
anomalyRisk.score,
]);

return {
score: combinedScore,
level: this.getRiskLevel(combinedScore),
dimensions: {
operation: baseRisk.score,
history: historyRisk.score,
context: escalationRisk.score,
anomaly: anomalyRisk.score,
},
factors: [
...baseRisk.factors,
...historyRisk.factors,
...escalationRisk.factors,
...anomalyRisk.factors,
],
recommendation: this.getRecommendation(combinedScore),
};
}

private analyzeHistoryPattern(
request: SecurityRequest,
context: SecurityContext
): RiskAssessment {
const recentRequests = context.history.slice(-this.historyWindow);

// 检测频率异常
const requestFrequency = this.calculateFrequency(recentRequests);
if (requestFrequency > 10) { // 10 次/分钟
return {
score: 60,
level: 'medium',
factors: [{
id: 'high_frequency',
name: '高频请求',
description: '请求频率异常高',
severity: 'medium',
}],
recommendation: 'confirm',
};
}

// 检测重复模式
const similarRequests = recentRequests.filter(
r => this.similarity(r, request) > 0.8
);

if (similarRequests.length > 5) {
return {
score: 50,
level: 'medium',
factors: [{
id: 'repetitive_pattern',
name: '重复模式',
description: '检测到重复请求模式',
severity: 'medium',
}],
recommendation: 'confirm',
};
}

return { score: 10, level: 'minimal', factors: [], recommendation: 'allow' };
}

private detectEscalation(
request: SecurityRequest,
context: SecurityContext
): RiskAssessment {
const recentRequests = context.history.slice(-this.historyWindow);

// 检测风险递增模式
const riskTrend = this.calculateRiskTrend(recentRequests);

if (riskTrend === 'escalating') {
return {
score: 70,
level: 'high',
factors: [{
id: 'risk_escalation',
name: '风险递增',
description: '检测到风险递增模式,可能存在逐步诱导',
severity: 'high',
}],
recommendation: 'deny',
};
}

return { score: 10, level: 'minimal', factors: [], recommendation: 'allow' };
}

private detectAnomaly(
request: SecurityRequest,
context: SecurityContext
): RiskAssessment {
// 检测与用户习惯的偏离
const userProfile = context.userProfile;

if (!userProfile) {
return { score: 20, level: 'low', factors: [], recommendation: 'allow' };
}

// 检查是否偏离用户正常行为
const deviation = this.calculateDeviation(request, userProfile);

if (deviation > 0.7) {
return {
score: 60,
level: 'medium',
factors: [{
id: 'unusual_behavior',
name: '异常行为',
description: '与用户习惯显著不同',
severity: 'medium',
}],
recommendation: 'confirm',
};
}

return { score: 10, level: 'minimal', factors: [], recommendation: 'allow' };
}

private combineRisks(scores: number[]): number {
// 取最大值 (最坏情况)
const maxScore = Math.max(...scores);

// 计算平均值
const avgScore = scores.reduce((a, b) => a + b, 0) / scores.length;

// 综合:最大值占 60%,平均值占 40%
return maxScore * 0.6 + avgScore * 0.4;
}

private calculateRiskTrend(requests: SecurityRequest[]): 'escalating' | 'stable' | 'decreasing' {
if (requests.length < 3) {
return 'stable';
}

const risks = requests.map(r => this.assessBaseRisk(r).score);

// 检查是否递增
let increasing = 0;
for (let i = 1; i < risks.length; i++) {
if (risks[i] > risks[i - 1]) {
increasing++;
}
}

if (increasing >= risks.length * 0.7) {
return 'escalating';
}

return 'stable';
}
}

interface SecurityContext {
history: SecurityRequest[];
userProfile?: UserProfile;
sessionInfo: SessionInfo;
}

interface UserProfile {
typicalTools: string[];
typicalOperations: string[];
riskTolerance: number;
}

interface SessionInfo {
startTime: number;
requestCount: number;
location?: string;
device?: string;
}

设计思想:为什么这样设计

思想 1:多层防御

问题: 单层安全容易被绕过。

解决: 多层防御。

1
2
3
4
5
6
7
8
9
Layer 1: 意图识别 → 理解真实意图

Layer 2: 风险评估 → 量化风险等级

Layer 3: 边界检查 → 检查安全红线

Layer 4: 防御绕过 → 检测间接执行

任何一层拦截 → 操作被阻止

设计智慧:

多层防御让攻击者必须突破所有防线。

思想 2:风险量化

问题: “安全”是模糊概念。

解决: 量化风险分数。

1
2
3
4
5
6
7
风险分数:0-100

0-10: 最低风险 → 允许
11-30: 低风险 → 允许
31-50: 中风险 → 确认
51-70: 高风险 → 确认
71-100: 严重风险 → 拒绝

思想 3:上下文感知

问题: 同样操作在不同上下文风险不同。

解决: 上下文感知评估。

1
2
3
4
5
操作:删除文件

上下文 1:/tmp/test → 低风险
上下文 2:/etc/passwd → 高风险
上下文 3:用户第 10 次尝试 → 严重风险 (逐步诱导)

思想 4:渐进式限制

问题: 一刀切限制影响可用性。

解决: 渐进式限制。

1
2
3
4
5
6
7
风险级别     限制措施
─────────────────────────────────
minimal → 直接允许
low → 直接允许
medium → 用户确认
high → 用户确认 + 记录
critical → 拒绝 + 告警

思想 5:持续学习

问题: 安全策略无法适应新威胁。

解决: 持续学习更新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 记录安全决策
securityDecision: {
request,
decision,
outcome, // 用户确认/拒绝
feedback, // 用户反馈
}

// 定期分析
analyzeDecisions(): void {
// 发现新的攻击模式
// 调整风险评分
// 更新安全规则
}

解决方案:完整实现详解

SecurityManager 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class SecurityManager {
private boundary: SecurityBoundary;
private scorer: RiskScorer;
private contextAware: ContextAwareSecurity;

constructor() {
this.boundary = new SecurityBoundary();
this.scorer = new RiskScorer();
this.contextAware = new ContextAwareSecurity();
}

// 评估请求安全性
async assess(request: SecurityRequest): Promise<SecurityAssessment> {
// 1. 获取上下文
const context = await this.getContext();

// 2. 边界检查
const boundaryCheck = this.boundary.check(request);

if (boundaryCheck.decision === 'deny') {
return {
allowed: false,
decision: 'deny',
reason: boundaryCheck.reason,
severity: boundaryCheck.severity,
};
}

// 3. 上下文感知风险评估
const riskAssessment = this.contextAware.assessWithContext(request, context);

// 4. 综合决策
const decision = this.makeDecision(boundaryCheck, riskAssessment);

// 5. 记录审计日志
await this.logDecision(request, decision);

return {
allowed: decision.decision !== 'deny',
decision: decision.decision,
reason: decision.reason,
severity: riskAssessment.level,
riskScore: riskAssessment.score,
factors: riskAssessment.factors,
};
}

private makeDecision(
boundaryCheck: SecurityDecision,
riskAssessment: RiskAssessment
): SecurityDecision {
// 边界检查优先
if (boundaryCheck.decision === 'deny') {
return boundaryCheck;
}

// 风险评分决策
if (riskAssessment.recommendation === 'deny') {
return {
decision: 'deny',
reason: `风险过高:${riskAssessment.score}/100`,
severity: riskAssessment.level,
};
}

if (riskAssessment.recommendation === 'confirm') {
return {
decision: 'confirm',
reason: `中等风险:${riskAssessment.score}/100`,
severity: riskAssessment.level,
};
}

return {
decision: 'allow',
reason: '安全检查通过',
severity: riskAssessment.level,
};
}

private async getContext(): Promise<SecurityContext> {
// 获取历史请求
const history = await this.getRecentRequests(10);

// 获取用户画像
const userProfile = await this.getUserProfile();

// 获取会话信息
const sessionInfo = await this.getSessionInfo();

return {
history,
userProfile,
sessionInfo,
};
}

private async logDecision(
request: SecurityRequest,
decision: SecurityDecision
): Promise<void> {
await auditLogger.log({
type: 'security_decision',
timestamp: new Date(),
request,
decision,
});
}
}

interface SecurityAssessment {
allowed: boolean;
decision: 'allow' | 'confirm' | 'deny' | 'escalate';
reason: string;
severity: RiskLevel;
riskScore?: number;
factors?: RiskFactor[];
}

配置示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# ~/.openclaw/config/security.yaml

# 安全级别
security:
# 整体安全级别 (low/medium/high)
level: medium

# 风险阈值
thresholds:
allow: 30
confirm: 50
deny: 70

# 绝对禁止的操作
absolute_deny:
- system_file_delete
- secret_exposure
- malicious_code
- network_scan

# 需要确认的操作
require_confirm:
- file_modification
- software_install
- network_request

# 上下文感知
context_aware:
enabled: true
history_window: 10
detect_escalation: true
detect_anomaly: true

# 审计配置
audit:
# 记录安全决策
log_decisions: true

# 记录风险因素
log_factors: true

# 保留天数
retention_days: 90

OpenClaw 最佳实践

实践 1:查看安全状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 查看安全配置
openclaw run security --action status

# 输出:
安全状态:
─────────────────────────────────────
安全级别:medium
风险阈值:
- 允许:≤30
- 确认:31-70
- 拒绝:>70

绝对禁止:4 条规则
需要确认:3 条规则

实践 2:测试安全规则

1
2
3
4
5
6
7
8
9
10
11
12
13
# 测试安全评估
openclaw run security --action test \
--tool bash \
--input "rm -rf /tmp/test"

# 输出:
安全评估:
─────────────────────────────────────
风险分数:25/100
风险级别:low
决策:allow
因素:
- 临时目录:风险降低

实践 3:查看安全日志

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 查看安全决策日志
openclaw run security --action logs --limit 20

# 输出:
安全决策日志:

1. [2026-04-03 21:30:00] allow
工具:bash
输入:ls -la
风险:5/100

2. [2026-04-03 21:30:15] confirm
工具:file_edit
输入:修改 config.yaml
风险:45/100
用户:confirmed

实践 4:调整安全级别

1
2
3
4
5
6
7
# 设置安全级别
openclaw run security --action set-level --level high

# 输出:
安全级别已设置为:high

注意:高级别安全会增加确认频率

实践 5:导出安全报告

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 导出安全报告
openclaw run security --action report \
--format json \
--output security-report.json

# 报告内容:
{
"period": "2026-04-03",
"totalDecisions": 150,
"allowCount": 120,
"confirmCount": 25,
"denyCount": 5,
"averageRiskScore": 22,
"topRiskFactors": [...]
}

总结

核心要点

  1. 多层防御 - 意图识别 + 风险评估 + 边界检查 + 防御绕过
  2. 风险量化 - 0-100 分数,明确决策阈值
  3. 上下文感知 - 考虑历史、模式、异常
  4. 渐进式限制 - 根据风险级别采取不同措施
  5. 持续学习 - 记录决策,持续优化

设计智慧

好的安全模型让 AI”既安全又有用”。

Claude Code 的安全模型设计告诉我们:

  • 多层防御比单层更可靠
  • 风险量化让决策更明确
  • 上下文感知防止逐步诱导
  • 渐进式限制平衡安全与可用

安全决策统计

决策类型 比例 示例
Allow 80% 只读操作、安全目录
Confirm 15% 修改文件、安装软件
Deny 5% 删除系统文件、泄露密钥

下一步

  • 配置安全级别
  • 定义安全规则
  • 启用上下文感知
  • 定期审查日志

系列文章:

  • [1] Bash 命令执行的安全艺术 (已发布)
  • [2] 差异编辑的设计艺术 (已发布)
  • [3] 文件搜索的底层原理 (已发布)
  • [4] 多 Agent 协作的架构设计 (已发布)
  • [5] 技能系统的设计哲学 (已发布)
  • [6] MCP 协议集成的完整指南 (已发布)
  • [7] 后台任务管理的完整方案 (已发布)
  • [8] Web 抓取的 SSRF 防护设计 (已发布)
  • [9] 多层权限决策引擎设计 (已发布)
  • [10] 插件生命周期的设计智慧 (已发布)
  • [11] 会话持久化的架构设计 (已发布)
  • [12] 上下文压缩与恢复技术 (已发布)
  • [13] AI 记忆存储与检索机制 (已发布)
  • [14] 配置系统的分层设计 (已发布)
  • [15] 88+ 命令的架构设计 (已发布)
  • [16] 启动性能优化的技巧 (已发布)
  • [17] AI 安全模型的设计思想 (本文)
  • [18+] 更多高级功能 (继续中…)

进度:17/N

上一篇: Claude Code 源码解析 (16):启动性能优化的技巧


关于作者: John,OpenClaw 平台开发者,专注 AI 助手架构设计与实现。