返回 CodeWhale
artifacts.rs
根目录 / crates / engine / src / fleet / artifacts.rs
1 //! Fleet artifact I/O. Both verifier publication and HTTP evidence reads use
2 //! the same workspace-relative, opened-directory authority. This replaces the
3 //! ordinary path-based writes in task_spec and reads in runtime_api.
4
5 #[cfg(test)]
6 use std::fs::File;
7 use std::io::{self, Read};
8 use std::path::Path;
9
10 use codewhale_util::files::WorkspaceFile;
11 pub use codewhale_util::files::path_is_confined;
12
13 use anyhow::{Context, Result, ensure};
14 use codewhale_protocol::fleet::FleetArtifactRef;
15 use sha2::{Digest, Sha256};
16
17 // The HTTP preview stays small; verifying a larger artifact streams its digest
18 // without retaining all bytes. The writer shares the ceiling so it cannot
19 // publish an artifact the evidence reader is unable to verify.
20 const MAX_ARTIFACT_BYTES: u64 = 16 * 1024 * 1024;
21
22 pub fn write(workspace: &Path, relative: &Path, bytes: &[u8]) -> Result<()> {
23 ensure!(
24 bytes.len() as u64 <= MAX_ARTIFACT_BYTES,
25 "Fleet artifact exceeds the 16 MiB limit"
26 );
27 let parent = WorkspaceFile::open(workspace, relative, true)?;
28 match parent.publish(bytes) {
29 Ok(()) => Ok(()),
30 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
31 let existing = parent.open_file()?;
32 let mut saved = Vec::new();
33 existing
34 .take(bytes.len() as u64 + 1)
35 .read_to_end(&mut saved)?;
36 ensure!(
37 saved == bytes,
38 "An existing Fleet artifact contains different bytes"
39 );
40 Ok(())
41 }
42 Err(error) => Err(error).context("Publishing Fleet artifact"),
43 }
44 }
45
46 pub fn read_verified(
47 workspace: &Path,
48 artifact: &FleetArtifactRef,
49 preview_limit: u64,
50 ) -> Result<(Vec<u8>, u64)> {
51 let parent = WorkspaceFile::open(workspace, &artifact.path, false)?;
52 let file = parent.open_file()?;
53 let size = file.metadata()?.len();
54 ensure!(
55 size <= MAX_ARTIFACT_BYTES,
56 "Fleet artifact exceeds the 16 MiB verification limit"
57 );
58 ensure!(
59 artifact.size_bytes.is_none_or(|expected| expected == size),
60 "Fleet artifact size changed"
61 );
62 let checksum = artifact
63 .checksum
64 .as_deref()
65 .context("Fleet artifact has no recorded checksum")?;
66 let mut hasher = Sha256::new();
67 let mut preview = Vec::new();
68 let mut buffer = [0_u8; 8192];
69 let mut total = 0_u64;
70 // The digest and returned preview consume exactly the same bytes from the
71 // same opened file. A changed/replaced pathname is never reopened for data.
72 let mut reader = (&file).take(size + 1);
73 loop {
74 let count = reader.read(&mut buffer)?;
75 if count == 0 {
76 break;
77 }
78 total += count as u64;
79 ensure!(total <= size, "Fleet artifact grew while being read");
80 hasher.update(&buffer[..count]);
81 let remaining = preview_limit.saturating_sub(preview.len() as u64) as usize;
82 preview.extend_from_slice(&buffer[..count.min(remaining)]);
83 }
84 ensure!(
85 total == size && file.metadata()?.len() == size,
86 "Fleet artifact size changed while being read"
87 );
88 ensure!(
89 format!(
90 "sha256:{}",
91 codewhale_runtime::hashing::hex_bytes(hasher.finalize())
92 ) == checksum,
93 "Fleet artifact checksum does not match the recorded receipt"
94 );
95 Ok((preview, size))
96 }
97
98 #[cfg(test)]
99 mod tests {
100 use super::*;
101 use codewhale_protocol::fleet::FleetArtifactKind;
102
103 fn reference(path: &str, bytes: &[u8]) -> FleetArtifactRef {
104 FleetArtifactRef {
105 kind: FleetArtifactKind::Receipt,
106 path: path.into(),
107 checksum: Some(format!(
108 "sha256:{}",
109 codewhale_runtime::hashing::sha256_hex(bytes)
110 )),
111 mime_type: None,
112 size_bytes: Some(bytes.len() as u64),
113 }
114 }
115
116 #[test]
117 fn publication_is_immutable_and_verifies_beyond_the_preview() {
118 let workspace = tempfile::tempdir().unwrap();
119 let bytes = vec![b'a'; 128 * 1024];
120 let artifact = reference(".codewhale/fleet/receipt.json", &bytes);
121 write(workspace.path(), &artifact.path, &bytes).unwrap();
122 write(workspace.path(), &artifact.path, &bytes).unwrap();
123 assert!(write(workspace.path(), &artifact.path, b"replacement").is_err());
124 let (preview, size) = read_verified(workspace.path(), &artifact, 65_536).unwrap();
125 assert_eq!(preview, bytes[..65_536]);
126 assert_eq!(size, bytes.len() as u64);
127
128 // Changing bytes outside the returned preview must still fail the
129 // complete digest check, even when size/metadata remain unchanged.
130 let mut changed = bytes;
131 *changed.last_mut().unwrap() = b'b';
132 std::fs::write(workspace.path().join(&artifact.path), changed).unwrap();
133 let error = read_verified(workspace.path(), &artifact, 65_536).unwrap_err();
134 assert!(error.to_string().contains("checksum"));
135 }
136
137 #[test]
138 fn missing_digest_size_mismatch_and_oversized_files_fail_closed() {
139 let workspace = tempfile::tempdir().unwrap();
140 let mut artifact = reference("receipt.json", b"receipt");
141 write(workspace.path(), &artifact.path, b"receipt").unwrap();
142 artifact.checksum = None;
143 assert!(read_verified(workspace.path(), &artifact, 64).is_err());
144 artifact = reference("receipt.json", b"receipt");
145 artifact.size_bytes = Some(999);
146 assert!(read_verified(workspace.path(), &artifact, 64).is_err());
147 File::options()
148 .write(true)
149 .open(workspace.path().join(&artifact.path))
150 .unwrap()
151 .set_len(MAX_ARTIFACT_BYTES + 1)
152 .unwrap();
153 assert!(
154 read_verified(workspace.path(), &artifact, 64)
155 .unwrap_err()
156 .to_string()
157 .contains("limit")
158 );
159 assert!(
160 write(
161 workspace.path(),
162 Path::new("huge.json"),
163 &vec![0; MAX_ARTIFACT_BYTES as usize + 1]
164 )
165 .is_err()
166 );
167 assert!(!workspace.path().join("huge.json").exists());
168 }
169
170 #[cfg(unix)]
171 #[test]
172 fn parent_and_final_symlinks_and_hard_links_never_escape() {
173 use std::os::unix::fs::symlink;
174 let workspace = tempfile::tempdir().unwrap();
175 let outside = tempfile::tempdir().unwrap();
176 let secret = b"OUTSIDE_SYNTHETIC_RECEIPT_CANARY";
177 let outside_file = outside.path().join("private.txt");
178 std::fs::write(&outside_file, secret).unwrap();
179 std::fs::create_dir_all(workspace.path().join(".codewhale/fleet")).unwrap();
180
181 let final_link = reference(".codewhale/fleet/final.json", secret);
182 symlink(&outside_file, workspace.path().join(&final_link.path)).unwrap();
183 assert!(read_verified(workspace.path(), &final_link, 64).is_err());
184 assert!(write(workspace.path(), &final_link.path, b"overwrite").is_err());
185
186 symlink(
187 outside.path(),
188 workspace.path().join(".codewhale/fleet/parent"),
189 )
190 .unwrap();
191 let parent_link = reference(".codewhale/fleet/parent/private.txt", secret);
192 assert!(read_verified(workspace.path(), &parent_link, 64).is_err());
193 assert!(write(workspace.path(), &parent_link.path, b"overwrite").is_err());
194 assert!(
195 write(
196 workspace.path(),
197 Path::new(".codewhale/fleet/parent/new.json"),
198 b"new"
199 )
200 .is_err()
201 );
202 assert!(!outside.path().join("new.json").exists());
203
204 let hard_link = reference(".codewhale/fleet/hard.json", secret);
205 std::fs::hard_link(&outside_file, workspace.path().join(&hard_link.path)).unwrap();
206 assert!(read_verified(workspace.path(), &hard_link, 64).is_err());
207 assert!(write(workspace.path(), &hard_link.path, b"overwrite").is_err());
208 assert_eq!(std::fs::read(outside_file).unwrap(), secret);
209 }
210
211 #[cfg(unix)]
212 #[test]
213 fn publication_uses_the_open_parent_after_a_path_swap() {
214 use std::os::unix::fs::symlink;
215 let workspace = tempfile::tempdir().unwrap();
216 let outside = tempfile::tempdir().unwrap();
217 let parent =
218 WorkspaceFile::open(workspace.path(), Path::new("receipts/item.json"), true).unwrap();
219 std::fs::rename(
220 workspace.path().join("receipts"),
221 workspace.path().join("pinned"),
222 )
223 .unwrap();
224 symlink(outside.path(), workspace.path().join("receipts")).unwrap();
225 parent.publish(b"complete receipt").unwrap();
226 assert_eq!(
227 std::fs::read(workspace.path().join("pinned/item.json")).unwrap(),
228 b"complete receipt"
229 );
230 assert!(!outside.path().join("item.json").exists());
231 assert!(write(workspace.path(), Path::new("receipts/next.json"), b"next").is_err());
232 }
233 }
234
234 lines RUST