跳到正文
原文
Microsoft Research· Alex Lavaee, Matthai Philipose·· 23 天前AI 评分51

微软研究院的 PDD Kit 如何形式化验证智能体编写的全栈 Web 应用

Formally verifying agent-written full-stack web apps with PDD Kit

AI 导读

微软研究院的 PDD Kit 把意图写成 Verus 规格,校验智能体代码对每个输入是否满足规格,覆盖不到处改用测试。团队在 GitHub Next 的 Chopin 中用它处理约 5000 行 Rust 应用 Pet Store 的登录逻辑,Verus 加固代码并发现既有缺陷,开发者审阅意图而非逐行阅读生成代码。

正文 · AI 翻译
PDDKit decision flowchart on green gradient background

概览

  • 面向日常软件的形式化方法。 PDD Kit 帮助你将意图转化为形式化规范,然后证明智能体所写的代码对每一个输入都成立,并在证明无法覆盖之处使用测试。它将形式化方法从小众的专业工作扩展到没有形式化方法背景的工程师以及日常应用,例如这里展示的全栈 Web 应用。
  • 详尽的逐行人工审查会变得难以扩展,因为 AI 智能体生成的代码量越来越大。 计划本应是你与编程智能体之间的契约,但实际上没有任何东西强制智能体遵守它。它编写的测试通常检查的是它构建出来的东西,而不是你所要求的内容。 
  • PDD Kit 让智能体遵守计划。 它与你协作,将你的意图转化为 Verus (在新标签页中打开) 中的形式化规范,证明智能体的代码对每一个输入都符合该规范,并在证明无法覆盖之处回退到测试。
  • 我们在一个全栈 Web 应用上试用了它。 在 GitHub Next 的 Chopin (在新标签页中打开) 中,我们使用 PDD Kit 对 Pet Store(一个 Rust (在新标签页中打开) 店面)的登录逻辑进行了形式化验证。Verus 加固了代码并发现了既有缺陷,证明相对于该规范不存在登录缺陷。开发者审查了意图,从未逐行阅读生成的代码。 

计划是智能体应当遵守的契约,但没有任何东西约束智能体去遵守它。

编程智能体现在常常一次就能交付整个功能,代码量往往达到数万行乃至数十万行。因此,逐行阅读拉取请求无法扩展以适应这种新的工作方式。如今,大多数团队改为投入计划和相关测试:向智能体描述他们想要的内容,来回迭代直到计划和拟议的测试看起来正确,然后把 它们交给智能体去实现。 

这种计划或自然语言规范本应是智能体所遵守的契约。然而在实践中,智能体可能会偏离它。它实现的内容略有不同,然后编写的测试能通过其自身实现,而不是你希望它编写的代码。持续集成(CI)因大量低质量测试而膨胀,覆盖率看起来很健康,而你所要求的与实际交付之间的差距会一直隐藏,直到出现缺陷报告或棘手的边界情况。

那么,当智能体生成的代码量越来越大时,如何可靠地扩展审查?智能体代码会以细心的审查者通常能发现的两种方式失败:遗漏明显必要的内容,或做出明显错误的事情。仅靠测试无法弥补这一差距,因为它们只检验程序所能做的事情中的极小一部分。弥补这一差距需要另一种机制,而这正是证明发挥作用之处。

审查问的是“这看起来对吗?”证明回答的是“这是对的吗?”数学证明表明,代码对每一个输入都符合其规范,包括测试套件可能遗漏的输入。这为所指定的属性提供了比仅靠测试更强的保证,尤其是在逐行审查并不切实际时。

证明曾经对日常软件来说过于昂贵。你需要专家、不熟悉的语言、比代码大许多倍的证明,而且证明要花数年才能开发完成,但此后有两件事发生了变化。首先,编程智能体的最新进展使它们越来越切实可行地根据定义良好的规格帮助生成形式化证明。其次,智能体现在能更好地帮助你编写形式化规格。我们将这种新的软件开发范式称为 Proof-Driven Development(PDD)。PDD Kit 是我们为此打造的工具包。

PDD Kit 如何工作

PDD Kit 之于形式化方法,大致相当于 Spec Kit(在新标签页中打开) 之于 Spec-Driven Development。它作为协作伙伴运行于 Chopin(在新标签页中打开) 之中,后者是 GitHub Next 的实时多人规划环境,团队与智能体可以在同一份共享文档中进行规划。

该工作流分为两部分(图 1)。首先,团队成员用通俗语言审阅意图。PDD Kit 会提出细心审阅者会问的问题,并在过程中解释相关代码,再把答案记录在一份 意图 工件 中,这是一份将用户意图与形式化规格或测试衔接起来的文档。用户意图中能够形式化的部分会被转换为形式化规格,其余必须凭信任接受的部分则被转换为供测试使用的非形式化规格。PDD Kit 会自动生成证明,以表明代码满足所推导出的形式化规格,并为非形式化规格生成高质量测试。你无需形式化方法背景即可完成这一切。 

Flow diagram showing the PDD Kit workflow for formally verifying agent-written code. Team members review intent by expressing requirements in plain language, which are formalized in a pdd-plan containing decision cards, intent artifacts, trusted boundaries, and reviewer approvals. The plan generates a formal specification with Verus ensures clauses. Machines then check the code through pdd-prove, which includes Verus proofs, tests for trusted components, and LLM gap review. Verified code and receipts are submitted as a pull request. Dashed feedback loops return specification contradictions and verification gaps to earlier planning and coding stages.
图 1. 借助 PDD Kit 的 Proof-Driven Development。团队成员确定意图。Verus 与测试套件确保代码符合该意图。

