ignition-core 1.7.1

Core library for ign: config, profiles, gateway client, actions, error taxonomy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
//! `impl ProjectHost for LocalFsTransport` (Phase 25, 25-07): the host half of
//! `deploy projects` on a data directory on the runner's own filesystem.
//!
//! Layout below `data_dir`:
//!
//! ```text
//! projects/<project>/.git                                   probed, never opened
//! ign-deploy/<gateway>/projects/<project>/release.json      the release record
//! ign-deploy/<gateway>/tag-providers/<provider>/record.json the tag record (26-06)
//! ign-deploy/<gateway>/projects/<project>/journal.json      the run journal (26-12)
//! ign-deploy/<gateway>/projects/<project>/pre-image/<name>  the run pre-image (26-12)
//! ```
//!
//! The reads run on a blocking thread and inspect every level with
//! `symlink_metadata`, so nothing is followed. See [`ProjectHost`] for the
//! fail-closed rule: only a clean "no such entry" is absent.
//!
//! The writes are the release record ([`ReleaseRecordWriter`], 25-11) and
//! the tag record ([`TagRecordWriter`], 26-06), each one file: a private
//! temporary sibling renamed over the record through a directory handle that
//! refuses a symlink at every level, exactly as the local ledger is replaced.
//! Both go through [`LocalFsTransport::replace_record_blocking`], and both
//! reads through the shared capped regular-file read.
//!
//! 26-12 adds the project run files beside the release record
//! (`journal.json`, `pre-image/<fixed name>`, [`ProjectRunWriter`]) through
//! the same replace and the same read.

use super::LocalFsTransport;
use crate::deploy::component_problem;
use crate::deploy::ledger::{
    LedgerRoot, RELEASE_RECORD_FILE, RELEASE_RECORD_MAX_BYTES, pre_image_location, pre_image_rel,
    project_journal_location, project_journal_rel, release_record_location, release_record_rel,
    tag_record_location, tag_record_rel,
};
use crate::deploy::project_run::{
    PRE_IMAGE_MAX_BYTES, PROJECT_JOURNAL_FILE, PROJECT_JOURNAL_MAX_BYTES, ProjectJournal,
};
use crate::deploy::projects::ReleaseRecord;
use crate::deploy::tag_record::{TAG_RECORD_FILE, TAG_RECORD_MAX_BYTES, TagRecord};
use crate::deploy::transport::local_fs::{Dir, FsError, Kind};
use crate::deploy::transport::projects::{
    GitEntry, ProjectHost, ProjectRunWriter, ReleaseRecordWriter, TagRecordWriter,
    check_pre_image_write, git_entry_location, project_run_names_problem_on,
    tag_record_names_problem_on,
};
use crate::error::CoreError;

