跳到正文
Microsoft Research· Alex Lavaee, Matthai Philipose·· 18 天前精选AI 评分68

Microsoft Research 推出 PDD Kit,用形式化验证检查智能体编写的全栈 Web 应用

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

AI 导读

Microsoft Research 介绍 PDD Kit,这是一款研究原型工具,可将团队确认的自然语言意图转成 Verus 形式化规格,并为智能体编写的 Rust 代码生成证明;无法证明的部分则通过测试检查。

推荐理由

PDD Kit 将自然语言需求、形式化规格与机器证明串成可审查流程,Pet Store 登录案例也清楚展示了证明覆盖范围及其依赖的信任边界。

正文 · 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)因大量低质量、高数量的测试而不断膨胀,测试覆盖率看起来很健康,而你要求的内容与最终交付的内容之间的差距,会一直隐藏到出现错误报告或棘手的边界情况。

那么,当代理生成的代码量越来越大时,如何可靠地扩展审查能力?代理代码通常会以两种方式失败,而细心的审查者通常能够发现这些问题:遗漏了某些显然必要的内容,或执行了某些显然错误的操作。仅靠测试无法弥合这一差距,因为测试只能覆盖程序所有可能行为中的极小一部分。要弥合这一差距,需要另一种机制,而这正是证明发挥作用的地方。

审查会问:“这看起来正确吗?”证明则会回答:“这正确吗?”数学证明能够表明,代码对每一个输入都符合其规范,包括测试套件可能遗漏的输入。与单独测试相比,这能为已指定的属性提供更强的保证,尤其是在无法实际进行逐行审查时。

证明过去对于日常软件来说成本过高。你需要专家、陌生的语言、规模比代码大许多倍的证明,而且开发证明要花费数年时间,但此后两件事改变了这一局面。首先,编码代理近期取得的进展,让它们越来越能够根据定义明确的规格说明协助生成形式化证明。其次,代理现在也能更好地帮助你编写形式化规格说明。我们将这种新型软件开发范式称为 证明驱动开发(PDD)。PDD Kit 是我们为此打造的工具包。

PDD Kit 的工作方式

对于形式化方法而言,PDD Kit 大致相当于Spec Kit(在新标签页中打开)对于规格驱动开发的作用。它作为合作伙伴运行于Chopin(在新标签页中打开)中。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 进行证明驱动开发。团队成员确定意图。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(在新标签页中打开),负责处理库存、促销、订单和结账。店面是一个编译为 WebAssembly(在新标签页中打开) 的 Leptos(在新标签页中打开) 应用。两部分加起来约有 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 的建议,但开发者希望做得更多。处理程序负责等待查询结果并签署令牌,而这段胶合代码恰恰是重构时可能悄悄调换两行代码的地方。因此,在意图审查时,开发者选择为登录处理程序单独编写异步规范,让证明也覆盖这段胶合代码,而不是信任它(图 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。每个函数在等待后若成功,就会准确返回其对应表中与该电子邮件地址或用户名匹配的那一行;否则返回无结果。 
  • 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)。一项条目在实际运行前会标为计划中;运行后,则会记录命令的结果以及运行时对应的提交。

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 的计划测试,在测试尚不存在时预先写好。计划将通过的测试标记为证据,而非证明。 

计划同样明确列出了无人做出保证的内容:登录流程最终是否会完成、超出范围的时钟是否会触发 panic、尝试的时序或频率,以及其他端点如何读取角色。 

第 5 步:阅读规格