因此,PDD Kit 中的每一项结果都会标明它所依据的是哪一种验证: 

  • 形式化验证是一种数学证明,证明代码对每一种可能的输入都满足其规格,并由一种称为验证器的工具进行检查。对如今的 PDD Kit 而言,该验证器是 Verus(在新标签页中打开),一种面向 Rust 的证明语言,由 Microsoft Research、Carnegie Mellon University、VMware Research、ETH Zurich、MPI-SWS、UNSW Sydney、the University of Texas at Austin、the University of Michigan、the University of British Columbia、the University of Wisconsin–Madison 以及 Weizmann Institute of Science 共同开发。
  • 经验验证通过运行代码并观察其行为来检查代码。它覆盖证明无法触及之处,例如第三方密码学库或用户界面。它使用单元测试和端到端测试、终端自动化、浏览器智能体,并使用计算机使用智能体来处理浏览器无法驱动的任何事物。测试通过仅表明代码在其尝试过的输入上可以工作,因此 PDD Kit 将其标记为证据而非证明。

二者之间的分界线是 可信计算基(TCB):证明假定其会按所述方式运行的代码。PDD Kit 使这条分界线明确可见,并要求你对每一部分予以签核。 

压轴项目:一个全栈 Web 应用

为了展示 PDD Kit 与现有代码库的集成,我们构建了 Pet Store,一个完全用 Rust(在新标签页中打开) 编写的全栈 Web 应用。后端使用 Axum(在新标签页中打开) 和 SQLite(在新标签页中打开),负责处理库存、促销、订单和结账。店面是一个 Leptos(在新标签页中打开) 应用,编译为 WebAssembly(在新标签页中打开)。二者合计约 5,000 行 Rust。

为求本博客简短,我们聚焦于对该应用的登录逻辑进行形式化验证,但同一流程也可用于验证整个应用的功能正确性。PDD Kit 建议 从应用中最敏感的部分开始,并逐步验证你的应用。登录缺陷可能会把客户的账户或管理员的控制权交给攻击者,因此证明方面的投入首先在这里获得回报。开发者在 Chopin 中的全部请求只有两句话: 

Verify the login logic in backend/src/handlers/auth.rs. Here are my requirements:

  1. You only get a token with the right password.
  2. Only admin accounts get admin tokens.

我们故意让这条请求保持粗略。捕捉用户意图,并把用户请求转化为证明能够检验的内容,是 PDD Kit 的工作。

步骤 1:代码之前的问题

PDD Kit 的规划工作流 pdd-plan 会阅读代码,并在编写任何内容之前,于 决策 选项卡中带回问题。当某个问题取决于代码如何工作,卡片会先解释那一部分:目标、各部分如何衔接,以及涉及的确切函数,这样你无需打开源代码即可作答。 

Screenshot of a verification tool evaluating a login authentication requirement. The prompt asks, “Must the right password always get a token?” A flow diagram shows a login request leading to a password check, where matching passwords receive a token and non-matching passwords are refused. Option A, highlighted as recommended, proves both outcomes: the correct password receives a token and an incorrect password is refused. Option B proves only that incorrect passwords are refused, leaving the result for the correct password unspecified.
图 2. 第一张决策卡片。“只有密码正确时”本身也会被拒绝所有人的登录所满足。双向证明可以排除这种情况。

这个问题看起来有些迂腐,但很重要。“只有密码正确才能获得令牌”排除了错误密码获得令牌这一坏情况,而拒绝所有人的登录也能完美遵守这一承诺。“正确的密码始终有效”正是排除这种情况的另一半。形式上,前者是蕴含(令牌 ⇒ 正确密码),后者是其逆命题。二者合起来构成“当且仅当”。若放任智能体自行决定,它会不告诉你就只选其一,但这里开发者选择了两个方向。

步骤 2:人类可读的意图图

随着对话进行,PDD Kit 会让计划顶部的 粗略工作 部分保持最新,这样用户就能跟踪重要概念,而无需回翻很长的聊天记录去找已经商定的内容。它包括正在规定的登录流程图、关于将证明什么与将信任什么的规范全景,以及在图片有助于理解时的心智模型。对于登录,PDD Kit 画了一个售票窗口(图 3)。

Three-panel illustration comparing login outcomes. In the first panel, a customer logs in with the correct email and password and receives a “customer” ticket. In the second panel, the same email is paired with an incorrect password and access is refused. In the third panel, an administrator logs in with the correct username and password and receives an “admin” ticket. The diagram uses a ticket-counter analogy to explain authentication and role-based access.
图 3. PDD Kit 的登录心智模型。你发送的字段选定窗口,窗口选定表格并随之确定角色,在密码匹配之前不会打印任何内容。

在其下方,意图图 将每项需求追溯到开发者自己的原话,并记录它是如何确定的(图 4)。每个条目都链接到为其建模的形式化规范章节以及覆盖它的测试,规范章节会展示 Verus 契约片段,并加以注释,以便开发者看到形式化规范如何对其意图进行建模。

Intent map showing the login authentication flow for issuing a token. If an account exists and bcrypt verifies the correct password, the user receives claims for that account. If the account does not exist or the password is incorrect, the result is “401 Unauthorized.” If the password hash cannot be read, the result is “500 unreadable hash.”
图 4. 决策之后的一条意图图条目:登录只有使用该账户的正确密码才会获得令牌,并且只要密码正确就总会获得令牌。流程图展示了密码检查可能结束的每一种方式。