impl LocalFsTransport {
    /// What `<data_dir>/projects/<project>/.git` is, probed with
    /// `symlink_metadata` at every level (nothing is followed).
    fn git_entry_blocking(&self, project: &str) -> Result<GitEntry, CoreError> {
        if let Some(why) = component_problem(project) {
            return Err(self.fail(format!("the project name {why}")));
        }
        // An unreadable host is not an absent `.git`.
        self.require_data_dir()?;

        let projects = self.data_dir.join("projects");
        match std::fs::symlink_metadata(&projects) {
            Ok(m) if m.file_type().is_symlink() => {
                return Err(self.fail("projects is a symlink; symlinks are refused"));
            }
            Ok(m) if !m.file_type().is_dir() => {
                return Err(self.fail("projects is not a directory"));
            }
            Ok(_) => {}
            Err(e) => {
                return Err(self.fail(format!(
                    "projects cannot be inspected ({}); is data_dir the gateway data directory?",
                    e.kind()
                )));
            }
        }

        let project_dir = projects.join(project);
        match std::fs::symlink_metadata(&project_dir) {
            // No project directory: nothing to be git-managed (the `create`
            // case).
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(GitEntry::Absent),
            Err(e) => {
                return Err(self.fail(format!(
                    "projects/{project} cannot be inspected ({})",
                    e.kind()
                )));
            }
            Ok(m) if m.file_type().is_symlink() => {
                return Err(self.fail(format!(
                    "projects/{project} is a symlink; symlinks are refused"
                )));
            }
            Ok(m) if !m.file_type().is_dir() => {
                return Err(self.fail(format!("projects/{project} is not a directory")));
            }
            Ok(_) => {}
        }

        let location = git_entry_location(project);
        match std::fs::symlink_metadata(project_dir.join(".git")) {
            Ok(m) => {
                let kind = m.file_type();
                Ok(if kind.is_symlink() {
                    GitEntry::Symlink
                } else if kind.is_dir() {
                    GitEntry::Directory
                } else if kind.is_file() {
                    GitEntry::File
                } else {
                    GitEntry::Other
                })
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(GitEntry::Absent),
            // Denied, I/O error and everything else: unknown, not absent.
            Err(e) => Err(self.fail(format!("{location} cannot be inspected ({})", e.kind()))),
        }
    }

    /// The release-record bytes, or `None` when any level of its path is
    /// absent. A refusal is `deploy_run_invalid` naming the location.
    fn read_release_record_blocking(
        &self,
        gateway: &str,
        project: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let location = release_record_location(LedgerRoot::DataDir, gateway, project);
        let bad = |problem: String| CoreError::DeployRunInvalid {
            run_id: "unknown".to_string(),
            problem: format!("{location}: {problem}"),
        };
        for (kind, value) in [("gateway", gateway), ("project", project)] {
            if let Some(why) = component_problem(value) {
                return Err(bad(format!("the {kind} name {why}")));
            }
        }
        self.read_regular_blocking(
            &release_record_rel(gateway, project),
            RELEASE_RECORD_MAX_BYTES,
            "the release record",
            (gateway, project),
            &bad,
        )
    }

    /// The tag-record bytes, or `None` when any level of its path is absent.
    /// A refusal is `deploy_run_invalid` naming the location.
    fn read_tag_record_blocking(
        &self,
        gateway: &str,
        provider: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let location = tag_record_location(LedgerRoot::DataDir, gateway, provider);
        let bad = |problem: String| CoreError::DeployRunInvalid {
            run_id: "unknown".to_string(),
            problem: format!("{location}: {problem}"),
        };
        if let Some(why) = tag_record_names_problem_on(gateway, provider, None) {
            return Err(bad(why));
        }
        self.read_regular_blocking(
            &tag_record_rel(gateway, provider),
            TAG_RECORD_MAX_BYTES,
            "the tag record",
            (gateway, provider),
            &bad,
        )
    }
}

/// A `deploy_run_invalid` naming `location`.
fn run_invalid(location: &str, problem: impl std::fmt::Display) -> CoreError {
    CoreError::DeployRunInvalid {
        run_id: "unknown".to_string(),
        problem: format!("{location}: {problem}"),
    }
}

impl LocalFsTransport {
    /// The project journal bytes (26-12), or `None` when any level of its
    /// path is absent.
    fn read_project_journal_blocking(
        &self,
        gateway: &str,
        project: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let location = project_journal_location(LedgerRoot::DataDir, gateway, project);
        let bad = |problem: String| run_invalid(&location, problem);
        if let Some(why) = project_run_names_problem_on(gateway, project, None, None) {
            return Err(bad(why));
        }
        self.read_regular_blocking(
            &project_journal_rel(gateway, project),
            PROJECT_JOURNAL_MAX_BYTES,
            "the journal",
            (gateway, project),
            &bad,
        )
    }

    /// One pre-image file (26-12), or `None` when any level of its path is
    /// absent.
    fn read_pre_image_blocking(
        &self,
        gateway: &str,
        project: &str,
        name: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let location = pre_image_location(LedgerRoot::DataDir, gateway, project, name);
        let bad = |problem: String| run_invalid(&location, problem);
        if let Some(why) = project_run_names_problem_on(gateway, project, Some(name), None) {
            return Err(bad(why));
        }
        self.read_regular_blocking(
            &pre_image_rel(gateway, project, name),
            PRE_IMAGE_MAX_BYTES,
            "the pre-image file",
            (gateway, project),
            &bad,
        )
    }

    /// Replace the project journal with `bytes`, which must be this gateway's
    /// and project's journal.
    fn write_project_journal_blocking(
        &self,
        gateway: &str,
        project: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let location = project_journal_location(LedgerRoot::DataDir, gateway, project);
        if let Some(why) = project_run_names_problem_on(gateway, project, None, None) {
            return Err(run_invalid(&location, why));
        }
        let journal = ProjectJournal::parse(bytes, &location, gateway, project)?;
        let temp_name = format!("{PROJECT_JOURNAL_FILE}.tmp-{}", journal.run_id);
        self.replace_record_blocking(
            &location,
            &project_journal_rel(gateway, project),
            &temp_name,
            bytes,
        )
    }

