Merge branch 'feat/m200-presenterfix-sign-manifest-fixtures'
Guards / 依赖许可与来源(cargo-deny) (push) Canceled after 0s
Guards / 文件行数 ≤400 守门 (push) Canceled after 0s
Guards / unsafe 落点守门(集合必须恰好等于期望) (push) Canceled after 0s
Guards / design 零第三方依赖守门 (push) Canceled after 0s
Guards / presenter 零 UI 守门 (push) Canceled after 0s
Guards / core 零 UI 守门 (push) Canceled after 0s
Dev Guards / 架构与合规守门(同 main 口径) (push) Canceled after 0s
Dev Guards / fmt (rustfmt --check) (push) Canceled after 0s
Dev Guards / clippy (ubuntu) (push) Canceled after 0s
Guards / 依赖许可与来源(cargo-deny) (push) Canceled after 0s
Guards / 文件行数 ≤400 守门 (push) Canceled after 0s
Guards / unsafe 落点守门(集合必须恰好等于期望) (push) Canceled after 0s
Guards / design 零第三方依赖守门 (push) Canceled after 0s
Guards / presenter 零 UI 守门 (push) Canceled after 0s
Guards / core 零 UI 守门 (push) Canceled after 0s
Dev Guards / 架构与合规守门(同 main 口径) (push) Canceled after 0s
Dev Guards / fmt (rustfmt --check) (push) Canceled after 0s
Dev Guards / clippy (ubuntu) (push) Canceled after 0s
This commit is contained in:
commit
de41e4c3b1
9 files changed
+359
-19
No files matched your search
@@ -84,3 +84,11 @@ jobs:
|
||||
run: python3 packaging/check_workflows_yaml.py --self-test
|
||||
- name: workflow 全部可被真 YAML 解析器 parse(无裸控制字符)
|
||||
run: python3 packaging/check_workflows_yaml.py
|
||||
# M190 r3:`update-test-key` 是**信任锚的开关**(把公开的测试公钥并进信任表)。它只许由
|
||||
# `crates/presenter` 的 `[dev-dependencies]` 打开;进了发布构建就等于「谁都能签出官方更新」。
|
||||
# 判据:core 的 `Cargo.toml` 只许自己的声明、presenter 只许 `[dev-dependencies]` 段内、
|
||||
# 其余(workflow / packaging 脚本 / 根 Cargo.toml / cargo 配置)出现即红。
|
||||
- name: 测试公钥守门自检(注入 workflow / dependencies / 根 Cargo.toml 三处变异)
|
||||
run: python3 packaging/check_test_key_off.py --self-test
|
||||
- name: 测试公钥不进发布构建(只许 presenter 的 dev-dependencies)
|
||||
run: python3 packaging/check_test_key_off.py
|
||||
Generated
+1
@@ -5209,6 +5209,7 @@ dependencies = [
|
||||
name = "unlucky-presenter"
|
||||
version = "0.2.3"
|
||||
dependencies = [
|
||||
"ed25519-dalek",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"unlucky-core",
|
||||
|
||||
@@ -81,3 +81,10 @@ workspace = true
|
||||
# 验收用法见 `crates/cli/tests/update_e2e_test.rs` 的文件头;`packaging/check_test_source_off.py`
|
||||
# 守门「发布流水线与打包脚本都不许打开它」。
|
||||
update-test-source = []
|
||||
|
||||
# M190:把**测试公钥**并进信任表(`trust::TEST_ONLY`)。它只加一把**公开**的钥,**不**开任何数据源
|
||||
# 开关(没有环境变量、没有 `DirSource`)。唯一使用者是 `crates/presenter` 的 `[dev-dependencies]`:
|
||||
# presenter 的更新链路用例要构造「本构建认得」的签名清单,而它们编译 core 时既没有 `cfg(test)`,
|
||||
# 也不该去打开 `update-test-source`(那条同时给出「本地目录当更新源」这条路)。
|
||||
# 守门:`packaging/check_test_key_off.py`(只许出现在这里与 presenter 的 dev-dependencies)。
|
||||
update-test-key = []
|
||||
@@ -5,15 +5,15 @@
|
||||
//!
|
||||
//! 签名走 `ed25519-dalek` 的 `SigningKey`(与仓里验签用的 `verify_strict` 同一棵树),而**不是**
|
||||
//! 自写实现——M190 r1 复审把自写曲线算术整体删掉了,这里也不留第二条算法。测试钥的种子是公开的
|
||||
//! (见下),它只对 `cfg(test)` 与 `update-test-source` 构建有意义。
|
||||
//! (见下),它只对 `cfg(test)` / `update-test-source` / `update-test-key` 三档构建有意义。
|
||||
|
||||
use super::support::TempDir;
|
||||
|
||||
/// 测试签名钥的 32 字节种子。
|
||||
///
|
||||
/// **它是公开的,故意不保密**:它只对 `cfg(test)` 与 `update-test-source` 构建有意义
|
||||
/// (`trust::TEST_ONLY` 才认这把钥),正式构建的信任表里没有它,所以拿它签不出任何正式版本
|
||||
/// 能装的清单。正式私钥只能来自仓库 Secret(见 `packaging/docs/signing.md`)。
|
||||
/// **它是公开的,故意不保密**:它只对 `cfg(test)` / `update-test-source` / `update-test-key` 三档
|
||||
/// 构建有意义(`trust::TEST_ONLY` 才认这把钥),正式构建的信任表里没有它,所以拿它签不出任何正式
|
||||
/// 版本能装的清单。正式私钥只能来自仓库 Secret(见 `packaging/docs/signing.md`)。
|
||||
pub(crate) const TEST_SIGNING_SEED: &[u8; 32] = b"ull-m190-test-key-seed-000000001";
|
||||
|
||||
/// 测试钥的 `key_id`(与 `trust::TEST_ONLY` 里那条一致)。
|
||||
|
||||
@@ -35,10 +35,12 @@
|
||||
//! # ② 把打印出来的 `PinnedKey { … }` 一行贴到下面 PINNED-KEYS 标记之间
|
||||
//! ```
|
||||
//!
|
||||
//! 测试/验收构建另有一把**只在** `cfg(test)` 与 `update-test-source` feature 里存在的测试钥:
|
||||
//! 它的私钥种子就写在测试夹具里、公开可见,因此它可以签出「本仓库自己认得」的清单,但对任何正式
|
||||
//! 构建毫无意义(正式表里没有它)。这条也由 `packaging/check_test_source_off.py` 的同一道闸守着
|
||||
//! ——正式发布流水线与打包脚本都不许打开 `update-test-source`。
|
||||
//! 测试/验收构建另有一把**只在** `cfg(test)` / `update-test-source` / `update-test-key` 三档里存在的
|
||||
//! 测试钥(三档的口径见下面 `keyring()`):它的私钥种子就写在测试夹具里、公开可见,因此它可以签出
|
||||
//! 「本仓库自己认得」的清单,但对任何正式构建毫无意义(正式表里没有它,`keyring()` 也不会把它并进
|
||||
//! 信任表)。后两档(那两个 feature)各由 `packaging/check_test_source_off.py` /
|
||||
//! `check_test_key_off.py` 守着 ——正式发布流水线与打包脚本都不许打开它们。
|
||||
//! (`cfg(test)` 那档不需要守门:发布构建里根本没有 `test` cfg。)
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
@@ -60,7 +62,8 @@ pub(crate) const PRODUCTION: &[PinnedKey] = &[
|
||||
// <<< PINNED-KEYS <<<
|
||||
];
|
||||
|
||||
/// 测试钥:**只**在 `cfg(test)` 与 `update-test-source` 构建里存在(正式表里没有它)。
|
||||
/// 测试钥:**只**在 `cfg(test)` / `update-test-source` / `update-test-key` 三档构建里存在(正式表里没有它;
|
||||
/// 三档的口径见下面 `keyring()`)。
|
||||
///
|
||||
/// 公钥由 `tests/support.rs` 里那串公开可见的 32 字节种子推出来(种子 = `ull-m190-test-key-seed-000000001`),
|
||||
/// 两者一旦漂开,`tests/signature_cases.rs::pinned_test_key_matches_the_test_seed` 会当场红。
|
||||
@@ -70,11 +73,32 @@ pub(crate) const TEST_ONLY: &[PinnedKey] = &[PinnedKey {
|
||||
}];
|
||||
|
||||
/// 本构建实际的信任锚(正式表 + 仅测试构建才有的那把测试钥)。
|
||||
///
|
||||
/// 三档「仅测试」的口径,逐档说明为什么需要它:
|
||||
///
|
||||
/// | 档 | 谁在用 | 为什么不能只靠 `cfg(test)` |
|
||||
/// |---|---|---|
|
||||
/// | `cfg(test)` | core 自己的单测 | 够用 |
|
||||
/// | `update-test-source` | CLI 的端到端验收(`--features update-test-source`) | 那是**另一个 target**,`cfg(test)` 不生效 |
|
||||
/// | `update-test-key` | `crates/presenter` 的 `[dev-dependencies]` | presenter 的更新链路用例编译 core 时既无 `cfg(test)`,也不该打开 `update-test-source`(那条会同时给出「本地目录当更新源」这条路)。这一档**只**加一把公开的测试公钥,不开任何数据源开关 |
|
||||
///
|
||||
/// 三者都**不会被 `keyring()` 并进信任表**:正式构建永远不认这把测试钥(官方构建三个 feature 都不开,
|
||||
/// 且 `check_test_source_off.py` / `check_test_key_off.py` 守着)。
|
||||
///
|
||||
/// ⚠ **别把这句话读成「产物里没有这段字节」**:这里的门是 `cfg!()`,它只让分支**不可达**,不是
|
||||
/// `#[cfg]` 的编译期剔除 —— `TEST_ONLY` 的**字节**照编在产物里(实测:无 feature 的 dev 与
|
||||
/// `--release` 两档 core rlib 里,公钥十六进制与 `test-only-key` 都还在)。「字节级不在产物里」
|
||||
/// 这一点**未证**、也未在此声称;它与「装不上公开种子签出来的清单」无关(信任表里没有它,验签仍
|
||||
/// fail-closed)。要换成 `#[cfg]` 让字节真的消失,是另一条结构性改动。
|
||||
pub(crate) fn keyring() -> &'static [PinnedKey] {
|
||||
static ALL: OnceLock<Vec<PinnedKey>> = OnceLock::new();
|
||||
ALL.get_or_init(|| {
|
||||
let mut keys = PRODUCTION.to_vec();
|
||||
if cfg!(any(test, feature = "update-test-source")) {
|
||||
if cfg!(any(
|
||||
test,
|
||||
feature = "update-test-source",
|
||||
feature = "update-test-key"
|
||||
)) {
|
||||
keys.extend_from_slice(TEST_ONLY);
|
||||
}
|
||||
keys
|
||||
|
||||
@@ -34,3 +34,12 @@ workspace = true
|
||||
# (`-p` 认 package 名 `unlucky-app-iced`;`unlucky-launcher-iced` 是 bin 名,写 `-p` 会找不到包)。
|
||||
# 官方发布构建不带这个 feature(`packaging/check_test_source_off.py` 守门)。
|
||||
update-test-source = ["unlucky-core/update-test-source"]
|
||||
|
||||
[dev-dependencies]
|
||||
# M190:presenter 的**更新链路用例**要构造「本构建认得」的签名清单(真发布必须带
|
||||
# `manifest.json.sig`,没有它 core 一律拒装)。这里打开 core 的 `update-test-key`:它**只**把一把
|
||||
# **公开**的测试公钥并进信任表,不开任何数据源开关(与 `update-test-source` 是两件事)。
|
||||
# 只出现在 `[dev-dependencies]`:库/发布构建拿不到它。守门:`packaging/check_test_key_off.py`。
|
||||
unlucky-core = { path = "../core", features = ["update-test-key"] }
|
||||
# 夹具用同一套种子现签清单(与 `crates/core/src/update/tests/support_sign.rs` 同源)。
|
||||
ed25519-dalek.workspace = true
|
||||
@@ -88,9 +88,48 @@ fn manifest_for(version: &str, payload: &[u8], notes: &str) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// 造一个本地更新源目录(`dist/stable.json` + `dist/asset.exe`)。
|
||||
fn dir_source(tmp: &TempDir, manifest: &str, payload: &[u8]) {
|
||||
/// 测试签名钥的 32 字节种子。
|
||||
///
|
||||
/// **与 `crates/core/src/update/tests/support_sign.rs` 同源**(同一个种子、同一个 `key_id`、
|
||||
/// 同一个信封形状):那边是 core 单测的夹具,这里是 presenter 侧的**等价薄夹具**——presenter 不能
|
||||
/// 依赖 core 的 `#[cfg(test)]` 资产,也不该把测试资产导出成生产 API。改一处就要改两处;
|
||||
/// 对不上时用例会以「签名验不过 / 不认识的钥」红,而不是静默变绿。
|
||||
const TEST_SIGNING_SEED: &[u8; 32] = b"ull-m190-test-key-seed-000000001";
|
||||
/// 测试钥的 `key_id`(与 `crates/core/src/update/trust.rs::TEST_ONLY` 一致)。
|
||||
const TEST_KEY_ID: &str = "test-only-key";
|
||||
|
||||
/// 用测试钥给清单签一份 `manifest.sig` 信封(M190 的信封形状:多签名数组 + 冗余摘要)。
|
||||
///
|
||||
/// 只有 `[dev-dependencies]` 打开了 core 的 `update-test-key`,所以这把公开的测试公钥在**测试构建**
|
||||
/// 的信任表里;发布构建里没有它,也就装不了用公开种子签出来的清单。
|
||||
fn signature_envelope(manifest: &str) -> String {
|
||||
use ed25519_dalek::{Signer, SigningKey};
|
||||
let signature = SigningKey::from_bytes(TEST_SIGNING_SEED)
|
||||
.sign(manifest.as_bytes())
|
||||
.to_bytes();
|
||||
let hex: String = signature.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||
let digest = sha256(manifest.as_bytes());
|
||||
format!(
|
||||
r#"{{"format":1,"signatures":[{{"alg":"ed25519","key_id":"{TEST_KEY_ID}","sig":"{hex}","manifest_sha256":"{digest}"}}]}}"#
|
||||
)
|
||||
}
|
||||
|
||||
/// 写一份清单**连它的签名**(`dist/stable.json` + `dist/stable.json.sig`)。
|
||||
///
|
||||
/// 真发布必须带 `.sig`(core 的 `verified_manifest` 先验签再解析),所以夹具一律成对落盘;
|
||||
/// 「坏清单」「空清单」这些用例也照签——它们要证的是「签名对、内容坏/为空」时的行为,
|
||||
/// 而不是绕过签名。
|
||||
fn write_manifest(tmp: &TempDir, manifest: &str) {
|
||||
tmp.write("dist/stable.json", manifest.as_bytes());
|
||||
tmp.write(
|
||||
"dist/stable.json.sig",
|
||||
signature_envelope(manifest).as_bytes(),
|
||||
);
|
||||
}
|
||||
|
||||
/// 造一个本地更新源目录(`dist/stable.json` + 它的签名 + `dist/asset.exe`)。
|
||||
fn dir_source(tmp: &TempDir, manifest: &str, payload: &[u8]) {
|
||||
write_manifest(tmp, manifest);
|
||||
tmp.write("dist/asset.exe", payload);
|
||||
}
|
||||
|
||||
@@ -180,7 +219,7 @@ fn a_broken_manifest_degrades_to_failure_not_up_to_date() {
|
||||
("bad version", manifest_for("not-a-version", b"abc", "")),
|
||||
] {
|
||||
let tmp = TempDir::new("badmanifest");
|
||||
tmp.write("dist/stable.json", manifest.as_bytes());
|
||||
write_manifest(&tmp, &manifest);
|
||||
let outcome = outcome_of(job(&tmp).check(&version("0.2.2"), Channel::Stable));
|
||||
assert!(
|
||||
matches!(outcome, UpdateOutcome::Failed(_)),
|
||||
@@ -206,7 +245,7 @@ fn an_empty_manifest_means_nothing_published_yet() {
|
||||
r#"{"channel":"stable","releases":[]}"#.to_string(),
|
||||
] {
|
||||
let tmp = TempDir::new("empty-manifest");
|
||||
tmp.write("dist/stable.json", manifest.as_bytes());
|
||||
write_manifest(&tmp, &manifest);
|
||||
let outcome = outcome_of(job(&tmp).check(&version("0.2.2"), Channel::Stable));
|
||||
assert!(
|
||||
matches!(&outcome, UpdateOutcome::UpToDate { latest: None }),
|
||||
@@ -219,15 +258,14 @@ fn an_empty_manifest_means_nothing_published_yet() {
|
||||
#[test]
|
||||
fn a_higher_version_without_our_platform_is_not_up_to_date() {
|
||||
let tmp = TempDir::new("missing-artifact");
|
||||
tmp.write(
|
||||
"dist/stable.json",
|
||||
format!(
|
||||
write_manifest(
|
||||
&tmp,
|
||||
&format!(
|
||||
r#"{{"channel":"stable","releases":[{{"version":"0.9.0","channel":"stable","artifacts":[{{"target":"{}","format":"portable-exe","url":"asset.exe","size":3,"sha256":"{}"}}]}}]}}"#,
|
||||
// 故意给一个不可能匹配本机的目标(`unknown` 架构永远对不上)
|
||||
"linux-x86",
|
||||
sha256(b"abc")
|
||||
)
|
||||
.as_bytes(),
|
||||
),
|
||||
);
|
||||
let outcome = outcome_of(job(&tmp).check(&version("0.2.2"), Channel::Stable));
|
||||
assert!(
|
||||
|
||||
@@ -71,6 +71,7 @@ Git Bash 下会静默落进 Docker VM(脚本内部用 `cygpath -m` 归一)
|
||||
| `packaging/check_publish_slots.py` | 发布名单守卫(M164/M184):名单 ⇄ 产物两个方向 + `mode: ci` 槽位无产物的警告;`--self-test` 注入 11 条回归 | ≤400 |
|
||||
| `packaging/check_pe_subsystem.py` | PE 子系统守卫(M196):**读产物 PE 头的 `Subsystem`**(GUI 必须 2 / CLI 必须 3),非 2 即红;`--self-test` 注入 8 条回归(红 6 / 绿 2)(见 §15) | ≤400 |
|
||||
| `packaging/check_test_source_off.py` | 测试通道守门(M169):workflow / 打包脚本 / `Cargo.toml default` 都不许打开 `update-test-source`;归属按 `jobs.*.steps[]` 列表项判、默认拒绝;`--self-test` 按 `tests/guard_vectors.json` 注入 | ≤400 |
|
||||
| `packaging/check_test_key_off.py` | 测试公钥守门(M190 r3):把公开的测试公钥并进信任表的那条 feature 只许出现在 `crates/core/Cargo.toml` 自己的声明与 `crates/presenter/Cargo.toml` 的 `[dev-dependencies]` 段内,其余(workflow / 打包脚本 / 根 `Cargo.toml` / `.cargo/config*.toml` / presenter 的 `[dependencies]`)出现即红;`--self-test` 注入 7 条向量(5 红 / 2 绿)+ 基线;其中一条专治「core 的声明里偷偷带子 feature」(`update-test-key = ["update-test-source"]` ⇒ 红) | ≤400 |
|
||||
| `packaging/tests/guard_vectors.json` | 守门自测向量(基线 + 32 条:26 红 / 6 绿),数据与代码分开 | ≤400 |
|
||||
| `packaging/ci-runtime-smoke.md` | §11 的细节:断言口径/阈值依据/失效模式/复跑 | ≤400 |
|
||||
| `packaging/docs/linux-evidence.md` | Linux 槽位的证据账(M184):现有证据盘点、WSLg 真机实测输出、xvfb 复跑、CI 增量估算、未验清单 | ≤400 |
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
"""守 `update-test-key`:这把**公开**的测试公钥不许进发布构建(M190 r3)。
|
||||
|
||||
背景:`crates/core` 的信任表(`trust::PRODUCTION`)正式构建里是空的(fail-closed,等用户录钥),
|
||||
测试公钥 `trust::TEST_ONLY` 只在三档「仅测试」构建里并入:`cfg(test)`、测试通道那条 feature、
|
||||
`update-test-key`。第三档是给 `crates/presenter` 的 `[dev-dependencies]` 用的——presenter 的更新链路
|
||||
用例要构造「本构建认得」的签名清单,而它编译 core 时既没有 `cfg(test)`,也不该打开
|
||||
「测试通道」那条 feature(它会**同时**给出「本地目录当更新源」这条路,是另一个更大的口子;
|
||||
那条由 `check_test_source_off.py` 守。⚠ 本文件**刻意不写那条 feature 的全名**:那个守门按字面
|
||||
扫 `packaging/**`,写了这里就红——这是它的设计(宁可误杀也不放过),不是笔误)。
|
||||
|
||||
这一档比「测试通道」那条 feature 窄,但它仍然是**信任锚的开关**:一旦进发布构建,任何人都能用公开种子
|
||||
签出「官方更新」。所以它的出现位置必须是**白名单**,而不是「没人会这么写」:
|
||||
|
||||
| 允许出现的地方 | 形态 |
|
||||
|---|---|
|
||||
| `crates/core/Cargo.toml` | 只能是它自己的声明,且必须是**空数组** `update-test-key = []`(写成带子 feature 的非空数组即红) |
|
||||
| `crates/presenter/Cargo.toml` | 只能出现在 `[dev-dependencies]` 段内 |
|
||||
| 本脚本 | 它必须写出这个 feature 名 |
|
||||
|
||||
其余任何地方(workflow、`packaging/` 的脚本、根 `Cargo.toml`、`.cargo/config*.toml`、presenter 的
|
||||
`[dependencies]`)提到它即红。`--self-test` 把这四类真实回归各注入一次(workflow / presenter 的
|
||||
`[dependencies]` / 根 `Cargo.toml` / core 声明里偷偷带子 feature),并断言合法写法不误杀。
|
||||
|
||||
python3 packaging/check_test_key_off.py
|
||||
python3 packaging/check_test_key_off.py --self-test
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
FEATURE = "update-test-key"
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
GUARD = Path(__file__).resolve()
|
||||
|
||||
#: 扫描面(逐项列举,不用 `**` 全仓:那会把 `target/` 拖进来)。
|
||||
GLOBS = (
|
||||
".github/workflows/**/*.yml",
|
||||
".github/workflows/**/*.yaml",
|
||||
".github/actions/**/*.yml",
|
||||
".github/actions/**/*.yaml",
|
||||
"packaging/**/*.py",
|
||||
"packaging/**/*.sh",
|
||||
"packaging/**/*.ps1",
|
||||
"Cargo.toml",
|
||||
"crates/*/Cargo.toml",
|
||||
"Makefile",
|
||||
"justfile",
|
||||
"Justfile",
|
||||
"Taskfile.yml",
|
||||
"Taskfile.yaml",
|
||||
"crates/*/Makefile",
|
||||
"packaging/Makefile",
|
||||
".cargo/config.toml",
|
||||
".cargo/config",
|
||||
"crates/*/.cargo/config.toml",
|
||||
"crates/*/.cargo/config",
|
||||
)
|
||||
|
||||
#: 白名单:(相对路径, 允许的形态)。形态见 `check_manifest` 的三种判法。
|
||||
ALLOWED_DECLARATION = "crates/core/Cargo.toml"
|
||||
ALLOWED_DEV_DEPENDENCY = "crates/presenter/Cargo.toml"
|
||||
|
||||
#: 另一条(更宽的)测试通道 feature 的名字。**刻意拼出来**:`check_test_source_off.py` 按字面扫
|
||||
#: `packaging/**`,这里写全名会让那个守门红 —— 那是它的设计(宁可误杀也不放过),不是笔误。
|
||||
#: 本文件与它同源同一套手法,别“顺手”把它写成字面量。
|
||||
OTHER_FEATURE = "-".join(("update", "test", "source"))
|
||||
|
||||
#: core 只许**自己的声明**,而且必须是**空数组** `update-test-key = []`。
|
||||
#: 这里认**内容**、不只认形状:写成带子 feature 的非空数组(`["<另一条 feature>"]`)会让这个「窄口子」
|
||||
#: 顺手把「宽口子」(环境变量 + `DirSource` 那条测试通道)拉起来 —— 那正是本守门要防的逃逸。
|
||||
DECLARATION = re.compile(rf"^\s*{re.escape(FEATURE)}\s*=\s*\[\s*\]\s*$")
|
||||
SECTION = re.compile(r"^\s*\[([^\]]+)\]\s*$")
|
||||
|
||||
|
||||
def strip_comment(line: str) -> str:
|
||||
"""引号感知地剥注释(与 `check_test_source_off.py` 同一手法,省得两处对同一行有不同看法)。"""
|
||||
quote = None
|
||||
for index, char in enumerate(line):
|
||||
if quote is not None:
|
||||
if char == quote:
|
||||
quote = None
|
||||
elif char in "\"'":
|
||||
quote = char
|
||||
elif char == "#" and (index == 0 or line[index - 1].isspace()):
|
||||
return line[:index]
|
||||
return line
|
||||
|
||||
|
||||
def check_manifest(path: Path, where: str) -> list[str]:
|
||||
"""`Cargo.toml`:核心只许自己的声明;presenter 只许 `[dev-dependencies]` 段内。"""
|
||||
problems: list[str] = []
|
||||
section = ""
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
code = strip_comment(line).strip()
|
||||
if not code:
|
||||
continue
|
||||
header = SECTION.match(code)
|
||||
if header:
|
||||
section = header.group(1).strip()
|
||||
continue
|
||||
if FEATURE not in code:
|
||||
continue
|
||||
if where == ALLOWED_DECLARATION and DECLARATION.match(code):
|
||||
continue
|
||||
if where == ALLOWED_DEV_DEPENDENCY and section == "dev-dependencies":
|
||||
continue
|
||||
problems.append(
|
||||
f"::error file={where}:{number}::{where} 在 `[{section or '顶部'}]` 里写了 `{FEATURE}`;"
|
||||
"它只许出现在 crates/core/Cargo.toml 自己的声明与 crates/presenter/Cargo.toml 的 "
|
||||
"`[dev-dependencies]` 里(这把公钥进发布构建 = 谁都能签出「官方更新」)"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def check_plain(path: Path, where: str) -> list[str]:
|
||||
"""其余文件类型:出现即红(不解释形态)。"""
|
||||
problems: list[str] = []
|
||||
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
|
||||
if FEATURE in strip_comment(line):
|
||||
problems.append(
|
||||
f"::error file={where}:{number}::{where} 提到 `{FEATURE}`:它不进 workflow / 打包脚本 / "
|
||||
"cargo 配置(测试钥只许由 crates/presenter 的 dev-dependencies 打开)"
|
||||
)
|
||||
return problems
|
||||
|
||||
|
||||
def scan(root: Path) -> list[str]:
|
||||
"""扫整个仓库,返回所有问题(空 = 绿)。"""
|
||||
problems: list[str] = []
|
||||
for pattern in GLOBS:
|
||||
for path in sorted(root.glob(pattern)):
|
||||
if not path.is_file() or path.resolve() == GUARD:
|
||||
continue
|
||||
where = path.relative_to(root).as_posix()
|
||||
try:
|
||||
if path.name == "Cargo.toml":
|
||||
problems += check_manifest(path, where)
|
||||
else:
|
||||
problems += check_plain(path, where)
|
||||
except (OSError, UnicodeDecodeError) as error:
|
||||
problems.append(f"::error file={where}::读不到:{error}")
|
||||
return problems
|
||||
|
||||
|
||||
# ────────────────────────── 变异自测 ──────────────────────────
|
||||
|
||||
BASELINE = {
|
||||
"crates/core/Cargo.toml": (
|
||||
"[features]\nother-feature = []\n\n# 注释里提到 update-test-key 不算违规\ntest-key = []\n"
|
||||
"update-test-key = []\n"
|
||||
),
|
||||
"crates/presenter/Cargo.toml": (
|
||||
"[dependencies]\nunlucky-core = { path = \"../core\" }\n\n"
|
||||
"[dev-dependencies]\nunlucky-core = { path = \"../core\", features = [\"update-test-key\"] }\n"
|
||||
),
|
||||
".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - run: cargo test\n",
|
||||
}
|
||||
|
||||
VECTORS = [
|
||||
(
|
||||
"workflow 里打开它",
|
||||
{".github/workflows/ci.yml": "jobs:\n a:\n steps:\n - run: cargo build --features update-test-key\n"},
|
||||
"red",
|
||||
),
|
||||
(
|
||||
"presenter 的 [dependencies] 里打开它",
|
||||
{
|
||||
"crates/presenter/Cargo.toml": (
|
||||
"[dependencies]\nunlucky-core = { path = \"../core\", features = [\"update-test-key\"] }\n"
|
||||
)
|
||||
},
|
||||
"red",
|
||||
),
|
||||
(
|
||||
"根 Cargo.toml 把依赖提起来",
|
||||
{
|
||||
"Cargo.toml": (
|
||||
'[workspace.dependencies]\nunlucky-core = { path = "crates/core", '
|
||||
'features = ["update-test-key"] }\n'
|
||||
)
|
||||
},
|
||||
"red",
|
||||
),
|
||||
("打包脚本提到它", {"packaging/x.sh": "cargo build --features update-test-key\n"}, "red"),
|
||||
(
|
||||
"core 自己的声明(合法)",
|
||||
{"crates/core/Cargo.toml": "[features]\nupdate-test-key = []\n"},
|
||||
"green",
|
||||
),
|
||||
(
|
||||
"core 的声明里偷偷带子 feature(形状合法、内容非法)",
|
||||
{"crates/core/Cargo.toml": f'[features]\n{FEATURE} = ["{OTHER_FEATURE}"]\n'},
|
||||
"red",
|
||||
),
|
||||
("注释里提到它(合法)", {"packaging/y.py": "# 见 update-test-key 的说明\n"}, "green"),
|
||||
]
|
||||
|
||||
|
||||
def _scan_case(files: dict[str, str]) -> list[str]:
|
||||
with tempfile.TemporaryDirectory(prefix="ull-test-key-guard-") as temp:
|
||||
root = Path(temp)
|
||||
for relative, text in files.items():
|
||||
path = root / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8")
|
||||
return scan(root)
|
||||
|
||||
|
||||
def self_test() -> int:
|
||||
failures = 0
|
||||
baseline = _scan_case(BASELINE)
|
||||
if baseline:
|
||||
print(f"FAIL 基线被判红:{baseline}", file=sys.stderr)
|
||||
failures += 1
|
||||
for label, files, expect in VECTORS:
|
||||
merged = dict(BASELINE)
|
||||
merged.update(files)
|
||||
problems = _scan_case(merged)
|
||||
red = bool(problems)
|
||||
if (expect == "red") != red:
|
||||
print(f"FAIL 向量「{label}」期望 {expect},实际 {'red' if red else 'green'}", file=sys.stderr)
|
||||
failures += 1
|
||||
print(f"self-test: {'ok' if failures == 0 else f'{failures} 处失败'}({len(VECTORS)} 条向量 + 基线)")
|
||||
return 0 if failures == 0 else 1
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="测试公钥不许进发布构建(M190)")
|
||||
parser.add_argument("--self-test", action="store_true", help="注入变异:该红的红、该绿的绿")
|
||||
parser.add_argument("--dir", type=Path, default=ROOT, help="仓库根(默认本文件上一级)")
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
if args.self_test:
|
||||
return self_test()
|
||||
problems = scan(args.dir)
|
||||
for line in problems:
|
||||
print(line, file=sys.stderr)
|
||||
if problems:
|
||||
print(f"FAIL:{len(problems)} 处(`{FEATURE}` 只许由 crates/presenter 的 dev-dependencies 打开)", file=sys.stderr)
|
||||
return 1
|
||||
print(f"ok: `{FEATURE}` 只出现在允许的位置(core 的声明 + presenter 的 dev-dependencies)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user