图 2 中的决策卡片,正是那种智能体否则会默默自行裁定的歧义。图 5 展示了这种差异在纸面上看起来有多小:两种解读只在一个单元格上不一致,即一个正确的密码却得不到令牌。

Side-by-side comparison of two authentication policies. The left panel, “Only when,” shows that a token implies the correct password but does not guarantee a token for a correct password. The right panel, “Exactly when,” shows a two-way relationship in which a token is issued if and only if the correct password is provided. The highlighted difference is that denying a token to a user with the correct password is allowed under the first policy but forbidden under the second.
图 5。同一句话的两种解读。它们只在一个单元格上不同,而这个单元格改变了证明必须确立的内容。

步骤 3:证明登录函数

在任何东西开始构建之前,PDD Kit 会要求团队对整个计划签字确认。它的初稿证明了登录核心的决策——选择表并依据密码进行门控——并把周围的处理程序保持为受信任且经过测试的。这是一个合理的默认做法,也是 PDD Kit 所建议的,但开发者想要更多。处理程序是查找被 await、令牌被签名的地方,而这层粘合代码恰恰是重构时可能悄悄对调两行的地方。因此在意图评审时,开发者选择给登录处理程序一份自己的异步规约,这样证明也会覆盖这层粘合代码,而不是信任它(图 6)。

Comparison of two approaches to verifying a login handler. Option A, recommended, keeps the login handler trusted and verifies only the login decision logic, while database lookups and token signing remain tested but trusted components. Option B gives the login handler its own formal specification, proving the orchestration logic but requiring additional trusted wrappers and assumed contracts around database lookups, clocks, and JWT signing.
图 6。证明登录的更多部分意味着要信任更多小型包装函数。卡片在开发者做出选择之前就这么说了。 

这一选择把几乎所有内容都移进了证明,只留给登录处理程序解包请求这一件事可做。一个新的异步函数 login_flow 把契约从请求的字段一路带到令牌或 HTTP 错误。随后 PDD Kit 把修订后的计划拿回来重新签字确认,因为符合你的意图并不等于证明,它也不会批准新的信任或更宽的范围。 

步骤 4:证明止于何处

关于一个程序,有很多事情你无法证明,而登录会碰到其中的大部分:

  • 验证器看不到的代码。 bcrypt 的哈希、sqlx 的查询以及 jsonwebtoken 的签名都位于其他 crate 中,处于证明之外。 
  • 关于外部世界的事实。 SQLite 此刻保存着什么、时钟显示的是什么时间,都是程序的输入,而不是其代码所能确立的东西。 
  • 某件事是否完成、以及完成得有多快。 规约说明的是如果登录给出应答你会得到什么。查询挂起,或查询很慢,都不会破坏其中的任何内容。 
  • 任何必须由人来判断的事情,比如一条错误消息是否有帮助,或者一个界面是否说得通。 
  • 任何没人写下来的东西。 证明覆盖的是它的规约,对规约之外的需求什么也不说。 

这就是经验验证发挥作用的地方。PDD Kit 会写明受信任边界,也就是本证明所依赖的那部分 TCB。它把每一块受信任的部分包进一个带有假定契约的小函数,使用 Verus 的 #[verifier::external_body] 或 external_fn_specification,要求开发者逐一接受每一项,并把每一条假定子句的测试写进计划。对于登录,开发者签字确认了六块:

  • 两次查找,Customer::find_by_email 和 Admin::find_by_username。每一次被 await 且成功的查找,都恰好返回其自身的表为该电子邮件或用户名所保存的那一行,或者不返回任何行。 
  • check_password,一个围绕 bcrypt::verify 的薄包装。它只在存储的哈希是 bcrypt 无法读取时才出错,而 Ok(true) 恰好表示正确的密码。 
  • generate_token,它在已配置的密钥下恰好签下所给的声明,并把签名失败报告为 500。 
  • expiry_from_now,它读取时钟,并写入恰好 24 小时之后的过期时间。 
  • database_error,它把一次失败的查找变成今天的 500,并附上 sqlx 的消息。 
  • 登录处理程序外壳,它解包请求,并原样把其字段传给 login_flow。 

在规范中,查找会把代码留在原处,并通过 external_fn_specification 从外部获得一份契约: 

/// Looks up a customer by exact email. 
/// Trusted, not proved: the SQL query runs in sqlx, which Verus cannot check. 
/// Every customer promise of `login_flow` rests on it. 
#[verifier::external_fn_specification] 
pub async fn ex_customer_find_by_email(pool: &sqlx::SqlitePool, email: &str) 
    -> (r: Result, sqlx::Error>) 
    ensures 
        // When the query succeeds, it returns the customers row on 
        // file for exactly this email, or None when there is none. 
        r matches Ok(found) ==> found == customer_on_file(email@), 
{ 
    Customer::find_by_email(pool, email).await 
} 

时钟是一个标有 #[verifier::external_body] 的小型包装器。Verus 使用它的 ensures 子句,且从不读取函数体: 

/// Reads the clock and computes a token's expiry 24 hours ahead. 
/// Trusted, not proved: chrono's clock is outside the proof. 
/// It panics if the time is out of range, as today's login does; 
/// that panic is not promised against. 
#[verifier::external_body] 
pub fn expiry_from_now() -> (r: Expiry) 
    ensures 
        // The expiry is exactly 24 hours (86,400 seconds) after the clock reading. 
        r.exp as int == r.now as int + 86_400, 
{ 
    ... 
} 