    /// Replace the pre-image file `name` of run `run_id` with `bytes`: a
    /// fixed name only, at most [`PRE_IMAGE_MAX_BYTES`], and a `run.json`
    /// only when it is this run's set.
    fn write_pre_image_blocking(
        &self,
        gateway: &str,
        project: &str,
        run_id: &str,
        name: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let location = pre_image_location(LedgerRoot::DataDir, gateway, project, name);
        check_pre_image_write(&location, gateway, project, run_id, name, bytes, None)?;
        self.replace_record_blocking(
            &location,
            &pre_image_rel(gateway, project, name),
            &format!("{name}.tmp-{run_id}"),
            bytes,
        )
    }

    /// Remove `journal.json` and nothing else; absent is a success, a
    /// symlink or anything but a regular file is refused and left.
    fn clear_project_journal_blocking(
        &self,
        gateway: &str,
        project: &str,
    ) -> Result<(), CoreError> {
        let location = project_journal_location(LedgerRoot::DataDir, gateway, project);
        if let Some(why) = project_run_names_problem_on(gateway, project, None, None) {
            return Err(run_invalid(&location, why));
        }
        self.require_data_dir()?;
        let failed = |e: FsError| match e {
            FsError::Changed => run_invalid(
                &location,
                "a path component is, or became, a symlink or a non-directory; refused",
            ),
            other => self.mirror_fail(
                "write",
                format!("{location} cannot be removed: {}", other.describe()),
            ),
        };
        let root = Dir::root(&self.data_dir).map_err(failed)?;
        let rel = project_journal_rel(gateway, project);
        let parts: Vec<&str> = rel.split('/').collect();
        match root.kind(&parts).map_err(failed)? {
            Kind::Missing => Ok(()),
            Kind::File => match root.unlink(&parts) {
                Ok(()) | Err(FsError::Missing) => Ok(()),
                Err(e) => Err(failed(e)),
            },
            Kind::Symlink => Err(run_invalid(
                &location,
                "the journal is a symlink; symlinks are refused",
            )),
            Kind::Dir | Kind::Other => {
                Err(run_invalid(&location, "the journal is not a regular file"))
            }
        }
    }
}

impl LocalFsTransport {
    /// Replace the release record of `project` on `gateway` with `bytes`.
    ///
    /// The names get the check the read applies, and `bytes` must be a valid
    /// record for them, so a wrong caller cannot put anything else on the
    /// host. A symlink at any level is refused. The record is written to a
    /// private temporary sibling named for the run, flushed and renamed over
    /// the old one; the sibling is removed again when a step fails, and a
    /// removal that fails is named in the error.
    fn write_release_record_blocking(
        &self,
        gateway: &str,
        project: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let location = release_record_location(LedgerRoot::DataDir, gateway, project);
        let bad = |problem: String| CoreError::DeployRunInvalid {
            run_id: "unknown".to_string(),
            problem: format!("{location}: {problem}"),
        };
        for (kind, value) in [("gateway", gateway), ("project", project)] {
            if let Some(why) = component_problem(value) {
                return Err(bad(format!("the {kind} name {why}")));
            }
        }
        // The same parse the read applies: a record that would be refused on
        // the way back is never put there.
        let record = ReleaseRecord::parse(bytes, &location, gateway, project)?;
        // The temporary sibling is named for the run, as the ssh writer's is,
        // so two runs on one data directory never write the same file. The
        // run id is already held to `[A-Za-z0-9._-]{1,128}`.
        let temp_name = format!("{RELEASE_RECORD_FILE}.tmp-{}", record.run_id);
        self.replace_record_blocking(
            &location,
            &release_record_rel(gateway, project),
            &temp_name,
            bytes,
        )
    }

