interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / tests / test_ledger_cli_keys.rs

258 lines · 8264 bytes Raw Blame History
1//! Signing keys stay off the command line (issue #49), and `ledger verify` names what it did not
2//! check (issue #50). Pre-registered rows:
3//!
4//! 1. A `ledger checkpoint` key from `--signing-key-file` or `RSI_LEDGER_SIGNING_KEY` gives the
5//! same signature as the same key passed with `--signing-key-hex`.
6//! 2. Precedence follows the judge: hex flag, then key file, then environment.
7//! 3. A missing or empty key file is refused and never falls back to another source.
8//! 4. `soak` reads its signing key from `--signing-key-file` and `RSI_SOAK_SIGNING_KEY`.
9//! 5. `ledger verify` prints PASS only when the latest checkpoint covers the whole ledger and its
10//! signature was checked. Otherwise it prints PARTIAL and names the gap.
11
12use p256::ecdsa::SigningKey;
13use spark_rsi::ledger::{BlockType, ImprovementLedger, MerkleCheckpoint};
14use std::fs;
15use std::path::{Path, PathBuf};
16use std::process::{Command, Output};
17
18const LEDGER_ENV: &str = "RSI_LEDGER_SIGNING_KEY";
19const SOAK_ENV: &str = "RSI_SOAK_SIGNING_KEY";
20
21fn bin() -> &'static Path {
22 Path::new(env!("CARGO_BIN_EXE_spark-rsi"))
23}
24
25fn key(seed: u8) -> SigningKey {
26 SigningKey::from_slice(&[seed; 32]).unwrap()
27}
28
29fn key_hex(seed: u8) -> String {
30 hex::encode([seed; 32])
31}
32
33fn pub_hex(seed: u8) -> String {
34 hex::encode(key(seed).verifying_key().to_sec1_point(false).as_bytes())
35}
36
37/// A ledger with three blocks after genesis.
38fn ledger() -> (tempfile::TempDir, PathBuf) {
39 let tmp = tempfile::tempdir().unwrap();
40 let root = tmp.path().join(".rsi");
41 let ledger = ImprovementLedger::open(&root).unwrap();
42 for i in 1..=3 {
43 ledger
44 .append_block(
45 BlockType::Evaluation,
46 format!("{{\"eval\": {}}}", i),
47 Vec::new(),
48 )
49 .unwrap();
50 }
51 (tmp, root)
52}
53
54/// `spark-rsi <args>` with no key in the environment unless the test sets one.
55fn cli(args: &[&str]) -> Command {
56 let mut cmd = Command::new(bin());
57 cmd.args(args)
58 .env_remove(LEDGER_ENV)
59 .env_remove(SOAK_ENV)
60 .env("RUST_LOG", "error");
61 cmd
62}
63
64fn run(mut cmd: Command) -> Output {
65 cmd.output().unwrap()
66}
67
68/// The checkpoint `ledger checkpoint` printed.
69fn checkpoint(out: Output) -> MerkleCheckpoint {
70 let stdout = String::from_utf8(out.stdout).unwrap();
71 assert!(
72 out.status.success(),
73 "checkpoint failed: {}",
74 String::from_utf8_lossy(&out.stderr)
75 );
76 let json = &stdout[stdout.find("Merkle Checkpoint Created").unwrap()..];
77 let json = &json[json.find('{').unwrap()..];
78 serde_json::Deserializer::from_str(json)
79 .into_iter::<MerkleCheckpoint>()
80 .next()
81 .unwrap()
82 .unwrap()
83}
84
85fn write_key_file(dir: &Path, name: &str, contents: &str) -> String {
86 let path = dir.join(name);
87 fs::write(&path, contents).unwrap();
88 path.to_str().unwrap().to_string()
89}
90
91#[test]
92fn checkpoint_key_from_file_or_env_signs_like_the_hex_flag() {
93 let (tmp, root) = ledger();
94 let root = root.to_str().unwrap();
95 let file = write_key_file(tmp.path(), "checkpoint.key", &format!("{}\n", key_hex(7)));
96
97 let by_flag = checkpoint(run(cli(&[
98 "ledger",
99 "checkpoint",
100 root,
101 "--signing-key-hex",
102 &key_hex(7),
103 ])));
104 let by_file = checkpoint(run(cli(&[
105 "ledger",
106 "checkpoint",
107 root,
108 "--signing-key-file",
109 &file,
110 ])));
111 let mut env_cmd = cli(&["ledger", "checkpoint", root]);
112 env_cmd.env(LEDGER_ENV, key_hex(7));
113 let by_env = checkpoint(run(env_cmd));
114
115 let flag_sig = by_flag.signature.clone().expect("hex flag signs");
116 assert_eq!(by_file.signature.as_deref(), Some(flag_sig.as_str()));
117 assert_eq!(by_env.signature.as_deref(), Some(flag_sig.as_str()));
118 assert!(by_env.verify_signature(key(7).verifying_key()));
119
120 let unsigned = checkpoint(run(cli(&["ledger", "checkpoint", root])));
121 assert_eq!(unsigned.signature, None);
122}
123
124#[test]
125fn checkpoint_key_precedence_is_flag_then_file_then_env() {
126 let (tmp, root) = ledger();
127 let root = root.to_str().unwrap();
128 let file = write_key_file(tmp.path(), "checkpoint.key", &key_hex(2));
129
130 let mut all_three = cli(&[
131 "ledger",
132 "checkpoint",
133 root,
134 "--signing-key-hex",
135 &key_hex(1),
136 "--signing-key-file",
137 &file,
138 ]);
139 all_three.env(LEDGER_ENV, key_hex(3));
140 assert!(checkpoint(run(all_three)).verify_signature(key(1).verifying_key()));
141
142 let mut file_and_env = cli(&["ledger", "checkpoint", root, "--signing-key-file", &file]);
143 file_and_env.env(LEDGER_ENV, key_hex(3));
144 assert!(checkpoint(run(file_and_env)).verify_signature(key(2).verifying_key()));
145}
146
147#[test]
148fn missing_or_empty_key_file_is_refused() {
149 let (tmp, root) = ledger();
150 let root_str = root.to_str().unwrap();
151 let empty = write_key_file(tmp.path(), "empty.key", "\n");
152 let missing = tmp.path().join("missing.key");
153
154 let mut empty_cmd = cli(&[
155 "ledger",
156 "checkpoint",
157 root_str,
158 "--signing-key-file",
159 &empty,
160 ]);
161 empty_cmd.env(LEDGER_ENV, key_hex(3));
162 let out = run(empty_cmd);
163 assert!(!out.status.success());
164 assert!(String::from_utf8_lossy(&out.stderr).contains("is empty"));
165
166 let out = run(cli(&[
167 "ledger",
168 "checkpoint",
169 root_str,
170 "--signing-key-file",
171 missing.to_str().unwrap(),
172 ]));
173 assert!(!out.status.success());
174 assert!(String::from_utf8_lossy(&out.stderr).contains("cannot read key file"));
175
176 let ledger = ImprovementLedger::open(&root).unwrap();
177 assert!(ledger.latest_checkpoint().unwrap().is_none());
178}
179
180#[test]
181fn soak_reads_its_signing_key_from_file_and_env() {
182 // A key that is not hex stops the soak at key parsing, before any cycle runs, so the error
183 // shows which source the soak read.
184 let tmp = tempfile::tempdir().unwrap();
185 let path = tmp.path().to_str().unwrap();
186 let file = write_key_file(tmp.path(), "soak.key", "not-hex");
187 let soak = |extra: &[&str], env: Option<&str>| {
188 let mut args = vec!["soak", "--path", path, "--cycles", "1"];
189 args.extend_from_slice(extra);
190 let mut cmd = cli(&args);
191 if let Some(v) = env {
192 cmd.env(SOAK_ENV, v);
193 }
194 let out = run(cmd);
195 assert!(!out.status.success());
196 String::from_utf8_lossy(&out.stderr).to_string()
197 };
198
199 assert!(soak(&[], None).contains("Missing cryptographic signing key"));
200 assert!(soak(&[], Some("not-hex")).contains("Invalid signing_key_hex"));
201 assert!(soak(&["--signing-key-file", &file], None).contains("Invalid signing_key_hex"));
202}
203
204#[test]
205fn verify_headline_names_what_was_not_checked() {
206 let (_tmp, root) = ledger();
207 let root_str = root.to_str().unwrap();
208 let pk = pub_hex(7);
209 let verify = |with_key: bool| {
210 let mut args = vec!["ledger", "verify", root_str];
211 if with_key {
212 args.extend_from_slice(&["--verifying-key-hex", &pk]);
213 }
214 let out = run(cli(&args));
215 assert!(out.status.success());
216 let stdout = String::from_utf8(out.stdout).unwrap();
217 stdout
218 .lines()
219 .find(|l| l.contains("Ledger Verification"))
220 .unwrap()
221 .to_string()
222 };
223
224 let headline = verify(false);
225 assert!(headline.contains("PARTIAL"), "{headline}");
226 assert!(
227 headline.contains("no Merkle checkpoint is stored"),
228 "{headline}"
229 );
230
231 checkpoint(run(cli(&[
232 "ledger",
233 "checkpoint",
234 root_str,
235 "--signing-key-hex",
236 &key_hex(7),
237 ])));
238 let headline = verify(true);
239 assert!(
240 headline.ends_with("Ledger Verification: PASS"),
241 "{headline}"
242 );
243
244 ImprovementLedger::open(&root)
245 .unwrap()
246 .append_block(
247 BlockType::Evaluation,
248 "{\"eval\": 4}".to_string(),
249 Vec::new(),
250 )
251 .unwrap();
252 let headline = verify(true);
253 assert!(headline.contains("PARTIAL"), "{headline}");
254 assert!(
255 headline.contains("1 block(s) after checkpoint #3 are not covered by any checkpoint"),
256 "{headline}"
257 );
258}