图 7 把这三层合在一起:Verus 所证明的、人们所接受且由测试检查的,以及无人承诺的。 

Diagram showing the proof boundary for a formally verified login system. Functionality outside the proof is either not promised or trusted and validated through human review and testing, including SQLite lookups, bcrypt, the system clock, JWT signing, database error handling, and request parsing. At the center, the formally verified portion consists of the login_flow and its components login_core, lookup_target, decide_login, and issue_token, which are proven by Verus for every input.
图 7. 登录证明止于何处。Verus 针对每一个输入证明核心部分。人们接受受信任环,测试对其进行检查。计划列出了无人承诺的内容。 

图 8 标出了哪些得到证明、哪些得到信任。每一项信任决策都是一张独立的卡片。它展示 Verus 将凭信任接受的子句、开发者正在接受的内容,以及若假设有误哪一项承诺会落空(图 9)。随后,每一个被假定的子句都会在计划的 Empirical verification 一节中得到经验检查,并在任何测试存在之前写成 Given/When/Then 场景(图 10)。一条记录在运行之前标为 planned,运行之后则记录该命令的结果以及它所针对的提交。

Proof map showing how a verified login system is divided between formally proved code and trusted, tested components. Five core functions, including login_flow, login_core, lookup_target, decide_login, and issue_token, are formally verified with Verus. Supporting functions for database queries, password verification, token signing, clock access, and error handling are treated as trusted contracts that are reviewed and tested.
图 8. 登录中哪些得到证明、哪些得到信任。绿色函数由 Verus 针对每一个输入加以证明。琥珀色部分受到信任、由开发者接受,并由计划 §4.1 中计划的测试加以检查。
Proof map showing how a verified login system is divided between formally proved code and trusted, tested components. Five core functions, including login_flow, login_core, lookup_target, decide_login, and issue_token, are formally verified with Verus. Supporting functions for database queries, password verification, token signing, clock access, and error handling are treated as trusted contracts that are reviewed and tested.
图 9. check_password 的信任卡片。Verus 凭信任接受这两条子句,因此由人接受它们,并由两项测试加以检查。 
Screenshot of a test plan for verifying password validation behavior. The section, “check_password_answers_with_bcrypts_verdict,” describes unit tests confirming that password checks return true for the correct password and false for incorrect or empty passwords. Example test cases use bcrypt hashes for customer and administrator accounts.
图 10. 针对受信任的 check_password 的一项计划中的测试,写于该测试存在之前。计划把通过的测试标为证据而非证明。 

计划同样明确写出了无人承诺的内容:登录 future 是否终将完成、越界时钟是否不会 panic、关于尝试时机或频率的任何事项,以及其他端点如何读取角色。 

第 5 步:阅读规范

意图产物是团队所审阅的内容。它是 PDD Kit 写成 Verus 契约的形式化规范的通俗语言版本。你或许会想,现在是否得有人去读证明而不是读代码。没有人需要这么做,因为编程代理会写出证明,而 Verus 会检查其中的每一步。如果 Verus 接受了证明,那么无论是否有人阅读,它都成立。规范是证明所依据的对象,因此人们审阅的是规范,而这一份短到几分钟就能学会阅读。每个函数都有一个 ensures 块:关于其结果 r 的陈述,必须对每一个可能的输入成立。Verus 在你构建时检查它们,如果任何子句哪怕对一个输入可能失败,构建就会失败,并且 Verus 会指向该子句。每条子句都读作一个如果—那么,图 11 拆解了开发者第一条需求所对应的子句。

Annotated code snippet explaining a formal verification clause for login tokens. The clause states that if a login returns a token, then the request names a valid account, the password matches the stored hash, the token contains valid claims, and the token’s subject and role match the authenticated account. Numbered callouts explain each part of the expression.
图 11. login_flow 上针对“只有密码正确才能得到令牌。”的 ensures 子句。同一个账户 a 出现在每一行,从而把密码检查与令牌联系起来。

注意,每一行都出现同一个 a,从而把密码检查与令牌绑在一起。例如,设想这样一个 bug:登录针对一个账户检查密码,却为另一个账户签发令牌。Bob 用自己正确的密码登录,却拿回了 Alice 账户的令牌。每一步单独看起来都没问题,但这一条款能抓住它,因为密码检查和令牌必须指名同一个账户。这正是测试套件很少想到要去查找的那种接线 bug。规范还必须在不运行它们中任何一个的情况下谈论 SQLite、bcrypt 和 JWT。它借助未解释函数来做到这一点,即没有函数体的名字:customer_on_file(email) 和 admin_on_file(username) 表示数据库所持有的行,bcrypt_verdict(password, hash) 表示 bcrypt 会给出的结果,token_claims(token, secret) 表示令牌所携带的内容。除了第 4 步的受信任契约所承诺的内容之外,Verus 对它们一无所知。证明说“无论数据库持有什么,登录都会据此做出正确的事”,而一份受信任契约则说“查找返回数据库所持有的内容。” 