    /// Replace the tag record of `provider` on `gateway` with `bytes`, under
    /// the same rules as the release record: the names are checked, `bytes`
    /// must be this gateway's and provider's [`TagRecord`], and the file is
    /// replaced atomically through a temporary sibling named for the run.
    fn write_tag_record_blocking(
        &self,
        gateway: &str,
        provider: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let location = tag_record_location(LedgerRoot::DataDir, gateway, provider);
        if let Some(why) = tag_record_names_problem_on(gateway, provider, None) {
            return Err(CoreError::DeployRunInvalid {
                run_id: "unknown".to_string(),
                problem: format!("{location}: {why}"),
            });
        }
        let record = TagRecord::parse(bytes, &location, gateway, provider)?;
        let temp_name = format!("{TAG_RECORD_FILE}.tmp-{}", record.run_id);
        self.replace_record_blocking(
            &location,
            &tag_record_rel(gateway, provider),
            &temp_name,
            bytes,
        )
    }

    /// Replace the record file at `rel` below `data_dir` with `bytes`: write
    /// the private temporary sibling `temp_name`, flush it and rename it over
    /// the record through a directory handle that refuses a symlink at every
    /// level. The sibling is removed again when a step fails. The callers have
    /// already checked the names and parsed `bytes`.
    fn replace_record_blocking(
        &self,
        location: &str,
        rel: &str,
        temp_name: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        // An unwritable host is an error, not a skipped record.
        self.require_data_dir()?;
        let failed = |e: FsError| match e {
            FsError::Changed => CoreError::DeployRunInvalid {
                run_id: "unknown".to_string(),
                problem: format!(
                    "{location}: a path component is, or became, a symlink or a non-directory; refused"
                ),
            },
            other => self.mirror_fail(
                "write",
                format!("{location} cannot be written: {}", other.describe()),
            ),
        };
        let root = Dir::root(&self.data_dir).map_err(failed)?;
        let parts: Vec<&str> = rel.split('/').collect();
        root.replace_via(&parts, temp_name, bytes).map_err(failed)
    }
}

#[async_trait::async_trait]
impl ReleaseRecordWriter for LocalFsTransport {
    async fn write_release_record(
        &self,
        gateway: &str,
        project: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let this = self.clone();
        let (gateway, project, bytes) = (gateway.to_string(), project.to_string(), bytes.to_vec());
        tokio::task::spawn_blocking(move || {
            this.write_release_record_blocking(&gateway, &project, &bytes)
        })
        .await
        .map_err(|e| CoreError::Internal(format!("local write task failed: {e}")))?
    }
}

#[async_trait::async_trait]
impl TagRecordWriter for LocalFsTransport {
    async fn write_tag_record(
        &self,
        gateway: &str,
        provider: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let this = self.clone();
        let (gateway, provider, bytes) =
            (gateway.to_string(), provider.to_string(), bytes.to_vec());
        tokio::task::spawn_blocking(move || {
            this.write_tag_record_blocking(&gateway, &provider, &bytes)
        })
        .await
        .map_err(|e| CoreError::Internal(format!("local write task failed: {e}")))?
    }
}

#[async_trait::async_trait]
impl ProjectRunWriter for LocalFsTransport {
    async fn write_journal(
        &self,
        gateway: &str,
        project: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let this = self.clone();
        let (gateway, project, bytes) = (gateway.to_string(), project.to_string(), bytes.to_vec());
        tokio::task::spawn_blocking(move || {
            this.write_project_journal_blocking(&gateway, &project, &bytes)
        })
        .await
        .map_err(|e| CoreError::Internal(format!("local write task failed: {e}")))?
    }

    async fn clear_journal(&self, gateway: &str, project: &str) -> Result<(), CoreError> {
        let this = self.clone();
        let (gateway, project) = (gateway.to_string(), project.to_string());
        tokio::task::spawn_blocking(move || this.clear_project_journal_blocking(&gateway, &project))
            .await
            .map_err(|e| CoreError::Internal(format!("local write task failed: {e}")))?
    }

    async fn write_pre_image(
        &self,
        gateway: &str,
        project: &str,
        run_id: &str,
        name: &str,
        bytes: &[u8],
    ) -> Result<(), CoreError> {
        let this = self.clone();
        let (gateway, project, run_id, name, bytes) = (
            gateway.to_string(),
            project.to_string(),
            run_id.to_string(),
            name.to_string(),
            bytes.to_vec(),
        );
        tokio::task::spawn_blocking(move || {
            this.write_pre_image_blocking(&gateway, &project, &run_id, &name, &bytes)
        })
        .await
        .map_err(|e| CoreError::Internal(format!("local write task failed: {e}")))?
    }
}

#[async_trait::async_trait]
impl ProjectHost for LocalFsTransport {
    async fn git_entry(&self, project: &str) -> Result<GitEntry, CoreError> {
        let this = self.clone();
        let project = project.to_string();
        tokio::task::spawn_blocking(move || this.git_entry_blocking(&project))
            .await
            .map_err(|e| CoreError::Internal(format!("local read task failed: {e}")))?
    }

