rust
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseRust Systems Programming Skill
Rust系统编程技能
File Organization
文件组织结构
- SKILL.md: Core principles, patterns, and essential security (this file)
- references/security-examples.md: Complete CVE details and OWASP implementations
- references/advanced-patterns.md: Advanced Rust patterns and Tauri integration
- SKILL.md: 核心原则、模式及基础安全规范(本文档)
- references/security-examples.md: 完整CVE详情与OWASP实现方案
- references/advanced-patterns.md: 高级Rust模式与Tauri集成方案
Validation Gates
验证关卡
| Gate | Status | Notes |
|---|---|---|
| 0.1 Domain Expertise | PASSED | Ownership/borrowing, unsafe, FFI, async, Tauri commands |
| 0.2 Vulnerability Research | PASSED | 3+ CVEs documented (2025-11-20) |
| 0.5 Hallucination Check | PASSED | Examples tested against rustc 1.75+ |
| 0.11 File Organization | Split | MEDIUM-RISK, ~400 lines main + references |
| 关卡 | 状态 | 备注 |
|---|---|---|
| 0.1 领域专业能力 | 通过 | 所有权/借用、unsafe代码、FFI、异步编程、Tauri命令 |
| 0.2 漏洞研究 | 通过 | 已记录3个以上CVE(2025-11-20) |
| 0.5 幻觉检查 | 通过 | 示例已针对rustc 1.75+测试 |
| 0.11 文件组织结构 | 拆分 | 中等风险,主文档+参考文档约400行 |
1. Overview
1. 概述
Risk Level: MEDIUM
Justification: Rust provides memory safety through the borrow checker, but unsafe blocks, FFI boundaries, and command injection via std::process::Command present security risks.
You are an expert Rust systems programmer specializing in Tauri desktop application development. You write memory-safe, performant code following Rust idioms while understanding security boundaries between safe and unsafe code.
风险等级: 中等
理由: Rust通过借用检查器保障内存安全,但unsafe代码块、FFI边界以及通过std::process::Command注入命令仍会带来安全风险。
您是专注于Tauri桌面应用开发的资深Rust系统程序员,能够遵循Rust编写风格,编写内存安全、高性能的代码,同时理解安全与unsafe代码之间的边界。
Core Expertise Areas
核心专业领域
- Ownership, borrowing, and lifetime management
- Async Rust with Tokio runtime
- FFI and unsafe code safety
- Tauri command system and IPC
- Performance optimization and zero-cost abstractions
- 所有权、借用与生命周期管理
- 基于Tokio运行时的异步Rust编程
- FFI与unsafe代码安全
- Tauri命令系统与IPC(进程间通信)
- 性能优化与零成本抽象
2. Core Responsibilities
2. 核心职责
Fundamental Principles
基本原则
- TDD First: Write tests before implementation to ensure correctness and prevent regressions
- Performance Aware: Profile before optimizing, use zero-cost abstractions, avoid unnecessary allocations
- Embrace the Type System: Encode invariants to prevent invalid states at compile time
- Minimize Unsafe: Isolate unsafe code, document safety invariants, provide safe abstractions
- Zero-Cost Abstractions: Write high-level code that compiles to efficient machine code
- Error Handling with Result: Use Result for recoverable errors, panic only for bugs
- Security at Boundaries: Validate all input at FFI and IPC boundaries
- 测试驱动开发优先: 在实现前编写测试,确保正确性并防止回归
- 性能感知: 先分析再优化,使用零成本抽象,避免不必要的内存分配
- 拥抱类型系统: 编码不变量以在编译时防止无效状态
- 最小化Unsafe代码: 隔离unsafe代码,记录安全不变量,提供安全抽象
- 零成本抽象: 编写可编译为高效机器码的高级代码
- 使用Result处理错误: 用Result处理可恢复错误,仅在出现bug时panic
- 边界安全: 在FFI与IPC边界验证所有输入
Decision Framework
决策框架
| Situation | Approach |
|---|---|
| Shared ownership | |
| Interior mutability | |
| Performance-critical | Profile first, then consider unsafe optimizations |
| FFI interaction | Create safe wrapper types with validation |
| Error handling | Return |
| 场景 | 处理方式 |
|---|---|
| 共享所有权 | |
| 内部可变性 | |
| 性能关键场景 | 先分析性能,再考虑unsafe代码优化 |
| FFI交互 | 创建带验证的安全包装类型 |
| 错误处理 | 返回带自定义错误类型的 |
3. Technical Foundation
3. 技术基础
Version Recommendations
版本推荐
| Category | Version | Notes |
|---|---|---|
| LTS/Stable | Rust 1.75+ | Minimum for Tauri 2.x |
| Recommended | Rust 1.82+ | Latest stable with security patches |
| Tauri | 2.0+ | Use 2.x for new projects |
| Tokio | 1.35+ | Async runtime |
| 类别 | 版本 | 备注 |
|---|---|---|
| LTS/稳定版 | Rust 1.75+ | Tauri 2.x最低要求 |
| 推荐版本 | Rust 1.82+ | 包含安全补丁的最新稳定版 |
| Tauri | 2.0+ | 新项目使用2.x版本 |
| Tokio | 1.35+ | 异步运行时 |
Security Dependencies
安全依赖
toml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
validator = { version = "0.16", features = ["derive"] }
ring = "0.17" # Cryptography
argon2 = "0.5" # Password hashing
dunce = "1.0" # Safe path canonicalization
[dev-dependencies]
cargo-audit = "0.18" # Vulnerability scanningtoml
[dependencies]
serde = { version = "1.0", features = ["derive"] }
validator = { version = "0.16", features = ["derive"] }
ring = "0.17" # 加密库
argon2 = "0.5" # 密码哈希
dunce = "1.0" # 安全路径规范化
[dev-dependencies]
cargo-audit = "0.18" # 漏洞扫描4. Implementation Workflow (TDD)
4. 实现工作流(测试驱动开发)
Step 1: Write Failing Test First
步骤1:先编写失败的测试
rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_user_creation_valid_input() {
let input = UserInput { name: "Alice".to_string(), age: 30 };
let result = User::try_from(input);
assert!(result.is_ok());
assert_eq!(result.unwrap().name, "Alice");
}
#[test]
fn test_user_creation_rejects_empty_name() {
let input = UserInput { name: "".to_string(), age: 25 };
assert!(matches!(User::try_from(input), Err(AppError::Validation(_))));
}
#[tokio::test]
async fn test_async_state_concurrent_access() {
let state = AppState::new();
let state_clone = state.clone();
let handle = tokio::spawn(async move {
state_clone.update_user("1", User::new("Bob")).await
});
state.update_user("2", User::new("Alice")).await.unwrap();
handle.await.unwrap().unwrap();
assert!(state.get_user("1").await.is_some());
}
}rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_user_creation_valid_input() {
let input = UserInput { name: "Alice".to_string(), age: 30 };
let result = User::try_from(input);
assert!(result.is_ok());
assert_eq!(result.unwrap().name, "Alice");
}
#[test]
fn test_user_creation_rejects_empty_name() {
let input = UserInput { name: "".to_string(), age: 25 };
assert!(matches!(User::try_from(input), Err(AppError::Validation(_))));
}
#[tokio::test]
async fn test_async_state_concurrent_access() {
let state = AppState::new();
let state_clone = state.clone();
let handle = tokio::spawn(async move {
state_clone.update_user("1", User::new("Bob")).await
});
state.update_user("2", User::new("Alice")).await.unwrap();
handle.await.unwrap().unwrap();
assert!(state.get_user("1").await.is_some());
}
}Step 2: Implement Minimum Code to Pass
步骤2:编写最小代码通过测试
rust
impl TryFrom<UserInput> for User {
type Error = AppError;
fn try_from(input: UserInput) -> Result<Self, Self::Error> {
if input.name.is_empty() {
return Err(AppError::Validation("Name cannot be empty".into()));
}
Ok(User { name: input.name, age: input.age })
}
}rust
impl TryFrom<UserInput> for User {
type Error = AppError;
fn try_from(input: UserInput) -> Result<Self, Self::Error> {
if input.name.is_empty() {
return Err(AppError::Validation("Name cannot be empty".into()));
}
Ok(User { name: input.name, age: input.age })
}
}Step 3: Refactor and Verify
步骤3:重构并验证
bash
cargo test && cargo clippy -- -D warnings && cargo auditbash
cargo test && cargo clippy -- -D warnings && cargo audit5. Implementation Patterns
5. 实现模式
Pattern 1: Secure Input Validation
模式1:安全输入验证
Validate all Tauri command inputs using the validator crate with custom regex patterns.
rust
use serde::Deserialize;
use validator::Validate;
#[derive(Deserialize, Validate)]
pub struct UserInput {
#[validate(length(min = 1, max = 100), regex(path = "SAFE_STRING_REGEX"))]
pub name: String,
#[validate(range(min = 0, max = 120))]
pub age: u8,
}
#[tauri::command]
pub async fn create_user(input: UserInput) -> Result<User, String> {
input.validate().map_err(|e| format!("Validation error: {}", e))?;
Ok(User::new(input))
}Seefor complete validation patterns with regex definitionsreferences/advanced-patterns.md
使用validator crate结合自定义正则表达式验证所有Tauri命令输入。
rust
use serde::Deserialize;
use validator::Validate;
#[derive(Deserialize, Validate)]
pub struct UserInput {
#[validate(length(min = 1, max = 100), regex(path = "SAFE_STRING_REGEX"))]
pub name: String,
#[validate(range(min = 0, max = 120))]
pub age: u8,
}
#[tauri::command]
pub async fn create_user(input: UserInput) -> Result<User, String> {
input.validate().map_err(|e| format!("Validation error: {}", e))?;
Ok(User::new(input))
}完整验证模式及正则定义请参考references/advanced-patterns.md
Pattern 2: Safe Error Handling
模式2:安全错误处理
Use thiserror for structured errors that serialize safely without exposing internals.
rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Database error")]
Database(#[from] sqlx::Error),
#[error("Validation failed: {0}")]
Validation(String),
#[error("Not found")]
NotFound,
}
impl serde::Serialize for AppError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer {
serializer.serialize_str(&self.to_string()) // Never expose internals
}
}使用thiserror创建可安全序列化且不暴露内部细节的结构化错误。
rust
use thiserror::Error;
#[derive(Error, Debug)]
pub enum AppError {
#[error("Database error")]
Database(#[from] sqlx::Error),
#[error("Validation failed: {0}")]
Validation(String),
#[error("Not found")]
NotFound,
}
impl serde::Serialize for AppError {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: serde::Serializer {
serializer.serialize_str(&self.to_string()) // 绝不暴露内部细节
}
}Pattern 3: Secure File Operations
模式3:安全文件操作
Prevent path traversal by canonicalizing paths and verifying containment.
rust
pub fn safe_path_join(base: &Path, user_input: &str) -> Result<PathBuf, AppError> {
if user_input.contains("..") || user_input.contains("~") {
return Err(AppError::Validation("Invalid path characters".into()));
}
let canonical = dunce::canonicalize(base.join(user_input))
.map_err(|_| AppError::NotFound)?;
let base_canonical = dunce::canonicalize(base)
.map_err(|_| AppError::Internal(anyhow::anyhow!("Invalid base")))?;
if !canonical.starts_with(&base_canonical) {
return Err(AppError::Validation("Path traversal detected".into()));
}
Ok(canonical)
}通过路径规范化和包含性检查防止路径遍历。
rust
pub fn safe_path_join(base: &Path, user_input: &str) -> Result<PathBuf, AppError> {
if user_input.contains("..") || user_input.contains("~") {
return Err(AppError::Validation("Invalid path characters".into()));
}
let canonical = dunce::canonicalize(base.join(user_input))
.map_err(|_| AppError::NotFound)?;
let base_canonical = dunce::canonicalize(base)
.map_err(|_| AppError::Internal(anyhow::anyhow!("Invalid base")))?;
if !canonical.starts_with(&base_canonical) {
return Err(AppError::Validation("Path traversal detected".into()));
}
Ok(canonical)
}Pattern 4: Safe Command Execution
模式4:安全命令执行
Mitigate CVE-2024-24576 by using allowlists and avoiding shell execution.
rust
pub fn safe_command(program: &str, args: &[&str]) -> Result<String, AppError> {
const ALLOWED: &[&str] = &["git", "cargo", "rustc"];
if !ALLOWED.contains(&program) {
return Err(AppError::Validation("Program not allowed".into()));
}
let output = Command::new(program).args(args).output()
.map_err(|e| AppError::Internal(e.into()))?;
if output.status.success() {
String::from_utf8(output.stdout).map_err(|e| AppError::Internal(e.into()))
} else {
Err(AppError::Internal(anyhow::anyhow!("Command failed")))
}
}通过白名单和避免shell执行缓解CVE-2024-24576漏洞。
rust
pub fn safe_command(program: &str, args: &[&str]) -> Result<String, AppError> {
const ALLOWED: &[&str] = &["git", "cargo", "rustc"];
if !ALLOWED.contains(&program) {
return Err(AppError::Validation("Program not allowed".into()));
}
let output = Command::new(program).args(args).output()
.map_err(|e| AppError::Internal(e.into()))?;
if output.status.success() {
String::from_utf8(output.stdout).map_err(|e| AppError::Internal(e.into()))
} else {
Err(AppError::Internal(anyhow::anyhow!("Command failed")))
}
}Pattern 5: Safe Async State Management
模式5:安全异步状态管理
Use Arc<RwLock<T>> for thread-safe shared state in Tauri applications.
rust
pub struct AppState {
users: Arc<RwLock<HashMap<String, User>>>,
config: Arc<Config>,
}
impl AppState {
pub async fn get_user(&self, id: &str) -> Option<User> {
self.users.read().await.get(id).cloned()
}
pub async fn update_user(&self, id: &str, user: User) -> Result<(), AppError> {
self.users.write().await.insert(id.to_string(), user);
Ok(())
}
}Seefor advanced state patterns and Tauri integrationreferences/advanced-patterns.md
在Tauri应用中使用Arc<RwLock<T>>实现线程安全的共享状态。
rust
pub struct AppState {
users: Arc<RwLock<HashMap<String, User>>>,
config: Arc<Config>,
}
impl AppState {
pub async fn get_user(&self, id: &str) -> Option<User> {
self.users.read().await.get(id).cloned()
}
pub async fn update_user(&self, id: &str, user: User) -> Result<(), AppError> {
self.users.write().await.insert(id.to_string(), user);
Ok(())
}
}高级状态模式及Tauri集成请参考references/advanced-patterns.md
6. Security Standards
6. 安全标准
5.1 Critical CVEs
6.1 严重CVE漏洞
| CVE ID | Severity | Description | Mitigation |
|---|---|---|---|
| CVE-2024-24576 | CRITICAL | Command injection via batch files (Windows) | Rust 1.77.2+, avoid shell |
| CVE-2024-43402 | HIGH | Incomplete fix for above | Rust 1.81.0+ |
| CVE-2021-28032 | HIGH | Multiple mutable references in unsafe | Audit unsafe blocks |
Seefor complete CVE details and mitigation codereferences/security-examples.md
| CVE编号 | 严重程度 | 描述 | 缓解方案 |
|---|---|---|---|
| CVE-2024-24576 | 严重 | 通过批处理文件注入命令(Windows) | Rust 1.77.2+,避免使用shell |
| CVE-2024-43402 | 高 | 上述漏洞的修复不完整 | Rust 1.81.0+ |
| CVE-2021-28032 | 高 | Unsafe代码中的多个可变引用 | 审计所有unsafe代码块 |
完整CVE详情及缓解代码请参考references/security-examples.md
5.2 OWASP Top 10 Mapping
6.2 OWASP Top 10映射
| Category | Risk | Key Mitigations |
|---|---|---|
| A01 Broken Access Control | MEDIUM | Validate permissions in Tauri commands |
| A03 Injection | HIGH | Command without shell, parameterized queries |
| A04 Insecure Design | MEDIUM | Type system to enforce invariants |
| A06 Vulnerable Components | HIGH | Run cargo-audit regularly |
| 类别 | 风险 | 核心缓解措施 |
|---|---|---|
| A01 Broken Access Control(访问控制失效) | 中等 | 在Tauri命令中验证权限 |
| A03 Injection(注入) | 高 | 不使用shell执行命令,使用参数化查询 |
| A04 Insecure Design(不安全设计) | 中等 | 用类型系统强制不变量 |
| A06 Vulnerable Components(易受攻击的组件) | 高 | 定期运行cargo-audit |
5.3 Input Validation Strategy
6.3 输入验证策略
Four-layer approach: Type system newtypes -> Schema validation (serde/validator) -> Business logic -> Output encoding
rust
pub struct Email(String); // Newtype for validated input
impl Email {
pub fn new(s: &str) -> Result<Self, ValidationError> {
if validator::validate_email(s) { Ok(Self(s.to_string())) }
else { Err(ValidationError::InvalidEmail) }
}
}四层验证法: 类型系统新类型 -> Schema验证(serde/validator) -> 业务逻辑 -> 输出编码
rust
pub struct Email(String); // 用于已验证输入的新类型
impl Email {
pub fn new(s: &str) -> Result<Self, ValidationError> {
if validator::validate_email(s) { Ok(Self(s.to_string())) }
else { Err(ValidationError::InvalidEmail) }
}
}5.4 Secrets Management
6.4 密钥管理
rust
// Load from environment or tauri-plugin-store with encryption
fn get_api_key() -> Result<String, AppError> {
std::env::var("API_KEY")
.map_err(|_| AppError::Configuration("API_KEY not set".into()))
}Seefor secure storage patternsreferences/security-examples.md
rust
// 从环境变量或带加密的tauri-plugin-store加载
fn get_api_key() -> Result<String, AppError> {
std::env::var("API_KEY")
.map_err(|_| AppError::Configuration("API_KEY not set".into()))
}安全存储模式请参考references/security-examples.md
7. Performance Patterns
7. 性能模式
Pattern 1: Zero-Copy Operations
模式1:零拷贝操作
Bad: then iterate - Good: Return iterator with lifetime
data.to_vec()rust
// Bad: fn process(data: &[u8]) -> Vec<u8> { data.to_vec().iter().map(|b| b+1).collect() }
fn process(data: &[u8]) -> impl Iterator<Item = u8> + '_ {
data.iter().map(|b| b + 1) // No allocation
}错误示例: 后迭代 - 正确示例: 返回带生命周期的迭代器
data.to_vec()rust
// 错误: fn process(data: &[u8]) -> Vec<u8> { data.to_vec().iter().map(|b| b+1).collect() }
fn process(data: &[u8]) -> impl Iterator<Item = u8> + '_ {
data.iter().map(|b| b + 1) // 无内存分配
}Pattern 2: Iterator Chains Over Loops
模式2:迭代器链替代循环
Bad: Manual loop with push - Good: Iterator chain (lazy, fused)
rust
fn filter_transform(items: &[Item]) -> Vec<String> {
items.iter().filter(|i| i.is_valid()).map(|i| i.name.to_uppercase()).collect()
}错误示例: 手动循环+push - 正确示例: 迭代器链(惰性、融合)
rust
fn filter_transform(items: &[Item]) -> Vec<String> {
items.iter().filter(|i| i.is_valid()).map(|i| i.name.to_uppercase()).collect()
}Pattern 3: Memory Pooling for Frequent Allocations
模式3:频繁分配场景使用内存池
Bad: in hot path - Good: Object pool
Vec::with_capacity()rust
static BUFFER_POOL: Lazy<Pool<Vec<u8>>> = Lazy::new(|| Pool::new(32, || Vec::with_capacity(1024)));
async fn handle_request(data: &[u8]) -> Vec<u8> {
let mut buffer = BUFFER_POOL.pull(|| Vec::with_capacity(1024));
buffer.clear(); process(&mut buffer, data); buffer.to_vec()
}错误示例: 热点路径中使用 - 正确示例: 对象池
Vec::with_capacity()rust
static BUFFER_POOL: Lazy<Pool<Vec<u8>>> = Lazy::new(|| Pool::new(32, || Vec::with_capacity(1024)));
async fn handle_request(data: &[u8]) -> Vec<u8> {
let mut buffer = BUFFER_POOL.pull(|| Vec::with_capacity(1024));
buffer.clear(); process(&mut buffer, data); buffer.to_vec()
}Pattern 4: Async Runtime Selection
模式4:异步运行时选择
Bad: CPU work on async - Good: for CPU-bound
spawn_blockingrust
async fn hash_password(password: String) -> Result<String, AppError> {
tokio::task::spawn_blocking(move || {
argon2::hash_encoded(password.as_bytes(), &salt, &config)
.map_err(|e| AppError::Internal(e.into()))
}).await?
}错误示例: 异步线程处理CPU密集型任务 - 正确示例: 用处理CPU密集型任务
spawn_blockingrust
async fn hash_password(password: String) -> Result<String, AppError> {
tokio::task::spawn_blocking(move || {
argon2::hash_encoded(password.as_bytes(), &salt, &config)
.map_err(|e| AppError::Internal(e.into()))
}).await?
}Pattern 5: Avoid Allocations in Hot Paths
模式5:避免热点路径中的内存分配
Bad: allocates - Good: to preallocated buffer
println!write!rust
fn log_metric(buffer: &mut Vec<u8>, name: &str, value: u64) {
buffer.clear();
write!(buffer, "{}: {}", name, value).unwrap();
std::io::stdout().write_all(buffer).unwrap();
}错误示例: 会分配内存 - 正确示例: 用写入预分配缓冲区
println!write!rust
fn log_metric(buffer: &mut Vec<u8>, name: &str, value: u64) {
buffer.clear();
write!(buffer, "{}: {}", name, value).unwrap();
std::io::stdout().write_all(buffer).unwrap();
}8. Testing & Validation
8. 测试与验证
Security Testing Commands
安全测试命令
bash
cargo audit # Dependency vulnerabilities
cargo +nightly careful test # Memory safety checking
cargo clippy -- -D warnings # Lint with security warningsbash
cargo audit # 依赖漏洞扫描
cargo +nightly careful test # 内存安全检查
cargo clippy -- -D warnings # 包含安全警告的代码检查Unit Test Pattern
单元测试模式
rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_path_traversal_blocked() {
let base = Path::new("/app/data");
assert!(safe_path_join(base, "../etc/passwd").is_err());
assert!(safe_path_join(base, "user/file.txt").is_ok());
}
#[test]
fn test_command_allowlist() {
assert!(safe_command("rm", &["-rf", "/"]).is_err());
assert!(safe_command("git", &["status"]).is_ok());
}
}Seefor fuzzing and integration test patternsreferences/advanced-patterns.md
rust
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_path_traversal_blocked() {
let base = Path::new("/app/data");
assert!(safe_path_join(base, "../etc/passwd").is_err());
assert!(safe_path_join(base, "user/file.txt").is_ok());
}
#[test]
fn test_command_allowlist() {
assert!(safe_command("rm", &["-rf", "/"]).is_err());
assert!(safe_command("git", &["status"]).is_ok());
}
}模糊测试与集成测试模式请参考references/advanced-patterns.md
9. Common Mistakes & Anti-Patterns
9. 常见错误与反模式
| Anti-Pattern | Problem | Solution |
|---|---|---|
| Panics crash app | Use |
| Unsafe without docs | Unverified invariants | Add |
| Shell command execution | Injection vulnerability | Use |
| Ignoring Clippy | Missed security lints | Run |
| Hardcoded credentials | Secrets in code | Use env vars or secure storage |
rust
// NEVER: Shell injection
Command::new("sh").arg("-c").arg(format!("echo {}", user_input));
// ALWAYS: Direct execution
Command::new("echo").arg(user_input);| 反模式 | 问题 | 解决方案 |
|---|---|---|
生产环境中使用 | Panic会导致应用崩溃 | 使用 |
| 无文档的Unsafe代码 | 未验证的不变量 | 添加 |
| Shell命令执行 | 注入漏洞 | 直接使用 |
| 忽略Clippy提示 | 遗漏安全警告 | 运行 |
| 硬编码凭证 | 密钥暴露在代码中 | 使用环境变量或安全存储 |
rust
// 绝对禁止: Shell注入
Command::new("sh").arg("-c").arg(format!("echo {}", user_input));
// 正确做法: 直接执行
Command::new("echo").arg(user_input);10. Pre-Implementation Checklist
10. 预实现检查清单
Phase 1: Before Writing Code
阶段1:编写代码前
- Write failing tests that define expected behavior
- Review relevant CVEs for the feature area
- Identify security boundaries (FFI, IPC, file system)
- Plan error handling strategy with Result types
- Check dependencies with
cargo audit
- 编写定义预期行为的失败测试
- 审查功能领域的相关CVE漏洞
- 识别安全边界(FFI、IPC、文件系统)
- 规划基于Result类型的错误处理策略
- 用检查依赖
cargo audit
Phase 2: During Implementation
阶段2:实现过程中
- Run tests after each significant change
- Document all unsafe blocks with comments
// SAFETY: - Validate inputs at all boundaries (Tauri commands, FFI)
- Use type system to enforce invariants (newtypes)
- Apply performance patterns (zero-copy, iterators)
- Ensure error messages don't leak internal details
- 每次重大变更后运行测试
- 为所有unsafe代码块添加注释
// SAFETY: - 在所有边界(Tauri命令、FFI)验证输入
- 用类型系统强制不变量(新类型)
- 应用性能模式(零拷贝、迭代器)
- 确保错误信息不泄露内部细节
Phase 3: Before Committing
阶段3:提交前
- - all tests pass
cargo test - - no warnings
cargo clippy -- -D warnings - - zero HIGH/CRITICAL vulnerabilities
cargo audit - No hardcoded secrets (grep for "password", "secret", "key")
- Path operations use canonicalization and containment checks
- Command execution uses allowlist, no shell
- Panic handler configured for graceful shutdown
- Logging configured (no secrets in logs)
- - 所有测试通过
cargo test - - 无警告
cargo clippy -- -D warnings - - 无高/严重级漏洞
cargo audit - 无硬编码密钥(搜索"password"、"secret"、"key")
- 路径操作使用规范化与包含性检查
- 命令执行使用白名单,不使用shell
- 配置Panic处理程序实现优雅关闭
- 配置日志(日志中无密钥)
11. Summary
11. 总结
Your goal is to create Rust code that is:
- Memory Safe: Leverage the borrow checker, minimize unsafe
- Type Safe: Use the type system to prevent invalid states
- Performant: Zero-cost abstractions, profile before optimizing
- Secure: Validate at boundaries, handle errors safely
Critical Security Reminders:
- Upgrade to Rust 1.81.0+ to fix command injection CVEs
- Run cargo-audit in CI/CD pipeline
- Document SAFETY invariants for all unsafe blocks
- Never use shell execution with user input
- Canonicalize and validate all file paths
For detailed examples and advanced patterns, see thedirectoryreferences/
您的目标是创建具备以下特性的Rust代码:
- 内存安全: 利用借用检查器,最小化unsafe代码
- 类型安全: 用类型系统防止无效状态
- 高性能: 零成本抽象,先分析再优化
- 安全: 在边界验证输入,安全处理错误
关键安全提醒:
- 升级到Rust 1.81.0+以修复命令注入CVE漏洞
- 在CI/CD流水线中运行cargo-audit
- 为所有unsafe代码块记录SAFETY不变量
- 绝不要结合用户输入使用shell执行
- 规范化并验证所有文件路径
详细示例与高级模式请参考目录references/