/// The customers row the database holds for 
/// exactly this email, if any, when login looks. 
/// Left abstract: only `Customer::find_by_email`'s 
/// trusted contract says what it is. 
pub uninterp spec fn customer_on_file(email: Seq) -> Option; 
... 
/// What bcrypt says about `password` against a 
/// stored `hash`: Some(true) when it is the password 
/// the hash was made from, Some(false) when it is 
/// not, None when bcrypt cannot read the hash. 
/// Left abstract: its meaning is bcrypt's, taken on trust through `check_password`. 
pub uninterp spec fn bcrypt_verdict(password: Seq, hash: Seq) 
    -> Option; 
 
/// The password is the right one for the stored hash, by bcrypt's verdict. 
pub open spec fn password_matches(password: Seq, hash: Seq) -> bool { 
    bcrypt_verdict(password, hash) == Some(true) 
} 

在这些之上,named_account(email, username) 说明一次登录所指的是哪个账户:若发送了电子邮件,则为该电子邮件对应的 customers 行,否则为该用户名对应的 admins 行,否则为无。它写得像 Rust,但它是一个从不运行、只出现在契约中的数学定义。这样的代码称为幽灵代码,因为验证器会检查它,而编译器会把它从程序中擦除。有了它,开发者那两句话的请求最终变成了 login_flow 上的八条 ensures 子句(图 12)。 

/// The account a login names: the customers row for 
/// the email when one is sent (role "customer"), 
/// otherwise the admins row for the username (role "admin"), otherwise none. 
pub open spec fn named_account(email: Option, username: Option) 
    -> Option { 
    match email { 
        Some(e) => match customer_on_file(e@) { 
            Some(c) => Some(NamedAccount { 
                id: c.id@, password_hash: c.password_hash@, role: customer_role() }), 
            None => None, 
        }, 
        None => match username { 
            Some(u) => match admin_on_file(u@) { 
                Some(a) => Some(NamedAccount { 
                    id: a.id@, password_hash: a.password_hash@, role: admin_role() }), 
                None => None, 
            }, 
            None => None, 
        }, 
    } 
} 

Traceability diagram showing how formal verification promises are derived from requirements. Statements made by developers and decisions recorded in design cards are mapped to eight specific guarantees in the login_flow specification, covering token issuance, account roles, invalid credentials, missing accounts, malformed requests, and error handling.
图 12。那两句话的请求以及 Both ways 决策,最终变成了 login_flow 上的八条 ensures 子句。其中四条保留了今天的拒绝行为,因此店面和现有的 API 测试仍能继续工作。 

下面是完整契约,其文档注释已作删节。每条子句上方都有意图产物向团队展示的通俗英语注释: 

/// The whole login, awaited end to end: from the 
/// request's fields to the token or the HTTP error. 
/// ... 
pub async fn login_flow(pool: &sqlx::SqlitePool, config: &Config, 
    email: Option, username: Option, password: &str) 
    -> (r: Result) 
    ensures 
        // Neither an email nor a username: 400 with today's message. 
        email is None && username is None 
            ==> (r matches Err(AppError::BadRequest(m)) 
                && m@ == missing_identity_text()), 
        // A token only for the account the login names, with its right 
        // password; it carries that account's id and its table's role. 
        r matches Ok(t) ==> (named_account(email, username) matches Some(a) 
            && password_matches(password@, a.password_hash) 
            && token_claims(t@, config.jwt_secret@) matches Some(c) 
            && c.sub@ == a.id && c.role@ == a.role), 
        // The right password for the named account always gets a 
        // token, unless a lookup or signing failure gives 500. 
        (named_account(email, username) matches Some(a) 
            && password_matches(password@, a.password_hash)) 
            ==> (r is Ok || r matches Err(AppError::Internal(_))), 
        // A login naming an account nobody holds gets 
        // 401, unless the lookup fails with 500. 
        ((email is Some || username is Some) && named_account(email, username) is None) 
            ==> (r matches Err(AppError::Unauthorized) 
                || r matches Err(AppError::Internal(_))), 
        // A wrong password for an account whose hash bcrypt 
        // can read gets 401, unless the lookup fails with 500. 
        (named_account(email, username) matches Some(a) 
            && bcrypt_verdict(password@, a.password_hash) == Some(false)) 
            ==> (r matches Err(AppError::Unauthorized) 
                || r matches Err(AppError::Internal(_))), 
        // An account whose stored hash bcrypt cannot read gets 500 and no token. 
        (named_account(email, username) matches Some(a) 
            && bcrypt_verdict(password@, a.password_hash) is None) 
            ==> r matches Err(AppError::Internal(_)), 
        // The admin role only for an admins row 
        // found by username, with no email sent. 
        (r matches Ok(t) && token_claims(t@, config.jwt_secret@) matches Some(c) 
            && c.role@ == admin_role()) 
            ==> (email is None && username matches Some(u) 
                && admin_on_file(u@) is Some), 
        // An email login's token always carries the customer role. 
        (r matches Ok(t) && email is Some) 
            ==> (token_claims(t@, config.jwt_secret@) matches Some(c) 
                && c.role@ == customer_role()), 
{ 
    unimplemented!() 
} 

受信任边界也体现在代码中。check_password 是 Verus 不检查其函数体的函数之一。它的契约把它与 bcrypt_verdict 联系起来,后者是一个不含公理的 bcrypt 未解释模型:

/// Asks bcrypt whether `password` matches the stored `hash`. 
/// Trusted, not proved: Verus cannot check bcrypt's hashing, 
/// so this wrapper's contract is assumed. 
/// Every password promise of `login_flow` rests on it. 
#[verifier::external_body] 
pub fn check_password(password: &str, hash: &str) -> (r: Result) 
    ensures 
        // bcrypt answers (Ok) exactly when it can read the stored hash. 
        r is Ok <==> bcrypt_verdict(password@, hash@) is Some, 
        // Its answer is its verdict: true for the 
        // right password, false for any other. 
        r matches Ok(b) ==> bcrypt_verdict(password@, hash@) == Some(b), 
{ 
    bcrypt::verify(password, hash).map_err(|e| e.to_string()) 
} 

它上方的文档注释说明了依赖于它的内容:login_flow 的每一项密码承诺。 每次登录都会在少数几个位置之一结束,其中只有一个位置带有令牌(图 13)。证明一次性覆盖了所有这些情况。 

Flowchart showing the end-to-end login process. A login request selects an account table based on an email or username, looks up the account, verifies the password, and issues a signed token when authentication succeeds. Error paths return appropriate HTTP responses: 400 for missing credentials, 401 for invalid credentials or missing accounts, and 500 for lookup or password-hash failures.
图 13。登录可以结束的每一种方式,来自该方案。 

login_flow 是 async 的:它会 await 一次数据库查询。Verus 可以为 async 函数加上契约,有一条规则值得了解(图 14)。requires 在调用创建 future 时被检查。ensures 描述的是你 await 它时所得到的值。没有任何东西保证该 future 会结束,因此一次挂起的查询不会破坏任何子句。 

login_flow 上的文档注释明确地这样说道: 

/// ... No promise the future completes. 
pub async fn login_flow(...) -> (r: Result) 

Diagram comparing how formal verification applies to synchronous and asynchronous functions. For both types, preconditions are checked when the function is called and postconditions are guaranteed when a result is returned. In an asynchronous login flow, the function may pause while awaiting a database lookup, and the specification makes no guarantee about whether or how quickly the operation completes.
图 14。契约何时被检查,针对一个 sync fn 和一个 async fn。 

login_flow 之所以保持简短,是因为它由更小的已证明片段构成。lookup_target 选择表。login_core await 查找并调用 decide_login,即密码门。issue_token 签发令牌,或把一次拒绝映射为今天的 HTTP 错误。每个片段都有自己的契约,Verus 仅凭这些契约来证明 login_flow,而不重新阅读它们的函数体。更改 decide_login 的函数体后,只有 decide_login 会再次被证明。 

下面是最小片段的全文,以及密码门的开头和结尾: 

pub fn lookup_target(email: Option, username: Option) 
    -> (r: Result) 
    ensures 
        // An email, when sent, wins: customers are searched for exactly that email. 
        email matches Some(e) 
            ==> r == Ok::(LookupTarget::CustomerByEmail(e)), 
        // With no email, a username sends the search 
        // to admins for exactly that username. 
        email is None && username matches Some(u) 
            ==> r == Ok::(LookupTarget::AdminByUsername(u)), 
        // With neither, the login is refused for missing an identity. 
        email is None && username is None 
            ==> r == Err::(LoginError::MissingIdentity), 

pub fn decide_login(target: &LookupTarget, found: Option, password: &str) 
    -> (r: Result) 
    ensures 
        // No row found: refused as Unauthorized, 
        // the same answer as a wrong password. 
        found is None 
            ==> r == Err::(LoginError::Unauthorized), 
        // Claims come back only for a found row 
        // whose stored hash matches the password. 
        r is Ok ==> found is Some 
            && password_matches(password@, found->Some_0.password_hash@), 
        // The right password for a found row always gets claims. 
        found matches Some(a) && password_matches(password@, a.password_hash@) 
            ==> r is Ok, 
        ... 
        // An admins-table search gives the role text "admin". 
        r matches Ok(c) && target is AdminByUsername ==> c.role@ == admin_role(), 
        // A customers-table search gives the role text "customer". 
        r matches Ok(c) && target is CustomerByEmail ==> c.role@ == customer_role(), 

login.rs 概览 

图 15 映射了整个规范文件 verified/src/login.rs。它自上而下分为四层:标头、Verus 需要了解的导入与类型、外部世界的抽象视图、将该视图连接到真实代码的可信契约,以及证明必须满足的五个契约。  

Annotated map of the verified/src/login.rs file showing the structure of a formally verified login implementation. The diagram categorizes sections as specification-only definitions, trusted external contracts, data types, and five functions formally proved with Verus: login_flow, login_core, issue_token, lookup_target, and decide_login.
图 15。login.rs 的各个部分,按文件顺序排列。灰色是标头和类型,紫色是仅出现在契约中的数学内容,琥珀色是可信部分,绿色是已证明部分。

以下是两个不太明显的部分,已作删节。external_type_specification 引入了 Verus 未定义的类型。pool 保持不透明,而 customers 行则保持其字段可见: 

/// The connection pool, opaque to the proof: only 
/// the lookups' contracts say what it returns. 
#[verifier::external_type_specification] 
#[verifier::external_body] 
#[verifier::reject_recursive_types(DB)] 
pub struct ExPool(sqlx::Pool); 
... 
/// A customers row, with its fields visible to the proof. 
#[verifier::external_type_specification] 
pub struct ExCustomer(Customer); 

而 LoginError 将决策与 HTTP 响应分开,这使得 issue_token 能把每次拒绝固定到今天的状态码: 