    async fn read_release_record(
        &self,
        gateway: &str,
        project: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let this = self.clone();
        let (gateway, project) = (gateway.to_string(), project.to_string());
        tokio::task::spawn_blocking(move || this.read_release_record_blocking(&gateway, &project))
            .await
            .map_err(|e| CoreError::Internal(format!("local read task failed: {e}")))?
    }

    async fn read_tag_record(
        &self,
        gateway: &str,
        provider: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let this = self.clone();
        let (gateway, provider) = (gateway.to_string(), provider.to_string());
        tokio::task::spawn_blocking(move || this.read_tag_record_blocking(&gateway, &provider))
            .await
            .map_err(|e| CoreError::Internal(format!("local read task failed: {e}")))?
    }

    async fn read_journal(
        &self,
        gateway: &str,
        project: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let this = self.clone();
        let (gateway, project) = (gateway.to_string(), project.to_string());
        tokio::task::spawn_blocking(move || this.read_project_journal_blocking(&gateway, &project))
            .await
            .map_err(|e| CoreError::Internal(format!("local read task failed: {e}")))?
    }

    async fn read_pre_image(
        &self,
        gateway: &str,
        project: &str,
        name: &str,
    ) -> Result<Option<Vec<u8>>, CoreError> {
        let this = self.clone();
        let (gateway, project, name) = (gateway.to_string(), project.to_string(), name.to_string());
        tokio::task::spawn_blocking(move || this.read_pre_image_blocking(&gateway, &project, &name))
            .await
            .map_err(|e| CoreError::Internal(format!("local read task failed: {e}")))?
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::Path;

    fn host(data: &Path) -> LocalFsTransport {
        LocalFsTransport::new(data.to_path_buf(), "nodes.master")
    }

    fn data_with_projects() -> tempfile::TempDir {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::create_dir_all(dir.path().join("projects")).expect("projects");
        dir
    }

    #[test]
    fn local_git_entry_kinds() {
        let dir = data_with_projects();
        let projects = dir.path().join("projects");
        let t = host(dir.path());

        // No project directory: absent.
        assert_eq!(
            t.git_entry_blocking("Nope").expect("absent"),
            GitEntry::Absent
        );
        // A project directory without .git: absent.
        std::fs::create_dir_all(projects.join("Plain")).expect("plain");
        assert_eq!(
            t.git_entry_blocking("Plain").expect("plain"),
            GitEntry::Absent
        );
        // .git as a directory.
        std::fs::create_dir_all(projects.join("Dir/.git")).expect("dir");
        assert_eq!(
            t.git_entry_blocking("Dir").expect("dir"),
            GitEntry::Directory
        );
        // .git as a file (a worktree or submodule pointer).
        std::fs::create_dir_all(projects.join("File")).expect("file dir");
        std::fs::write(projects.join("File/.git"), b"gitdir: ../x").expect("file");
        assert_eq!(t.git_entry_blocking("File").expect("file"), GitEntry::File);
        // .git as a symlink, dangling or not: reported, never followed.
        #[cfg(unix)]
        {
            std::fs::create_dir_all(projects.join("Link")).expect("link dir");
            std::os::unix::fs::symlink("/nonexistent/target", projects.join("Link/.git"))
                .expect("symlink");
            assert_eq!(
                t.git_entry_blocking("Link").expect("link"),
                GitEntry::Symlink
            );
        }
    }

    #[test]
    fn local_git_entry_missing_projects_dir_is_transport_failed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let err = host(dir.path())
            .git_entry_blocking("CapApp")
            .expect_err("no data/projects");
        assert_eq!(err.code(), "transport_failed");
        assert!(err.to_string().contains("projects"), "{err}");

        // A data_dir that does not exist at all fails the same way.
        let err = host(&dir.path().join("gone"))
            .git_entry_blocking("CapApp")
            .expect_err("no data_dir");
        assert_eq!(err.code(), "transport_failed");
    }

