test(credentials): 登记 B-02 生产验收

This commit is contained in:
2026-09-09 09:07:04 +08:00
parent 37ff31b96c
commit 9c2fbc761f
4 changed files with 270 additions and 14 deletions
+14 -1
View File
@@ -55,7 +55,7 @@ def test_config_rejects_personal_vault_plaintext_secrets_and_unconfirmed_roots(t
assert (existing / "keep.txt").read_text(encoding="utf-8") == "keep" assert (existing / "keep.txt").read_text(encoding="utf-8") == "keep"
def test_missing_driver_is_a_junit_failure_and_never_a_skip(tmp_path): def test_missing_driver_is_a_junit_failure_and_never_a_skip(tmp_path, monkeypatch):
data_root = tmp_path / "isolated" data_root = tmp_path / "isolated"
config_path = config(tmp_path / "config.json", data_root) config_path = config(tmp_path / "config.json", data_root)
report = tmp_path / "report" report = tmp_path / "report"
@@ -63,6 +63,7 @@ def test_missing_driver_is_a_junit_failure_and_never_a_skip(tmp_path):
suite="sidecar", case="A-01", config=str(config_path), report_dir=str(report), suite="sidecar", case="A-01", config=str(config_path), report_dir=str(report),
list_cases=False, json=False, list_cases=False, json=False,
) )
monkeypatch.setattr(runner, "repository_changes", lambda: ())
assert runner.execute(args, {}) == 1 assert runner.execute(args, {}) == 1
result = json.loads((report / "cases" / "A-01.json").read_text(encoding="utf-8")) result = json.loads((report / "cases" / "A-01.json").read_text(encoding="utf-8"))
summary = json.loads((report / "summary.json").read_text(encoding="utf-8")) summary = json.loads((report / "summary.json").read_text(encoding="utf-8"))
@@ -74,6 +75,18 @@ def test_missing_driver_is_a_junit_failure_and_never_a_skip(tmp_path):
assert "skipped=\"0\"" in junit assert "skipped=\"0\"" in junit
def test_execution_rejects_uncommitted_non_vault_source(tmp_path, monkeypatch):
config_path = config(tmp_path / "config.json", tmp_path / "isolated")
args = Namespace(
suite="sidecar", case="A-01", config=str(config_path), report_dir=str(tmp_path / "report"),
list_cases=False, json=False,
)
monkeypatch.setattr(runner, "repository_changes", lambda: ("scripts/changed.py",))
with pytest.raises(runner.AcceptanceError, match="SOURCE_TREE_DIRTY"):
runner.execute(args, {})
assert not (tmp_path / "report").exists()
def test_driver_result_must_supply_assertions_metrics_and_zero_exit(tmp_path): def test_driver_result_must_supply_assertions_metrics_and_zero_exit(tmp_path):
driver = tmp_path / "driver.py" driver = tmp_path / "driver.py"
driver.write_text("", encoding="utf-8") driver.write_text("", encoding="utf-8")
+135 -11
View File
@@ -807,22 +807,35 @@ mod tests {
assert!(!broker.is_locked()); assert!(!broker.is_locked());
} }
#[test] #[test]
fn python_fernet_migration_is_verified_idempotent_and_preserves_sources() { fn b02_fernet_migration_matrix_is_atomic_verified_and_idempotent() {
let fixture: serde_json::Value = let fixture: serde_json::Value =
serde_json::from_str(include_str!("../tests/fixtures/fernet-python.json")).unwrap(); serde_json::from_str(include_str!("../tests/fixtures/fernet-python.json")).unwrap();
let temp = tempfile::tempdir().unwrap(); let temp = tempfile::tempdir().unwrap();
let old = temp.path().join("legacy"); let old = temp.path().join("legacy");
fs::create_dir(&old).unwrap(); fs::create_dir(&old).unwrap();
let source = serde_json::to_vec(&fixture["tokens"]).unwrap(); let source = serde_json::to_vec(&fixture["tokens"]).unwrap();
fs::write(old.join("credentials.json"), &source).unwrap(); let source_path = old.join("credentials.json");
fs::write(old.join("master.key"), fixture["key"].as_str().unwrap()).unwrap(); let key_path = old.join("master.key");
let legacy_key = fixture["key"].as_str().unwrap();
fs::write(&source_path, &source).unwrap();
fs::write(&key_path, legacy_key).unwrap();
let mut broker = CredentialBroker::new(temp.path().join("new/stronghold.v1")); let mut broker = CredentialBroker::new(temp.path().join("new/stronghold.v1"));
broker.unlock(password()).unwrap(); broker.unlock(password()).unwrap();
assert_eq!(broker.import_fernet(&old, None).unwrap(), 100); for _ in 0..4 {
assert_eq!(broker.import_fernet(&old, None).unwrap(), 100); assert_eq!(broker.import_fernet(&old, None).unwrap(), 100);
assert_eq!(broker.list().unwrap().len(), 100); assert_eq!(broker.list().unwrap().len(), 100);
assert_eq!(fs::read(old.join("credentials.json")).unwrap(), source); }
assert!(old.join("master.key").is_file()); assert_eq!(fs::read(&source_path).unwrap(), source);
assert_eq!(fs::read_to_string(&key_path).unwrap(), legacy_key);
let marker: serde_json::Value =
serde_json::from_slice(&fs::read(old.join(".opennexus-owner.json")).unwrap()).unwrap();
assert_eq!(marker["state"], "switched");
assert_eq!(marker["count"], 100);
assert_eq!(marker["environment_key"], false);
assert_eq!(
marker["source_sha256"],
format!("{:x}", Sha256::digest(&source))
);
broker.lock(); broker.lock();
broker.unlock(password()).unwrap(); broker.unlock(password()).unwrap();
for (id, value) in fixture["values"].as_object().unwrap() { for (id, value) in fixture["values"].as_object().unwrap() {
@@ -835,18 +848,129 @@ mod tests {
value.as_str().unwrap().as_bytes() value.as_str().unwrap().as_bytes()
); );
} }
broker
let environment_source = temp.path().join("environment-source");
fs::create_dir(&environment_source).unwrap();
fs::write(environment_source.join("credentials.json"), &source).unwrap();
let mut environment_broker =
CredentialBroker::new(temp.path().join("environment-target/stronghold.v1"));
environment_broker.unlock(password()).unwrap();
assert_eq!(
environment_broker
.import_fernet(
&environment_source,
Some(Zeroizing::new(legacy_key.to_string())),
)
.unwrap(),
100
);
assert_eq!(environment_broker.list().unwrap().len(), 100);
assert!(!environment_source.join("master.key").exists());
assert_eq!(
fs::read(environment_source.join("credentials.json")).unwrap(),
source
);
let environment_marker: serde_json::Value = serde_json::from_slice(
&fs::read(environment_source.join(".opennexus-owner.json")).unwrap(),
)
.unwrap();
assert_eq!(environment_marker["environment_key"], true);
let empty_source = temp.path().join("empty-source");
fs::create_dir(&empty_source).unwrap();
fs::write(empty_source.join("credentials.json"), b"{}").unwrap();
fs::write(empty_source.join("master.key"), legacy_key).unwrap();
let mut empty_broker =
CredentialBroker::new(temp.path().join("empty-target/stronghold.v1"));
empty_broker.unlock(password()).unwrap();
assert_eq!(empty_broker.import_fernet(&empty_source, None).unwrap(), 0);
assert!(empty_broker.list().unwrap().is_empty());
assert_eq!(
fs::read(empty_source.join("credentials.json")).unwrap(),
b"{}"
);
let empty_marker: serde_json::Value =
serde_json::from_slice(&fs::read(empty_source.join(".opennexus-owner.json")).unwrap())
.unwrap();
assert_eq!(empty_marker["count"], 0);
assert_eq!(empty_marker["state"], "switched");
let missing_key_source = temp.path().join("missing-key-source");
fs::create_dir(&missing_key_source).unwrap();
fs::write(missing_key_source.join("credentials.json"), &source).unwrap();
let mut missing_key_broker =
CredentialBroker::new(temp.path().join("missing-key-target/stronghold.v1"));
missing_key_broker.unlock(password()).unwrap();
let missing_target_before = fs::read(&missing_key_broker.path).ok();
assert_eq!(
missing_key_broker
.import_fernet(&missing_key_source, None)
.unwrap_err(),
"MIGRATION_KEY_MISSING"
);
assert_eq!(
fs::read(&missing_key_broker.path).ok(),
missing_target_before
);
assert_eq!(
fs::read(missing_key_source.join("credentials.json")).unwrap(),
source
);
assert!(!missing_key_source.join(".opennexus-owner.json").exists());
let bad_source = temp.path().join("bad-token-source");
fs::create_dir(&bad_source).unwrap();
let mut bad_tokens = fixture["tokens"].clone();
bad_tokens["provider-050"] = serde_json::json!("invalid-fernet-token");
let bad_bytes = serde_json::to_vec(&bad_tokens).unwrap();
fs::write(bad_source.join("credentials.json"), &bad_bytes).unwrap();
fs::write(bad_source.join("master.key"), legacy_key).unwrap();
let mut bad_broker =
CredentialBroker::new(temp.path().join("bad-token-target/stronghold.v1"));
bad_broker.unlock(password()).unwrap();
let bad_target_before = fs::read(&bad_broker.path).ok();
assert_eq!(
bad_broker.import_fernet(&bad_source, None).unwrap_err(),
"MIGRATION_DECRYPT_FAILED"
);
assert_eq!(fs::read(&bad_broker.path).ok(), bad_target_before);
assert_eq!(
fs::read(bad_source.join("credentials.json")).unwrap(),
bad_bytes
);
assert!(!bad_source.join(".opennexus-owner.json").exists());
let conflict_source = temp.path().join("conflict-source");
fs::create_dir(&conflict_source).unwrap();
fs::write(conflict_source.join("credentials.json"), &source).unwrap();
fs::write(conflict_source.join("master.key"), legacy_key).unwrap();
let mut conflict_broker =
CredentialBroker::new(temp.path().join("conflict-target/stronghold.v1"));
conflict_broker.unlock(password()).unwrap();
conflict_broker
.put( .put(
&CredentialId::legacy("provider-000"), &CredentialId::legacy("provider-000"),
Zeroizing::new(b"changed-new-value".to_vec()), Zeroizing::new(b"changed-new-value".to_vec()),
) )
.unwrap(); .unwrap();
let conflict_target_before = fs::read(&conflict_broker.path).unwrap();
assert_eq!( assert_eq!(
broker.import_fernet(&old, None).unwrap_err(), conflict_broker
.import_fernet(&conflict_source, None)
.unwrap_err(),
"MIGRATION_CONFLICT" "MIGRATION_CONFLICT"
); );
assert_eq!( assert_eq!(
broker fs::read(&conflict_broker.path).unwrap(),
conflict_target_before
);
assert_eq!(
fs::read(conflict_source.join("credentials.json")).unwrap(),
source
);
assert!(!conflict_source.join(".opennexus-owner.json").exists());
assert_eq!(
conflict_broker
.resolve(&Scope::Provider, &CredentialId::legacy("provider-000")) .resolve(&Scope::Provider, &CredentialId::legacy("provider-000"))
.unwrap() .unwrap()
.unwrap() .unwrap()
@@ -0,0 +1,89 @@
"""B-02 Fernet-to-Stronghold migration acceptance driver."""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import shutil
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
TEST = "credentials::tests::b02_fernet_migration_matrix_is_atomic_verified_and_idempotent"
def sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
case_id = os.environ.get("OPENNEXUS_ACCEPTANCE_CASE_ID", "")
output = Path(args.output)
output.parent.mkdir(parents=True, exist_ok=True)
cargo = shutil.which("cargo")
if case_id != "B-02" or cargo is None:
result = {
"schema": 1,
"case_id": case_id,
"status": "FAILED",
"reason": "B-02 requires the registered case ID and Cargo.",
"assertions": [{"name": "driver prerequisites", "status": "FAILED", "evidence": "case ID or Cargo missing"}],
"metrics": {"peak_rss_bytes": None, "max_process_count": None, "denied_access_count": None},
"files": [],
"revisions": [],
}
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return 1
command = [
cargo,
"test",
"--manifest-path",
str(ROOT / "frontend" / "src-tauri" / "Cargo.toml"),
"--locked",
"--lib",
TEST,
"--",
"--exact",
"--nocapture",
]
completed = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, check=False)
print(completed.stdout, end="")
print(completed.stderr, end="")
passed = completed.returncode == 0 and "1 passed; 0 failed" in completed.stdout
status = "PASSED" if passed else "FAILED"
evidence = f"cargo exact test {TEST}"
assertions = [
{"name": "100 records preserve IDs and decrypted values", "status": status, "evidence": evidence},
{"name": "local and environment master keys are handled without source mutation", "status": status, "evidence": evidence},
{"name": "three repeat imports add no records", "status": status, "evidence": evidence},
{"name": "empty source switches with zero records", "status": status, "evidence": evidence},
{"name": "missing key and bad token do not switch or mutate source/target", "status": status, "evidence": evidence},
{"name": "same target ID with a different value rejects the full migration", "status": status, "evidence": evidence},
]
fixture = ROOT / "frontend" / "src-tauri" / "tests" / "fixtures" / "fernet-python.json"
result = {
"schema": 1,
"case_id": case_id,
"status": status,
"reason": "" if passed else "The exact Rust B-02 acceptance oracle failed.",
"assertions": assertions,
"metrics": {"peak_rss_bytes": None, "max_process_count": None, "denied_access_count": None},
"files": [{"path": "frontend/src-tauri/tests/fixtures/fernet-python.json", "sha256": sha256(fixture)}],
"revisions": [],
}
output.write_text(json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return 0 if passed else 1
if __name__ == "__main__":
raise SystemExit(main())
+32 -2
View File
@@ -31,7 +31,13 @@ CASE_SUITES = {
ALL_CASES = tuple(case for cases in CASE_SUITES.values() for case in cases) ALL_CASES = tuple(case for cases in CASE_SUITES.values() for case in cases)
# A case becomes executable only when a repository-owned driver is registered here. # A case becomes executable only when a repository-owned driver is registered here.
# Component/unit test commands are deliberately not treated as production acceptance. # Component/unit test commands are deliberately not treated as production acceptance.
CASE_DRIVERS: dict[str, dict[str, Any]] = {} CASE_DRIVERS: dict[str, dict[str, Any]] = {
"B-02": {
"driver": "scripts/acceptance_cases/b02_credentials.py",
"timeout_seconds": 900,
"required_metrics": (),
},
}
ENV_NAME = re.compile(r"[A-Z][A-Z0-9_]{2,127}") ENV_NAME = re.compile(r"[A-Z][A-Z0-9_]{2,127}")
RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{2,63}") RUN_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{2,63}")
SENSITIVE_KEY = re.compile(r"(?:password|passwd|secret|token|api[_-]?key|credential)", re.I) SENSITIVE_KEY = re.compile(r"(?:password|passwd|secret|token|api[_-]?key|credential)", re.I)
@@ -122,7 +128,7 @@ def load_config(path: Path, environ: dict[str, str] | None = None) -> dict[str,
if config.get("isolated") is not True or config.get("allow_destructive") is not True: if config.get("isolated") is not True or config.get("allow_destructive") is not True:
raise AcceptanceError("CONFIG_ISOLATION_CONFIRMATION_REQUIRED") raise AcceptanceError("CONFIG_ISOLATION_CONFIRMATION_REQUIRED")
run_id = config.get("run_id") run_id = config.get("run_id")
if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id): if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id) or run_id.startswith("replace-"):
raise AcceptanceError("CONFIG_RUN_ID_INVALID") raise AcceptanceError("CONFIG_RUN_ID_INVALID")
profile = config.get("platform_profile") profile = config.get("platform_profile")
if not isinstance(profile, str) or not profile.strip(): if not isinstance(profile, str) or not profile.strip():
@@ -420,6 +426,26 @@ def _repository_evidence(config: dict[str, Any]) -> dict[str, Any]:
return {"commit": commit or None, "lock_sha256": locks, "artifact_sha256": artifacts} return {"commit": commit or None, "lock_sha256": locks, "artifact_sha256": artifacts}
def repository_changes() -> tuple[str, ...]:
paths: set[str] = set()
commands = (
["git", "diff", "--name-only", "-z", "--", ".", ":(exclude)backend/data/vault"],
["git", "diff", "--cached", "--name-only", "-z", "--", ".", ":(exclude)backend/data/vault"],
["git", "ls-files", "--others", "--exclude-standard", "-z"],
)
for command in commands:
completed = subprocess.run(command, cwd=ROOT, capture_output=True, check=False)
if completed.returncode != 0:
raise AcceptanceError("SOURCE_STATE_UNAVAILABLE")
for raw in completed.stdout.split(b"\0"):
if not raw:
continue
path = raw.decode("utf-8", errors="replace").replace("\\", "/")
if path != "backend/data/vault" and not path.startswith("backend/data/vault/"):
paths.add(path)
return tuple(sorted(paths))
def execute(args: argparse.Namespace, environ: dict[str, str] | None = None) -> int: def execute(args: argparse.Namespace, environ: dict[str, str] | None = None) -> int:
environ = os.environ if environ is None else environ environ = os.environ if environ is None else environ
if args.list_cases: if args.list_cases:
@@ -431,6 +457,10 @@ def execute(args: argparse.Namespace, environ: dict[str, str] | None = None) ->
selected = select_cases(args.suite, args.case) selected = select_cases(args.suite, args.case)
config_path = Path(args.config).resolve() config_path = Path(args.config).resolve()
config = load_config(config_path, environ) config = load_config(config_path, environ)
changes = repository_changes()
if changes:
preview = ",".join(changes[:10])
raise AcceptanceError(f"SOURCE_TREE_DIRTY: {preview}")
if args.suite == "all" and not config.get("platform_profile"): if args.suite == "all" and not config.get("platform_profile"):
raise AcceptanceError("CONFIG_PLATFORM_PROFILE_REQUIRED") raise AcceptanceError("CONFIG_PLATFORM_PROFILE_REQUIRED")
prepare_isolated_root(config) prepare_isolated_root(config)