意图文档是团队评审的内容。它是 PDD Kit 以 Verus 契约编写的形式化规格的通俗语言版本。你可能会想,是不是现在有人必须读证明而不是读代码。不需要,因为编码代理会编写证明,而 Verus 会检查其中的每一步。只要 Verus 接受了证明,无论是否有人阅读,它都成立。证明以规格为准,因此人们评审的是规格;而这份规格很短,几分钟就能学会阅读。每个函数都有一个 ensures 块:关于其结果 r 的陈述,这些陈述必须对每种可能的输入都成立。构建时 Verus 会检查这些陈述;如果任何子句哪怕对一种输入可能不成立,构建就会失败,Verus 也会指出该子句。每个子句都可以读作一个 if-then,图 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,这就把密码检查和令牌关联了起来。举例来说,想象一下这样一个漏洞:登录时用一个账户检查密码,却为另一个账户签发令牌。Bob 用自己的正确密码登录,却拿到了 Alice 账户的令牌。每一步单独看起来都没问题,但这个子句能捕捉到问题,因为密码检查和令牌必须指向同一个账户。这类连接错误,测试套件很少会想到要检查。规范还必须在不实际运行 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 表中的行;再否则就是 none。它看起来像 Rust,但其实是一个永不运行、只出现在契约中的数学定义。这样的代码称为幽灵代码,因为验证器会检查它,但编译器会将它从程序中删除。借助它,开发者提出的两句话要求最终被写成了 login_flow(图 12)上的八个 ensures 子句。 

/// 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 是异步的:它会等待数据库查询。Verus 可以为异步函数添加契约,但有一条规则值得了解(图 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 等待查询并调用 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:证明、检查、弥合差距 

开发者的审查在批准规范时结束。之后的所有工作——实现和证明——都由机器检查,因此本文重点讨论规范,而非证明。开发者批准后,构建计划阶段(图 16)会将获批计划交给 pdd-prove,由它将计划转换为一个小型任务图(图 16)。对于登录功能,这包含七项任务:让 login.rs 在后端 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。构建计划将获批的规范转换为开发机器上的七项任务。第一项任务是在不改变任何契约承诺的前提下,让 login.rs 通过 Verus 构建;如果做不到,就暂停并询问,而不是削弱契约。 

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

  • 编码代理编写实现和证明,Verus 则根据推导出的形式化规范对它们进行检查。 
  • 计划要求对可信边界内的所有内容进行测试。 
  • LLM 验证器会并排阅读计划、规范和结果,寻找差距:没有证明、也没有通过检查的要求。发现的差距会返回给编码代理,直到全部消除。如果规范本身存在差距,例如两项要求相互矛盾,就会将问题交还开发者作出决定。 

证明的质量取决于规范,因此 pdd-prove 也会检查规范。模型自行编写规范,或经过调优以生成证明时,往往会采用薄弱的不变式:这些条款虽然能通过验证,却几乎没有排除任何情况。它们确实能证明某些东西,只不过很少是你真正关心的东西。我们称之为“凭感觉验证”。这就是为什么确保你的意图与代理保持一致如此重要,也是 PDD Kit 的优势所在。 

这个循环严格禁止移动目标。如果异步结构无法用固定版本的 Verus 表达,任务就会暂停并询问团队,而不会改用非异步辅助函数,也不会削弱契约。 

PDD Kit 如何消除一类错误?变异检查是 PDD Kit 防止凭感觉验证的方式。pdd-prove 会在代码的临时副本中,为每条 ensures 子句植入一个错误,例如拒绝所有人,或在检查邮箱前先检查用户名;Verus 必须针对目标子句拒绝每个变异版本。若某个变异版本通过,就意味着该子句没有约束任何内容,它会作为一个缺口反馈出来。 

第 7 步:结合已验证代码审查意图

任务通过后,pdd-prove 会创建拉取请求。其中会添加一个 verified/ crate,包含 login_flow、其组件、相应证明,以及带有测试的可信封装,并让实际登录处理程序经由 login_flow 运行,同时保留现有的 HTTP 状态码。经过验证的逻辑会集成到生产登录路径中并增强它,而不是集成到它的副本中。 

开发者无需逐行详尽审查生成的代码,也能合并更改。整个过程中,团队一直在审查意图工件,并由团队做最终决定。我们把更多审查重点从代码审查转向了意图审查。拉取请求相当于一份凭据,其说明会将每项登录要求标注为已通过形式化验证或已通过实证检查。 