    #[test]
    fn local_git_entry_refuses_a_project_that_is_not_a_directory() {
        let dir = data_with_projects();
        std::fs::write(dir.path().join("projects/CapApp"), b"x").expect("file");
        let err = host(dir.path())
            .git_entry_blocking("CapApp")
            .expect_err("a file where the project directory belongs");
        assert_eq!(err.code(), "transport_failed");
    }

    #[test]
    fn local_git_entry_refuses_unsafe_project_names() {
        let dir = data_with_projects();
        for bad in ["", ".", "..", "a/b", "a\\b", ".git"] {
            let err = host(dir.path())
                .git_entry_blocking(bad)
                .expect_err("unsafe name");
            assert_eq!(err.code(), "transport_failed", "{bad:?}");
        }
    }

    #[cfg(unix)]
    #[test]
    fn local_git_entry_unreadable_project_dir_is_transport_failed_not_absent() {
        use std::os::unix::fs::PermissionsExt;
        let dir = data_with_projects();
        let project = dir.path().join("projects/CapApp");
        std::fs::create_dir_all(project.join(".git")).expect("git dir");
        std::fs::set_permissions(&project, std::fs::Permissions::from_mode(0o000)).expect("chmod");
        // A privileged user (root) ignores the mode; the probe cannot be
        // denied there, and the assertion below would not hold.
        let privileged = std::fs::read_dir(&project).is_ok();
        let result = host(dir.path()).git_entry_blocking("CapApp");
        std::fs::set_permissions(&project, std::fs::Permissions::from_mode(0o755))
            .expect("restore");
        if privileged {
            assert_eq!(result.expect("privileged probe"), GitEntry::Directory);
        } else {
            let err = result.expect_err("a denied probe is not an answer");
            assert_eq!(err.code(), "transport_failed");
            assert!(err.to_string().contains("projects/CapApp/.git"), "{err}");
        }
    }

    fn write_record(data: &Path, gateway: &str, project: &str, bytes: &[u8]) {
        let path = data.join(release_record_rel(gateway, project));
        std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        std::fs::write(path, bytes).expect("write");
    }

    #[test]
    fn local_release_record_read() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let read = || t.read_release_record_blocking("gw", "CapApp");

        // Absent at every level.
        assert_eq!(read().expect("no ign-deploy"), None);
        std::fs::create_dir_all(dir.path().join("ign-deploy/gw/projects")).expect("mkdir");
        assert_eq!(read().expect("no project dir"), None);
        std::fs::create_dir_all(dir.path().join("ign-deploy/gw/projects/CapApp")).expect("mkdir");
        assert_eq!(read().expect("no file"), None);

        // A regular file returns its bytes.
        write_record(dir.path(), "gw", "CapApp", b"{\"schema_version\":1}");
        assert_eq!(
            read().expect("file"),
            Some(b"{\"schema_version\":1}".to_vec())
        );

        // Over the cap.
        write_record(
            dir.path(),
            "gw",
            "CapApp",
            &vec![b'x'; RELEASE_RECORD_MAX_BYTES + 1],
        );
        let err = read().expect_err("over the cap");
        assert_eq!(err.code(), "deploy_run_invalid");
        assert!(
            err.to_string()
                .contains("ign-deploy/gw/projects/CapApp/release.json"),
            "{err}"
        );

        // A directory where the file belongs.
        let file = dir.path().join(release_record_rel("gw", "CapApp"));
        std::fs::remove_file(&file).expect("rm");
        std::fs::create_dir(&file).expect("dir");
        let err = read().expect_err("a directory");
        assert_eq!(err.code(), "deploy_run_invalid");
    }

    #[cfg(unix)]
    #[test]
    fn local_release_record_refuses_symlinks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let outside = dir.path().join("outside.json");
        std::fs::write(&outside, b"{}").expect("outside");
        let file = dir.path().join(release_record_rel("gw", "CapApp"));
        std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
        std::os::unix::fs::symlink(&outside, &file).expect("symlink");
        let err = t
            .read_release_record_blocking("gw", "CapApp")
            .expect_err("a symlinked record");
        assert_eq!(err.code(), "deploy_run_invalid");

