返回 CodeWhale
mutation_onestep_tests.rs
根目录 / crates / skills / src / mutation_onestep_tests.rs
1 use super::*;
2 use codewhale_net::network_policy::NetworkPolicy;
3 use std::sync::{Arc, Mutex};
4 use tempfile::TempDir;
5
6 struct Fixture {
7 _tmp: TempDir,
8 workspace: PathBuf,
9 home: PathBuf,
10 network: NetworkPolicy,
11 }
12
13 impl Fixture {
14 fn new() -> Self {
15 let tmp = TempDir::new().unwrap();
16 let workspace = tmp.path().join("ws");
17 let home = tmp.path().join("home");
18 fs::create_dir_all(&workspace).unwrap();
19 fs::create_dir_all(&home).unwrap();
20 Self {
21 _tmp: tmp,
22 workspace,
23 home,
24 network: NetworkPolicy {
25 allow: vec!["127.0.0.1".into()],
26 ..NetworkPolicy::default()
27 },
28 }
29 }
30
31 fn ctx(&self) -> MutationContext<'_> {
32 MutationContext {
33 workspace: &self.workspace,
34 home: Some(&self.home),
35 configured_skills_dir: None,
36 network: &self.network,
37 max_size: install::DEFAULT_MAX_SIZE_BYTES,
38 registry_url: install::DEFAULT_REGISTRY_URL,
39 }
40 }
41
42 fn source(&self, name: &str, body: &str) -> PathBuf {
43 let dir = self.workspace.join("src").join(name);
44 fs::create_dir_all(&dir).unwrap();
45 fs::write(
46 dir.join("SKILL.md"),
47 format!("---\nname: {name}\ndescription: d\n---\n{body}\n"),
48 )
49 .unwrap();
50 dir
51 }
52
53 fn skills_dir(&self, target: SkillTargetScope) -> PathBuf {
54 match target {
55 SkillTargetScope::Project => self.workspace.join(".codewhale").join("skills"),
56 SkillTargetScope::Global => self.home.join(".codewhale").join("skills"),
57 }
58 }
59 }
60
61 async fn run(
62 fx: &Fixture,
63 initiator: Option<SkillInitiator>,
64 request: SkillOneStepRequest,
65 ) -> Result<SkillOneStepReceipt> {
66 execute_one_step(request, initiator, &fx.ctx()).await
67 }
68
69 fn install_spec(spec: &str, target: SkillTargetScope) -> SkillOneStepRequest {
70 SkillOneStepRequest::Install {
71 spec: spec.to_string(),
72 target,
73 }
74 }
75
76 fn path_spec(dir: &Path) -> String {
77 format!("path:{}", dir.display())
78 }
79
80 #[test]
81 fn local_path_spec_table() {
82 for local in [
83 "path:foo",
84 "./foo",
85 "../foo",
86 "/abs/foo",
87 "~/foo",
88 "~",
89 ".",
90 "..",
91 "C:\\skills\\foo",
92 "c:/skills/foo",
93 "D:foo",
94 "\\\\server\\share\\foo",
95 "\\foo",
96 ".\\foo",
97 "..\\foo",
98 "dir\\foo",
99 ] {
100 assert!(local_path_spec(local).is_some(), "{local}");
101 }
102 for remote in [
103 "review-pr",
104 "github:o/r",
105 "https://example.com/a.tar.gz",
106 "http://127.0.0.1:1/a.tar.gz",
107 "my.skill",
108 ] {
109 assert!(local_path_spec(remote).is_none(), "{remote}");
110 }
111 assert_eq!(local_path_spec("path: x y "), Some("x y"));
112 }
113
114 #[tokio::test]
115 async fn folder_install_update_and_no_change() {
116 let fx = Fixture::new();
117 let src = fx.source("folder-skill", "one");
118 let spec = path_spec(&src);
119
120 let first = run(&fx, None, install_spec(&spec, SkillTargetScope::Project))
121 .await
122 .unwrap();
123 assert_eq!(first.outcome, SkillMutationOutcome::Installed);
124 assert!(
125 first
126 .summary
127 .starts_with("Installed skill folder-skill (project) from path:")
128 );
129
130 let again = run(&fx, None, install_spec(&spec, SkillTargetScope::Project))
131 .await
132 .unwrap();
133 assert_eq!(again.outcome, SkillMutationOutcome::NoChange);
134
135 fs::write(
136 src.join("SKILL.md"),
137 "---\nname: folder-skill\ndescription: d\n---\ntwo\n",
138 )
139 .unwrap();
140 let updated = run(
141 &fx,
142 None,
143 install_spec("./src/folder-skill", SkillTargetScope::Project),
144 )
145 .await
146 .unwrap();
147 assert_eq!(updated.outcome, SkillMutationOutcome::Updated);
148 let dest = fx
149 .skills_dir(SkillTargetScope::Project)
150 .join("folder-skill");
151 assert!(
152 fs::read_to_string(dest.join("SKILL.md"))
153 .unwrap()
154 .contains("two")
155 );
156 let marker = read_installed_marker(&dest).unwrap().unwrap();
157 assert!(marker.spec.starts_with("path:"));
158 assert!(!dest.with_extension("bak").exists());
159 }
160
161 #[tokio::test]
162 async fn path_provenance_update_copies_again() {
163 let fx = Fixture::new();
164 let src = fx.source("redo", "one");
165 run(
166 &fx,
167 None,
168 install_spec(&path_spec(&src), SkillTargetScope::Project),
169 )
170 .await
171 .unwrap();
172 fs::write(
173 src.join("SKILL.md"),
174 "---\nname: redo\ndescription: d\n---\nchanged\n",
175 )
176 .unwrap();
177 let receipt = run(
178 &fx,
179 Some(SkillInitiator::Person),
180 SkillOneStepRequest::Mutation(SkillMutationRequest::UpdateByName {
181 name: "redo".into(),
182 scope: Some(SkillTargetScope::Project),
183 expected_digest: None,
184 }),
185 )
186 .await
187 .unwrap();
188 assert_eq!(receipt.outcome, SkillMutationOutcome::Updated);
189 assert_eq!(receipt.action, SkillActionKind::Update);
190 let dest = fx.skills_dir(SkillTargetScope::Project).join("redo");
191 assert!(
192 fs::read_to_string(dest.join("SKILL.md"))
193 .unwrap()
194 .contains("changed")
195 );
196 }
197
198 #[tokio::test]
199 async fn install_over_unmarked_directory_is_refused() {
200 let fx = Fixture::new();
201 let src = fx.source("held", "new");
202 let existing = fx.skills_dir(SkillTargetScope::Project).join("held");
203 fs::create_dir_all(&existing).unwrap();
204 fs::write(
205 existing.join("SKILL.md"),
206 "---\nname: held\ndescription: d\n---\nmine\n",
207 )
208 .unwrap();
209 let err = run(
210 &fx,
211 None,
212 install_spec(&path_spec(&src), SkillTargetScope::Project),
213 )
214 .await
215 .unwrap_err();
216 assert!(
217 err.to_string().contains("not installed by Codewhale"),
218 "{err}"
219 );
220 assert!(
221 fs::read_to_string(existing.join("SKILL.md"))
222 .unwrap()
223 .contains("mine")
224 );
225 }
226
227 #[tokio::test]
228 async fn missing_skill_md_and_file_sources_are_refused() {
229 let fx = Fixture::new();
230 let empty = fx.workspace.join("empty");
231 fs::create_dir_all(&empty).unwrap();
232 let err = run(
233 &fx,
234 None,
235 install_spec(&path_spec(&empty), SkillTargetScope::Project),
236 )
237 .await
238 .unwrap_err();
239 assert!(err.to_string().contains("no SKILL.md"), "{err}");
240
241 let archive = fx.workspace.join("pack.txt");
242 fs::write(&archive, b"x").unwrap();
243 let err = run(
244 &fx,
245 None,
246 install_spec(&path_spec(&archive), SkillTargetScope::Project),
247 )
248 .await
249 .unwrap_err();
250 assert!(err.to_string().contains(".tar.gz / .tgz archives"), "{err}");
251 let corrupt = fx.workspace.join("corrupt.tar.gz");
252 fs::write(&corrupt, b"not-gzip").unwrap();
253 assert!(
254 run(
255 &fx,
256 None,
257 install_spec(&path_spec(&corrupt), SkillTargetScope::Project),
258 )
259 .await
260 .is_err()
261 );
262 assert!(
263 !fx.skills_dir(SkillTargetScope::Project)
264 .join("empty")
265 .exists()
266 );
267 }
268
269 #[cfg(unix)]
270 #[tokio::test]
271 async fn symlinks_are_refused() {
272 let fx = Fixture::new();
273 let real = fx.source("linked", "body");
274 let link = fx.workspace.join("link-to-skill");
275 std::os::unix::fs::symlink(&real, &link).unwrap();
276 let err = run(
277 &fx,
278 None,
279 install_spec(&path_spec(&link), SkillTargetScope::Project),
280 )
281 .await
282 .unwrap_err();
283 assert!(err.to_string().contains("symlinked"), "{err}");
284
285 let outside = fx.workspace.join("secret.txt");
286 fs::write(&outside, "secret").unwrap();
287 std::os::unix::fs::symlink(&outside, real.join("leak.txt")).unwrap();
288 let err = run(
289 &fx,
290 None,
291 install_spec(&path_spec(&real), SkillTargetScope::Project),
292 )
293 .await
294 .unwrap_err();
295 assert!(format!("{err:#}").contains("not safe to copy"), "{err:#}");
296 assert!(
297 !fx.skills_dir(SkillTargetScope::Project)
298 .join("linked")
299 .exists()
300 );
301 }
302
303 #[tokio::test]
304 async fn shipped_markers_are_stripped() {
305 let fx = Fixture::new();
306 let src = fx.source("marked", "body");
307 fs::write(src.join(install::TRUSTED_MARKER), "{\"schema_version\":2}").unwrap();
308 fs::write(
309 src.join(install::INSTALLED_FROM_MARKER),
310 "{\"spec\":\"github:evil/skill\"}",
311 )
312 .unwrap();
313 run(
314 &fx,
315 None,
316 install_spec(&path_spec(&src), SkillTargetScope::Project),
317 )
318 .await
319 .unwrap();
320 let dest = fx.skills_dir(SkillTargetScope::Project).join("marked");
321 assert!(!dest.join(install::TRUSTED_MARKER).exists());
322 let marker = read_installed_marker(&dest).unwrap().unwrap();
323 assert!(marker.spec.starts_with("path:"), "{}", marker.spec);
324 }
325
326 #[cfg(unix)]
327 #[tokio::test]
328 async fn executable_bit_is_kept() {
329 use std::os::unix::fs::PermissionsExt;
330 let fx = Fixture::new();
331 let src = fx.source("exec", "body");
332 fs::create_dir_all(src.join("scripts")).unwrap();
333 let script = src.join("scripts").join("run.sh");
334 fs::write(&script, "#!/bin/sh\n").unwrap();
335 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap();
336 let receipt = run(
337 &fx,
338 None,
339 install_spec(&path_spec(&src), SkillTargetScope::Project),
340 )
341 .await
342 .unwrap();
343 assert!(
344 receipt.summary.ends_with("includes 1 script"),
345 "{}",
346 receipt.summary
347 );
348 let copied = fx
349 .skills_dir(SkillTargetScope::Project)
350 .join("exec")
351 .join("scripts")
352 .join("run.sh");
353 assert_eq!(
354 fs::metadata(copied).unwrap().permissions().mode() & 0o111,
355 0o111
356 );
357 }
358
359 #[tokio::test]
360 async fn only_a_person_global_install_records_approval() {
361 let fx = Fixture::new();
362 let src = fx.source("approval", "body");
363 let spec = path_spec(&src);
364
365 for (initiator, target, expect_marker) in [
366 (None, SkillTargetScope::Global, false),
367 (Some(SkillInitiator::Agent), SkillTargetScope::Global, false),
368 (
369 Some(SkillInitiator::CommandLine),
370 SkillTargetScope::Global,
371 false,
372 ),
373 (
374 Some(SkillInitiator::Person),
375 SkillTargetScope::Project,
376 false,
377 ),
378 (Some(SkillInitiator::Person), SkillTargetScope::Global, true),
379 ] {
380 let dest = fx.skills_dir(target).join("approval");
381 if dest.exists() {
382 fs::remove_dir_all(&dest).unwrap();
383 }
384 run(&fx, initiator, install_spec(&spec, target))
385 .await
386 .unwrap();
387 let marker = dest.join(install::TRUSTED_MARKER);
388 assert_eq!(marker.exists(), expect_marker, "{initiator:?} {target:?}");
389 if expect_marker {
390 let digest = package_digest::compute_package_digest(&dest).unwrap();
391 assert!(fs::read_to_string(marker).unwrap().contains(&digest));
392 }
393 }
394 }
395
396 #[tokio::test]
397 async fn person_update_rebinds_trust_to_the_new_digest() {
398 let fx = Fixture::new();
399 let src = fx.source("rebind", "one");
400 let spec = path_spec(&src);
401 run(
402 &fx,
403 Some(SkillInitiator::Person),
404 install_spec(&spec, SkillTargetScope::Global),
405 )
406 .await
407 .unwrap();
408 fs::write(
409 src.join("SKILL.md"),
410 "---\nname: rebind\ndescription: d\n---\ntwo\n",
411 )
412 .unwrap();
413 run(
414 &fx,
415 Some(SkillInitiator::Person),
416 install_spec(&spec, SkillTargetScope::Global),
417 )
418 .await
419 .unwrap();
420 let dest = fx.skills_dir(SkillTargetScope::Global).join("rebind");
421 let digest = package_digest::compute_package_digest(&dest).unwrap();
422 assert!(
423 fs::read_to_string(dest.join(install::TRUSTED_MARKER))
424 .unwrap()
425 .contains(&digest)
426 );
427 }
428
429 fn tarball(skill_name: &str, body: &str) -> Vec<u8> {
430 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
431 let mut builder = tar::Builder::new(encoder);
432 let mut dir = tar::Header::new_gnu();
433 dir.set_entry_type(tar::EntryType::Directory);
434 dir.set_mode(0o755);
435 dir.set_size(0);
436 builder
437 .append_data(&mut dir, "repo-main/", std::io::empty())
438 .unwrap();
439 let content = format!("---\nname: {skill_name}\ndescription: d\n---\n{body}\n");
440 let mut file = tar::Header::new_gnu();
441 file.set_mode(0o644);
442 file.set_size(content.len() as u64);
443 builder
444 .append_data(&mut file, "repo-main/SKILL.md", content.as_bytes())
445 .unwrap();
446 builder.into_inner().unwrap().finish().unwrap()
447 }
448
449 async fn serve(body: Arc<Mutex<Vec<u8>>>) -> std::net::SocketAddr {
450 use tokio::io::{AsyncReadExt, AsyncWriteExt};
451 let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
452 let addr = listener.local_addr().unwrap();
453 tokio::spawn(async move {
454 while let Ok((mut socket, _)) = listener.accept().await {
455 let body = body.clone();
456 tokio::spawn(async move {
457 let mut request = Vec::new();
458 let mut buf = [0u8; 1024];
459 while let Ok(n) = socket.read(&mut buf).await {
460 if n == 0 {
461 return;
462 }
463 request.extend_from_slice(&buf[..n]);
464 if request.windows(4).any(|w| w == b"\r\n\r\n") {
465 break;
466 }
467 }
468 let payload = body.lock().unwrap().clone();
469 let head = format!(
470 "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
471 payload.len()
472 );
473 let _ = socket.write_all(head.as_bytes()).await;
474 let _ = socket.write_all(&payload).await;
475 });
476 }
477 });
478 addr
479 }
480
481 #[tokio::test]
482 async fn remote_install_again_updates_or_reports_no_change() {
483 let fx = Fixture::new();
484 let body = Arc::new(Mutex::new(tarball("remote-skill", "one")));
485 let addr = serve(body.clone()).await;
486 let url = format!("http://{addr}/s.tar.gz");
487
488 let first = run(
489 &fx,
490 Some(SkillInitiator::Person),
491 install_spec(&url, SkillTargetScope::Global),
492 )
493 .await
494 .unwrap();
495 assert_eq!(first.outcome, SkillMutationOutcome::Installed);
496 let dest = fx.skills_dir(SkillTargetScope::Global).join("remote-skill");
497 assert!(dest.join(install::TRUSTED_MARKER).exists());
498
499 let same = run(
500 &fx,
501 Some(SkillInitiator::Person),
502 install_spec(&url, SkillTargetScope::Global),
503 )
504 .await
505 .unwrap();
506 assert_eq!(same.outcome, SkillMutationOutcome::NoChange);
507
508 *body.lock().unwrap() = tarball("remote-skill", "two");
509 let moved = run(
510 &fx,
511 Some(SkillInitiator::Person),
512 install_spec(&url, SkillTargetScope::Global),
513 )
514 .await
515 .unwrap();
516 assert_eq!(moved.outcome, SkillMutationOutcome::Updated);
517 assert!(
518 fs::read_to_string(dest.join("SKILL.md"))
519 .unwrap()
520 .contains("two")
521 );
522 let digest = package_digest::compute_package_digest(&dest).unwrap();
523 assert!(
524 fs::read_to_string(dest.join(install::TRUSTED_MARKER))
525 .unwrap()
526 .contains(&digest)
527 );
528 }
529
530 #[tokio::test]
531 async fn remote_install_over_other_source_says_it_replaces() {
532 let fx = Fixture::new();
533 let first = Arc::new(Mutex::new(tarball("shared-name", "one")));
534 let second = Arc::new(Mutex::new(tarball("shared-name", "two")));
535 let a = serve(first).await;
536 let b = serve(second).await;
537 let url_a = format!("http://{a}/a.tar.gz");
538 let url_b = format!("http://{b}/b.tar.gz");
539
540 run(&fx, None, install_spec(&url_a, SkillTargetScope::Project))
541 .await
542 .unwrap();
543 let receipt = run(&fx, None, install_spec(&url_b, SkillTargetScope::Project))
544 .await
545 .unwrap();
546 assert_eq!(receipt.outcome, SkillMutationOutcome::Updated);
547 assert!(
548 receipt
549 .summary
550 .contains(&format!("replaces the copy from {url_a}")),
551 "{}",
552 receipt.summary
553 );
554 }
555
556 #[tokio::test]
557 async fn remote_install_over_unmarked_directory_is_refused() {
558 let fx = Fixture::new();
559 let body = Arc::new(Mutex::new(tarball("hand-made", "remote")));
560 let addr = serve(body).await;
561 let existing = fx.skills_dir(SkillTargetScope::Project).join("hand-made");
562 fs::create_dir_all(&existing).unwrap();
563 fs::write(
564 existing.join("SKILL.md"),
565 "---\nname: hand-made\ndescription: d\n---\nmine\n",
566 )
567 .unwrap();
568 let err = run(
569 &fx,
570 None,
571 install_spec(
572 &format!("http://{addr}/x.tar.gz"),
573 SkillTargetScope::Project,
574 ),
575 )
576 .await
577 .unwrap_err();
578 assert!(
579 format!("{err:#}").contains("not installed here")
580 || format!("{err:#}").contains("hand-made"),
581 "{err:#}"
582 );
583 assert!(
584 fs::read_to_string(existing.join("SKILL.md"))
585 .unwrap()
586 .contains("mine")
587 );
588 }
589
590 #[tokio::test]
591 async fn remote_no_change_does_not_trust_locally_modified_content() {
592 let fx = Fixture::new();
593 let body = Arc::new(Mutex::new(tarball("tamper", "one")));
594 let addr = serve(body).await;
595 let url = format!("http://{addr}/t.tar.gz");
596 run(&fx, None, install_spec(&url, SkillTargetScope::Global))
597 .await
598 .unwrap();
599 let dest = fx.skills_dir(SkillTargetScope::Global).join("tamper");
600 fs::write(dest.join("extra.sh"), "echo hi").unwrap();
601 let receipt = run(
602 &fx,
603 Some(SkillInitiator::Person),
604 install_spec(&url, SkillTargetScope::Global),
605 )
606 .await
607 .unwrap();
608 assert_eq!(receipt.outcome, SkillMutationOutcome::NoChange);
609 assert!(dest.join("extra.sh").exists());
610 assert!(!dest.join(install::TRUSTED_MARKER).exists());
611 }
612
613 type ArchiveEntry<'a> = (&'a str, tar::EntryType, u32, &'a [u8], Option<&'a str>);
614
615 fn build_archive_bytes(entries: &[ArchiveEntry<'_>]) -> Vec<u8> {
616 let encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
617 let mut builder = tar::Builder::new(encoder);
618 for (path, kind, mode, data, link_target) in entries {
619 let mut header = tar::Header::new_gnu();
620 header.set_entry_type(*kind);
621 header.set_mode(*mode);
622 if let Some(target) = link_target {
623 header.set_size(0);
624 header.set_path(path).unwrap();
625 header.set_link_name(target).unwrap();
626 header.set_cksum();
627 builder.append(&header, std::io::empty()).unwrap();
628 } else {
629 let body: &[u8] = if *kind == tar::EntryType::Directory {
630 &[]
631 } else {
632 data
633 };
634 header.set_size(body.len() as u64);
635 let raw = path.as_bytes();
636 assert!(raw.len() <= 100);
637 header.as_gnu_mut().unwrap().name[..raw.len()].copy_from_slice(raw);
638 header.set_cksum();
639 builder.append(&header, body).unwrap();
640 }
641 }
642 builder.into_inner().unwrap().finish().unwrap()
643 }
644
645 #[tokio::test]
646 async fn local_tar_gz_and_tgz_install_update_and_preserve_exec() {
647 let fx = Fixture::new();
648 let skill_one = b"---\nname: pack-skill\ndescription: d\n---\nv1\n".to_vec();
649 let script = b"#!/bin/sh\necho ok\n";
650 let flat_bytes = build_archive_bytes(&[
651 ("SKILL.md", tar::EntryType::Regular, 0o644, &skill_one, None),
652 ("scripts/", tar::EntryType::Directory, 0o755, &[], None),
653 (
654 "scripts/run.sh",
655 tar::EntryType::Regular,
656 0o755,
657 script,
658 None,
659 ),
660 (
661 ".installed-from",
662 tar::EntryType::Regular,
663 0o644,
664 br#"{"spec":"spoofed"}"#,
665 None,
666 ),
667 (
668 ".trusted",
669 tar::EntryType::Regular,
670 0o644,
671 br#"{"digest":"spoofed"}"#,
672 None,
673 ),
674 ]);
675 let archive_path = fx.workspace.join("pack-skill.tar.gz");
676 fs::write(&archive_path, &flat_bytes).unwrap();
677
678 let first = run(
679 &fx,
680 None,
681 install_spec("./pack-skill.tar.gz", SkillTargetScope::Project),
682 )
683 .await
684 .unwrap();
685 assert_eq!(first.outcome, SkillMutationOutcome::Installed);
686 assert!(
687 first
688 .summary
689 .starts_with("Installed skill pack-skill (project) from path:")
690 && first.summary.ends_with(", on; includes 1 script"),
691 "{}",
692 first.summary
693 );
694 let dest = fx.skills_dir(SkillTargetScope::Project).join("pack-skill");
695 assert!(!dest.join(install::TRUSTED_MARKER).exists());
696 let marker = read_installed_marker(&dest).unwrap().unwrap();
697 assert!(marker.spec.starts_with("path:") && marker.spec.ends_with("pack-skill.tar.gz"));
698 #[cfg(unix)]
699 {
700 use std::os::unix::fs::PermissionsExt;
701 let mode = fs::metadata(dest.join("scripts/run.sh"))
702 .unwrap()
703 .permissions()
704 .mode();
705 assert_ne!(mode & 0o111, 0);
706 }
707
708 let same = run(
709 &fx,
710 None,
711 install_spec(&path_spec(&archive_path), SkillTargetScope::Project),
712 )
713 .await
714 .unwrap();
715 assert_eq!(same.outcome, SkillMutationOutcome::NoChange);
716
717 let skill_two = b"---\nname: pack-skill\ndescription: d\n---\nv2\n".to_vec();
718 let wrapped_v2 = build_archive_bytes(&[
719 ("repo-main/", tar::EntryType::Directory, 0o755, &[], None),
720 (
721 "repo-main/SKILL.md",
722 tar::EntryType::Regular,
723 0o644,
724 &skill_two,
725 None,
726 ),
727 (
728 "repo-main/scripts/",
729 tar::EntryType::Directory,
730 0o755,
731 &[],
732 None,
733 ),
734 (
735 "repo-main/scripts/run.sh",
736 tar::EntryType::Regular,
737 0o755,
738 script,
739 None,
740 ),
741 (
742 "repo-main/.TRUSTED",
743 tar::EntryType::Regular,
744 0o644,
745 br#"{"digest":"spoofed"}"#,
746 None,
747 ),
748 ]);
749 fs::write(&archive_path, &wrapped_v2).unwrap();
750
751 let updated = run(
752 &fx,
753 Some(SkillInitiator::Person),
754 SkillOneStepRequest::Mutation(SkillMutationRequest::UpdateByName {
755 name: "pack-skill".into(),
756 scope: Some(SkillTargetScope::Project),
757 expected_digest: None,
758 }),
759 )
760 .await
761 .unwrap();
762 assert_eq!(updated.outcome, SkillMutationOutcome::Updated);
763 assert!(
764 fs::read_to_string(dest.join("SKILL.md"))
765 .unwrap()
766 .contains("v2")
767 );
768 assert!(!dest.join(".TRUSTED").exists());
769 assert!(!dest.join(install::TRUSTED_MARKER).exists());
770
771 let tgz_path = fx.home.join("wrapped.tgz");
772 let tgz_skill = b"---\nname: tgz-global\ndescription: d\n---\nglobal\n".to_vec();
773 let tgz_bytes = build_archive_bytes(&[
774 ("wrapper/", tar::EntryType::Directory, 0o755, &[], None),
775 (
776 "wrapper/SKILL.md",
777 tar::EntryType::Regular,
778 0o644,
779 &tgz_skill,
780 None,
781 ),
782 (
783 "wrapper/.installed-from",
784 tar::EntryType::Regular,
785 0o644,
786 br#"{"spec":"spoofed"}"#,
787 None,
788 ),
789 ]);
790 fs::write(&tgz_path, &tgz_bytes).unwrap();
791
792 let global = run(
793 &fx,
794 Some(SkillInitiator::Person),
795 install_spec("~/wrapped.tgz", SkillTargetScope::Global),
796 )
797 .await
798 .unwrap();
799 assert_eq!(global.outcome, SkillMutationOutcome::Installed);
800 let global_dest = fx.skills_dir(SkillTargetScope::Global).join("tgz-global");
801 let digest = package_digest::compute_package_digest(&global_dest).unwrap();
802 assert!(
803 fs::read_to_string(global_dest.join(install::TRUSTED_MARKER))
804 .unwrap()
805 .contains(&digest)
806 );
807 }
808
809 #[tokio::test]
810 async fn local_archive_security_and_invalid_inputs_are_refused() {
811 let fx = Fixture::new();
812 let skill_md = b"---\nname: bad\ndescription: d\n---\nbad\n";
813
814 let symlink_bytes = build_archive_bytes(&[
815 ("SKILL.md", tar::EntryType::Regular, 0o644, skill_md, None),
816 (
817 "leak",
818 tar::EntryType::Symlink,
819 0o777,
820 &[],
821 Some("/etc/passwd"),
822 ),
823 ]);
824 let symlink_tar = fx.workspace.join("sym.tar.gz");
825 fs::write(&symlink_tar, symlink_bytes).unwrap();
826 assert!(
827 run(
828 &fx,
829 None,
830 install_spec(&path_spec(&symlink_tar), SkillTargetScope::Project),
831 )
832 .await
833 .is_err()
834 );
835
836 let hardlink_bytes = build_archive_bytes(&[
837 ("SKILL.md", tar::EntryType::Regular, 0o644, skill_md, None),
838 ("hard", tar::EntryType::Link, 0o644, &[], Some("SKILL.md")),
839 ]);
840 let hardlink_tar = fx.workspace.join("hard.tar.gz");
841 fs::write(&hardlink_tar, hardlink_bytes).unwrap();
842 assert!(
843 run(
844 &fx,
845 None,
846 install_spec(&path_spec(&hardlink_tar), SkillTargetScope::Project),
847 )
848 .await
849 .is_err()
850 );
851
852 for (file_name, entry_name) in [
853 ("dotdot.tar.gz", "../escape/SKILL.md"),
854 ("abs.tar.gz", "/tmp/evil/SKILL.md"),
855 ("backslash.tar.gz", "dir\\SKILL.md"),
856 ] {
857 let bytes =
858 build_archive_bytes(&[(entry_name, tar::EntryType::Regular, 0o644, skill_md, None)]);
859 let path = fx.workspace.join(file_name);
860 fs::write(&path, bytes).unwrap();
861 assert!(
862 run(
863 &fx,
864 None,
865 install_spec(&path_spec(&path), SkillTargetScope::Project),
866 )
867 .await
868 .is_err(),
869 "{file_name}"
870 );
871 }
872
873 let missing_md =
874 build_archive_bytes(&[("README.md", tar::EntryType::Regular, 0o644, b"hi", None)]);
875 let missing_tar = fx.workspace.join("missing.tar.gz");
876 fs::write(&missing_tar, missing_md).unwrap();
877 assert!(
878 run(
879 &fx,
880 None,
881 install_spec(&path_spec(&missing_tar), SkillTargetScope::Project),
882 )
883 .await
884 .is_err()
885 );
886
887 let many = codewhale_skill_install::bounded_tar::test_archives::empty_entries_archive(
888 ("SKILL.md", skill_md),
889 600,
890 );
891 let many_tar = fx.workspace.join("many.tar.gz");
892 fs::write(&many_tar, many).unwrap();
893 assert!(
894 run(
895 &fx,
896 None,
897 install_spec(&path_spec(&many_tar), SkillTargetScope::Project),
898 )
899 .await
900 .is_err()
901 );
902
903 let big_payload = vec![b'x'; 8192];
904 let big_bytes = build_archive_bytes(&[
905 ("SKILL.md", tar::EntryType::Regular, 0o644, skill_md, None),
906 (
907 "big.txt",
908 tar::EntryType::Regular,
909 0o644,
910 &big_payload,
911 None,
912 ),
913 ]);
914 let big_tar = fx.workspace.join("big.tar.gz");
915 fs::write(&big_tar, big_bytes).unwrap();
916 let mut small_ctx = fx.ctx();
917 small_ctx.max_size = 1024;
918 assert!(
919 execute_one_step(
920 install_spec(&path_spec(&big_tar), SkillTargetScope::Project),
921 None,
922 &small_ctx,
923 )
924 .await
925 .is_err()
926 );
927
928 let plain = fx.workspace.join("notes.txt");
929 fs::write(&plain, "not an archive").unwrap();
930 assert!(
931 run(
932 &fx,
933 None,
934 install_spec(&path_spec(&plain), SkillTargetScope::Project),
935 )
936 .await
937 .is_err()
938 );
939
940 #[cfg(unix)]
941 {
942 let real_tar = fx.workspace.join("real.tar.gz");
943 fs::write(&real_tar, tarball("linked-arc", "body")).unwrap();
944 let sym_tar = fx.workspace.join("sym-link.tar.gz");
945 std::os::unix::fs::symlink(&real_tar, &sym_tar).unwrap();
946 assert!(
947 run(
948 &fx,
949 None,
950 install_spec(&path_spec(&sym_tar), SkillTargetScope::Project),
951 )
952 .await
953 .is_err()
954 );
955 }
956
957 assert!(
958 !fx.skills_dir(SkillTargetScope::Project)
959 .join("bad")
960 .exists()
961 );
962 }
963
964 #[tokio::test]
965 async fn skills_state_off_survives_update_and_shows_off_in_receipt() {
966 let fx = Fixture::new();
967 let state_path = fx.home.join(".codewhale").join("skills_state.toml");
968 let mut store =
969 codewhale_runtime::skill_state::SkillStateStore::load_from(state_path.clone()).unwrap();
970 store.set_enabled("disabled-skill", false).unwrap();
971
972 let body = Arc::new(Mutex::new(tarball("disabled-skill", "one")));
973 let addr = serve(body.clone()).await;
974 let url = format!("http://{addr}/d.tar.gz");
975
976 let installed = run(&fx, None, install_spec(&url, SkillTargetScope::Project))
977 .await
978 .unwrap();
979 assert!(
980 installed.summary.ends_with(", off"),
981 "{}",
982 installed.summary
983 );
984
985 *body.lock().unwrap() = tarball("disabled-skill", "two");
986 let updated = run(&fx, None, install_spec(&url, SkillTargetScope::Project))
987 .await
988 .unwrap();
989 assert_eq!(updated.outcome, SkillMutationOutcome::Updated);
990 assert!(updated.summary.ends_with(", off"), "{}", updated.summary);
991 let after_store =
992 codewhale_runtime::skill_state::SkillStateStore::load_from(state_path).unwrap();
993 assert!(!after_store.is_enabled("disabled-skill"));
994 }
995
996 #[tokio::test]
997 async fn legacy_execute_install_remote_updates_in_place_without_auto_trust() {
998 let fx = Fixture::new();
999 let body = Arc::new(Mutex::new(tarball("legacy-skill", "one")));
1000 let addr = serve(body.clone()).await;
1001 let source = InstallSource::parse(&format!("http://{addr}/l.tar.gz")).unwrap();
1002
1003 let first = execute(
1004 SkillMutationRequest::InstallRemote {
1005 source: source.clone(),
1006 target: SkillTargetScope::Global,
1007 },
1008 &fx.ctx(),
1009 )
1010 .await
1011 .unwrap();
1012 assert_eq!(first.outcome, SkillMutationOutcome::Installed);
1013 let dest = fx.skills_dir(SkillTargetScope::Global).join("legacy-skill");
1014 assert!(!dest.join(install::TRUSTED_MARKER).exists());
1015
1016 let same = execute(
1017 SkillMutationRequest::InstallRemote {
1018 source: source.clone(),
1019 target: SkillTargetScope::Global,
1020 },
1021 &fx.ctx(),
1022 )
1023 .await
1024 .unwrap();
1025 assert_eq!(same.outcome, SkillMutationOutcome::NoChange);
1026
1027 *body.lock().unwrap() = tarball("legacy-skill", "two");
1028 let updated = execute(
1029 SkillMutationRequest::InstallRemote {
1030 source,
1031 target: SkillTargetScope::Global,
1032 },
1033 &fx.ctx(),
1034 )
1035 .await
1036 .unwrap();
1037 assert_eq!(updated.outcome, SkillMutationOutcome::Updated);
1038 assert!(!dest.join(install::TRUSTED_MARKER).exists());
1039 }
1040
1040 lines RUST