/// Why a login gets no token. 
pub enum LoginError { 
    /// Neither an email nor a username was sent: 400 Bad Request. 
    MissingIdentity, 
    /// No such account, or the password does not match: 401 Unauthorized. 
    Unauthorized, 
    /// bcrypt could not read the stored hash, with its message: 500 Internal. 
    UnreadableHash(String), 
    /// The lookup query failed: 500 Internal, with sqlx's message. 
    Database(sqlx::Error), 
} 

在计划返回给你之前,两个审查代理会针对由意图产物派生出的形式化规范挑错,以确保高质量的转译,使规范符合你的要求,并且不会承诺超出证明所能表明的内容。规范精炼在后台运行并接收实时用户反馈,不断迭代,直到审查者一致认为规范是健全的。 

第 6 步:证明、检查、填补缺口 

对规范签字确认,是开发者审查的终点。此后的一切,即实现与证明,都由机器检查,这也是本文把篇幅花在规范而非证明上的原因。一旦开发者签字确认,Build plan 阶段(图 16)会把已批准的计划交给 pdd-prove,由其转化为一个小型任务图(图 16)。对于登录,共有七项任务:让 login.rs 在 backend crate 内于 Verus 下完成构建,证明决策、令牌和整个流程,然后为可信包装器和端到端登录编写测试。 

Screenshot of a PDD Kit build plan for a login-token issuance specification. The build workflow contains seven tasks, with the first task focused on making verified/src/login.rs successfully build under Verus while preserving contract meanings. Subsequent tasks cover proving login-related functions, testing trusted wrappers, running end-to-end login tests, and validating token-signing behavior.
图 16。Build plan 在开发机上将已批准的规范转化为七项任务。第一项让 login.rs 在 Verus 下完成构建,且不改变任何契约所承诺的内容,并停下来询问,而不是削弱契约。 

每项任务都运行相同的循环: 

  • 编码代理编写实现与证明,Verus 则对照派生的形式化规范加以检查。 
  • 可信边界内的任何内容都会获得计划所要求的测试。 
  • LLM 验证器并排阅读计划、规范和结果,并寻找缺口:没有证明且没有通过检查的需求。缺口会返回给编码代理,直到不再剩余。如果规范本身存在缺口,例如两条相互矛盾的需求,则会作为一项决策返回给开发者。 

证明的好坏只取决于其规范,因此 pdd-prove 也会检查规范。当模型自行编写规范,或被调优以生成证明时,它往往会落到弱不变量上:能够通过验证但几乎什么都排除不了的子句。它们确实证明了某些东西,只是很少是你关心的东西。我们称之为“氛围验证”。因此,确保你的意图与代理保持一致非常重要,而这也正是 PDD Kit 所擅长的。 

该循环严格要求不得中途改变目标。如果某个 async 构造无法在固定版本的 Verus 中表达,任务会停下来询问团队,而不是改用非 async 辅助函数或削弱契约。 

PDD Kit 如何消除各类 bug?变异检查是 PDD Kit 防范 vibe verification 的方式。pdd-prove 会在代码的临时副本中为每条 ensures 子句植入一个 bug,比如拒绝所有人,或在检查邮箱之前先检查用户名,而 Verus 必须在该变异体所针对的子句上拒绝每一个变异体。能通过的变异体意味着该子句没有任何约束,它会作为一个缺口返回。 

第 7 步:连同已验证代码一起审查意图

当这些任务通过后,pdd-prove 会创建 pull request。它们会添加一个 verified/ crate,其中包含 login_flow、它的各个部分、它们的证明,以及带有测试的可信包装器,并把真正的登录处理程序经由 login_flow 路由,同时保留现有的 HTTP 状态码。你的已验证逻辑会接入并加固生产环境的登录路径,而不是它的一份副本。 

开发者无需依赖对生成代码进行穷尽式逐行审查即可合并。审查一直发生在意图产物上,团队在那里拥有最终决定权。我们把更多审查重点从代码审查转移到了意图审查。该 pull request 充当一份回执,其描述会把每项登录需求标记为已经形式化验证或已经经验性检查。 

合并是证明加入团队常规工作流的环节。PDD Kit 的 pdd-ship 工作流会把 Verus 检查加入 CI,与经验性测试并列,因此此后对登录的每一次更改,无论出自人还是 agent,都必须继续针对同一份 spec 进行证明,而损坏的证明会像失败的测试一样使构建失败。而且因为证明覆盖每一个输入,PDD Kit 会裁剪那些只是重新检查已证明内容的测试,例如密码门的基于示例的测试,并保留守护可信边界的测试,从而使 CI 同时变得更强、更精简。 

证明说了什么、没说什么 

“Fully verified”很容易被夸大,所以下面正是我们所声称的内容。

  • 已证明。login_flow、login_core、lookup_target、decide_login和issue_token 的函数体对每一个输入都满足其契约。登录会选择正确的表,将请求的密码与它所指定账户的已存储哈希进行比较,签发一个带有该账户 id 及其表所给出角色的 token,并用今天的 400、401 或 500 且不带 token 拒绝其余一切。 
  • 可信且已测试。两次数据库查找、check_password 基于 bcrypt、时钟、token 签名、数据库错误消息以及处理程序的请求解包都位于证明之外,每一项都处在开发者已接受的一份假定契约之后。针对真实 bcrypt、真实 SQLite schema 和真实 router 的测试覆盖了它们。 
  • 假定。Verus、Rust 编译器与 Z3 (在新标签页中打开) 工具链,以及 Verus 的标准库 vstd (在新标签页中打开)。 

为什么是 Rust 