        // A symlinked directory above the record is refused the same way.
        std::fs::remove_file(&file).expect("rm");
        let real = dir.path().join("elsewhere");
        std::fs::create_dir_all(&real).expect("real");
        std::fs::remove_dir(file.parent().expect("parent")).expect("rmdir");
        std::os::unix::fs::symlink(&real, file.parent().expect("parent")).expect("dir link");
        let err = t
            .read_release_record_blocking("gw", "CapApp")
            .expect_err("a symlinked directory");
        assert_eq!(err.code(), "deploy_run_invalid");
    }

    #[test]
    fn local_release_record_with_an_unreadable_host_is_not_absent() {
        let dir = tempfile::tempdir().expect("tempdir");
        let err = host(&dir.path().join("gone"))
            .read_release_record_blocking("gw", "CapApp")
            .expect_err("no data_dir");
        assert_eq!(err.code(), "transport_failed");
    }

    #[test]
    fn local_release_record_refuses_unsafe_names() {
        let dir = tempfile::tempdir().expect("tempdir");
        for (gateway, project) in [
            ("..", "CapApp"),
            ("gw", ".."),
            ("gw", "a/b"),
            ("", "CapApp"),
        ] {
            let err = host(dir.path())
                .read_release_record_blocking(gateway, project)
                .expect_err("unsafe name");
            assert_eq!(err.code(), "deploy_run_invalid", "{gateway:?} {project:?}");
        }
    }

    fn record_bytes(gateway: &str, project: &str, release: &str) -> Vec<u8> {
        ReleaseRecord {
            schema_version: 1,
            gateway: gateway.to_string(),
            project: project.to_string(),
            release: release.to_string(),
            artifact_sha256: "a".repeat(64),
            run_id: "20261020T101500Z-ab12".to_string(),
            deployed_at: "2026-10-20T10:15:00Z".to_string(),
        }
        .to_bytes()
    }

    /// V5: the record is written below the ledger root, read back by the
    /// reader that gates the next deploy, and replaced by the next one. No
    /// temporary file is left behind.
    #[test]
    fn local_release_record_write_round_trips_and_replaces() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let first = record_bytes("gw", "CapApp", "v1.0.0");
        t.write_release_record_blocking("gw", "CapApp", &first)
            .expect("write");
        assert_eq!(
            t.read_release_record_blocking("gw", "CapApp")
                .expect("read"),
            Some(first)
        );
        let second = record_bytes("gw", "CapApp", "v1.1.0");
        t.write_release_record_blocking("gw", "CapApp", &second)
            .expect("replace");
        assert_eq!(
            t.read_release_record_blocking("gw", "CapApp")
                .expect("read"),
            Some(second)
        );
        let folder = dir.path().join("ign-deploy/gw/projects/CapApp");
        let names: Vec<String> = std::fs::read_dir(&folder)
            .expect("folder")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, ["release.json"], "no temporary file is left");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(folder.join("release.json"))
                .expect("metadata")
                .permissions()
                .mode();
            assert_eq!(mode & 0o777, 0o600);
        }
    }

    /// WR-04: the temporary sibling is named for the run. Another run's
    /// temporary file in the same folder (the old shared name, or one with
    /// another run id) is neither read, removed nor renamed in, and this
    /// run's own is gone afterwards.
    #[test]
    fn local_release_record_write_uses_a_per_run_temporary_name() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let folder = dir.path().join("ign-deploy/gw/projects/CapApp");
        std::fs::create_dir_all(&folder).expect("folder");
        std::fs::write(folder.join("release.json.ign-new"), b"the shared name").expect("a");
        std::fs::write(folder.join("release.json.tmp-other-run"), b"another run").expect("b");

        let record = record_bytes("gw", "CapApp", "v1.0.0");
        t.write_release_record_blocking("gw", "CapApp", &record)
            .expect("write");

        assert_eq!(
            std::fs::read(folder.join("release.json")).expect("record"),
            record
        );
        assert_eq!(
            std::fs::read(folder.join("release.json.ign-new")).expect("kept"),
            b"the shared name"
        );
        assert_eq!(
            std::fs::read(folder.join("release.json.tmp-other-run")).expect("kept"),
            b"another run"
        );
        let mut names: Vec<String> = std::fs::read_dir(&folder)
            .expect("folder")
            .map(|e| e.expect("entry").file_name().to_string_lossy().into_owned())
            .collect();
        names.sort();
        assert_eq!(
            names,
            [
                "release.json",
                "release.json.ign-new",
                "release.json.tmp-other-run"
            ],
            "this run's temporary file is gone"
        );
    }

    /// The writer applies the reader's name check and refuses bytes that are
    /// not a record for those names; nothing is created for a refusal.
    #[test]
    fn local_release_record_write_fails_closed() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let good = record_bytes("gw", "CapApp", "v1.0.0");
        for (gateway, project) in [
            ("..", "CapApp"),
            ("gw", ".."),
            ("gw", "a/b"),
            ("", "CapApp"),
            ("gw", ".git"),
        ] {
            let err = t
                .write_release_record_blocking(gateway, project, &good)
                .expect_err("unsafe name");
            assert_eq!(err.code(), "deploy_run_invalid", "{gateway:?} {project:?}");
        }
        // Not a record, a record for another project, an over-cap blob.
        for bytes in [
            b"{}".to_vec(),
            b"not json".to_vec(),
            record_bytes("gw", "Other", "v1.0.0"),
            vec![b'x'; RELEASE_RECORD_MAX_BYTES + 1],
        ] {
            let err = t
                .write_release_record_blocking("gw", "CapApp", &bytes)
                .expect_err("not this project's record");
            assert_eq!(err.code(), "deploy_run_invalid");
        }
        assert!(
            !dir.path().join("ign-deploy").exists(),
            "a refused write creates nothing"
        );
        // An unwritable host is an error, not a skipped record.
        let err = host(&dir.path().join("gone"))
            .write_release_record_blocking("gw", "CapApp", &good)
            .expect_err("no data_dir");
        assert_eq!(err.code(), "transport_failed");
    }

    /// A symlink on the record's path is never followed, at the file or at
    /// any directory above it.
    #[cfg(unix)]
    #[test]
    fn local_release_record_write_refuses_symlinks() {
        let dir = tempfile::tempdir().expect("tempdir");
        let t = host(dir.path());
        let bytes = record_bytes("gw", "CapApp", "v1.0.0");
        let outside = dir.path().join("outside.json");
        std::fs::write(&outside, b"keep").expect("outside");
        let file = dir.path().join(release_record_rel("gw", "CapApp"));
        std::fs::create_dir_all(file.parent().expect("parent")).expect("mkdir");
        std::os::unix::fs::symlink(&outside, &file).expect("symlink");
        let err = t
            .write_release_record_blocking("gw", "CapApp", &bytes)
            .expect_err("a symlinked record");
        assert_eq!(err.code(), "deploy_run_invalid");
        assert_eq!(std::fs::read(&outside).expect("untouched"), b"keep");

        std::fs::remove_file(&file).expect("rm");
        let real = dir.path().join("elsewhere");
        std::fs::create_dir_all(&real).expect("real");
        std::fs::remove_dir(file.parent().expect("parent")).expect("rmdir");
        std::os::unix::fs::symlink(&real, file.parent().expect("parent")).expect("dir link");
        let err = t
            .write_release_record_blocking("gw", "CapApp", &bytes)
            .expect_err("a symlinked directory");
        assert_eq!(err.code(), "deploy_run_invalid");
        assert_eq!(
            std::fs::read_dir(&real).expect("real").count(),
            0,
            "nothing was written through the link"
        );
    }

    #[tokio::test]
    async fn the_writer_works_through_the_trait() {
        let dir = tempfile::tempdir().expect("tempdir");
        let w: Box<dyn ReleaseRecordWriter> = Box::new(host(dir.path()));
        let bytes = record_bytes("gw", "CapApp", "v1.0.0");
        w.write_release_record("gw", "CapApp", &bytes)
            .await
            .expect("write");
        let t = host(dir.path());
        assert_eq!(
            t.read_release_record("gw", "CapApp").await.expect("read"),
            Some(bytes)
        );
    }

    #[tokio::test]
    async fn the_host_works_through_the_trait() {
        let dir = data_with_projects();
        std::fs::create_dir_all(dir.path().join("projects/CapApp/.git")).expect("git");
        let t: Box<dyn ProjectHost> = Box::new(host(dir.path()));
        assert_eq!(
            t.git_entry("CapApp").await.expect("probe"),
            GitEntry::Directory
        );
        assert_eq!(
            t.read_release_record("gw", "CapApp").await.expect("record"),
            None
        );
    }
}