合并是让证明融入团队日常工作流的环节。PDD Kit 的 pdd-ship 工作流会将 Verus 检查与实证测试一同加入 CI,因此之后无论由人还是智能体修改登录功能,都必须继续针对同一规范进行证明;证明失败就会像测试失败一样导致构建失败。而且由于证明涵盖所有输入,PDD Kit 会删去那些只是在重复验证已证明内容的测试,例如基于示例的密码门禁测试,并保留用于守护可信边界的测试,因此 CI 的可靠性和精简程度会同时提升。 

证明能说明什么,不能说明什么 

“完全验证”很容易被夸大,下面准确说明我们所作的承诺。

  • 已证明。 login_flow、login_core、lookup_target、decide_login 和 issue_token 的函数体对所有输入都满足其契约。登录会选择正确的表,将请求中的密码与所指定账户存储的哈希进行比较,使用该账户的 ID 和其所在表中指定的角色签发令牌,并对其他所有情况返回现有的 400、401 或 500 状态码,且不签发令牌。 
  • 可信且经过测试。 两次数据库查询、check_password 在 bcrypt 上的操作、时钟、令牌签名、数据库错误消息,以及处理程序对请求的解包,都不在证明范围内;每项都由开发者认可的假设契约加以约束。针对真实 bcrypt、真实 SQLite 架构和真实路由器的测试覆盖了这些部分。 
  • 假设。 Verus、Rust 编译器和 Z3(在新标签页中打开) 工具链,以及 Verus 的标准库 vstd(在新标签页中打开)。 

为什么选择 Rust 

目前 PDD Kit 只验证 Rust,因为 Verus 面向的语言就是 Rust。如果你的代码库已经使用 Rust,就无需迁移。其他语言编写的代码可以移植到 Rust,并依据同一规范进行检查;非 Rust 项目也可以通过绑定调用经过验证的 Rust 代码。 

此外还有一个不那么显而易见的优势。减少对逐行详尽审查的依赖后,可读性就不再是选择语言的首要理由。你可以根据速度和安全性选择语言,并尽情优化,因为任何破坏规范的更改都会导致证明失败。 

PDD Kit 使用预期

PDD Kit 是一个研究原型,目前只能验证 Rust,因为 Verus 支持的语言是 Rust。其他语言的代码可以移植到 Rust,并依据同一规范进行检查;非 Rust 项目也可以通过绑定调用经过验证的 Rust 代码。证明仍然需要投入大量精力,主要花在构造证明本身,而清晰的规范有助于减少这部分工作,这也是 PDD Kit 很大一部分工作都围绕着先准确理解意图展开的原因。我们会从出错代价最高的地方着手,例如登录、支付或权限,然后逐步验证代码库的其余部分。

Pet Store 的登录只是一个应用中的一部分:一份任何人都能读懂的规范、一份证明代码符合规范的 Verus 证明,以及针对证明所依赖的所有可信部分编写的测试。我们希望坦诚指出其中最薄弱的环节。保证的可靠程度取决于这六个可信部分,其中两项承担了大部分重任:check_password负责兑现所有与密码有关的承诺,而两次查找则负责兑现所有关于令牌指向哪个账户的承诺。测试可以为它们提供支持,但没有任何证明能验证它们。我们预计,随着时间推移,这个可信边界会大幅缩小,从而让越来越多的代码能够通过形式化验证;我们也希望了解这种方法的适用范围能扩展到多大。

我们真正改变的是人们审查的内容。团队不再主要依赖逐行审查智能体生成的代码,而是审查它的预期行为——用通俗易懂的语言描述,而证明则确保代码符合这些要求。计划本应始终是契约,而现在智能体真的必须遵守它。

致谢

这项工作由 Microsoft Research Catalyst Lab、GitHub Next 和软件工程研究(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