PDD Kit 目前只验证 Rust,因为那是 Verus 所支持的语言。如果你的代码库已经是 Rust,就无需迁移。其他语言的代码可以移植到 Rust,并针对同一份 spec 进行检查,非 Rust 项目可以通过绑定调用已验证的 Rust。 

还有一个不那么明显的好处。一旦对逐行穷尽式审查的依赖降低,可读性就不再是选择一门语言的主要理由。你可以出于速度和安全性来选择语言,并尽情优化,因为任何破坏 spec 的更改都会使证明失败。 

对 PDD Kit 可以期待什么

PDD Kit 是一个研究原型,目前只能验证 Rust,因为这正是 Verus 所支持的语言。其他语言的代码可以移植到 Rust,并对照同一份规范进行检查,非 Rust 项目也可以通过绑定调用经过验证的 Rust。证明仍然需要切实的努力,主要耗费在产出证明本身,而清晰的规范能降低这种努力,这也是 PDD Kit 如此强调先把意图弄对的原因。我们会从缺陷代价最高的地方入手,例如登录、支付或权限,再逐块验证代码库的其余部分。

Pet Store 的登录只是一个应用中的一块:一份任何人都能读懂的规范、一份证明代码与之相符的 Verus 证明,以及对证明所采信的一切所做的测试。我们希望把最薄弱的环节讲清楚。这些保证的强度只取决于那六个受信任的部分,其中两个承担了大部分分量:check_password 对应每一项密码承诺,两次查找则对应每一项关于令牌指向哪个账户的承诺。测试可以支持它们,但没有任何东西能证明它们。我们预计这一受信任边界会随时间显著缩小,从而让越来越多的代码能够得到形式化验证,我们也想看看这种方法能扩展到什么程度。

我们真正改变的是人们审查的对象。团队不再主要依赖对智能体所生成代码的逐行审查,而是用通俗语言审查其本意,并由证明把代码约束在这一本意上。计划本来就应当是契约,而现在智能体确实必须遵守它。

致谢

这项工作是 Microsoft Research Catalyst Lab、GitHub Next 与 Research in Software Engineering (RiSE) 小组的合作成果。我们感谢 GitHub Next 的 Maggie Appleton 和 Krzysztof Cieślak 在 Chopin 上的合作,也感谢 Nikhil Swamy、Lef Ioannidis、Janardhan Kulkarni 和 Shuvendu Lahiri 就形式化验证与意图形式化给出的反馈和讨论。我们还要感谢 F*/Pulse 与 Verus 团队的支持。最后,我们感谢 GitHub Next 的 Idan Gazit 对这次合作的支持。

常见问题

  • 你会的,而且是的,它会。证明表明的是代码符合规范,而不是规范就是你的本意。因此 PDD Kit 围绕现有的意图形式化研究来构建。pdd-plan 工作流会读取你的代码,在写下任何内容之前先提问,并把你的回答转化为一份 Verus 规范,外加一份由你批准的通俗语言计划,标出歧义而不是自行猜测。两个审查智能体会检查这份规范,而 pdd-prove 工作流会为每个条款植入一个缺陷,以捕捉那些能够验证通过但实际上什么都没有排除的条款。错误的规范仍然可能出现,因此 PDD Kit 强调把需求表述明确、识别歧义,并让开发者在验证开始之前参与审查和批准规范。 

  • 区别在于用什么把代码约束到计划上。

    方法由什么检查代码
    规范驱动开发没有任何东西强制执行规范
    测试驱动开发针对一部分输入样本的测试,往往写成与已构建内容相匹配 
    智能体检查自己的工作编写代码的同一个模型
    证明驱动开发Verus 会自动验证如下证明:你的代码满足你所批准的规范

    PDD 保留了 SDD 的规划循环,并在证明无法覆盖之处仍然使用测试。测试检查的是部分输入,而证明则确立:在其所声明的假设下,代码对形式模型所覆盖的全部输入都满足指定属性。 

  • 该证明是带有 Verus 构造注解的 Rust 代码,由 Verus 使用 Z3 求解器进行机械检查。它可在你的 Rust 构建所在的任何地方运行:pdd-prove 工作流在证明过程中运行它,而 pdd-ship 工作流将其加入构建和 CI,从而使损坏的证明导致构建失败。该检查是确定性的,不涉及模型。模型编写规范、代码和证明,但只有确定性的 Verus 运行才能决定它是否通过。检查耗时因代码规模和证明难度而异:小型模块通常只需数秒,较大的代码库则可能长达数分钟。

  • PDD Kit 将更多审查流程转向验证代码应当做什么,同时利用形式化验证为实现满足这些要求提供额外保证。开发者审查自然语言计划、形式化规范,以及超出证明范围的可信组件。由此产生的拉取请求会记录哪些内容经过了形式化验证、哪些经过了测试,以及哪些地方可能需要额外审查。在 Pet Store 全栈 Web 应用上,这种方法减少了对生成代码进行逐行详尽审查的依赖。

  • 我们选择 Verus,是因为它允许我们直接验证 Rust 代码,这与 PDD Kit 将形式化验证融入现有 Rust 开发工作流的重点相一致。 其他证明语言(例如 Lean、F*、Rocq)采用不同的形式化验证方法,各有取舍。PDD Kit 背后的技术也可以帮助将这些语言投入使用。

在新标签页中打开

文章 使用 PDD Kit 对智能体编写的全栈 Web 应用进行形式化验证 最先发布于 Microsoft Research。

来源:Microsoft Research · microsoft.com