1use crate::{
3 Error, Manifest, Result,
4 adoption::{self, Boundary, Event, anchors, checked_bytes, parent_identity, same},
5 context::HostContext,
6 error::io_error,
7 journal::{self, Phase, Progress},
8 local::LocalConfig,
9 model::Tool,
10 observation::{self, Entry, Kind},
11 state::WriterLock,
12 tool_journal::{Header, Journal, Operation},
13};
14use rustix::fs::{self, Mode, OFlags, RenameFlags};
15use serde::{Deserialize, Serialize};
16use std::{
17 fs::File,
18 path::{Path, PathBuf},
19};
20const MAX_TOOLS: usize = 4096;
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "kebab-case")]
24pub enum Change {
25 Edit,
26 Remove,
27}
28#[derive(Serialize)]
30pub struct Preview {
31 pub schema: u32,
32 pub preview_only: bool,
33 pub repository: PathBuf,
34 pub repository_id: String,
35 pub tool: Tool,
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub change: Option<Change>,
38 #[serde(skip_serializing_if = "Option::is_none")]
39 pub before: Option<Tool>,
40 pub profiles: Vec<String>,
41 pub no_op: bool,
42 pub effects: Vec<PathBuf>,
43 #[serde(skip)]
44 host: HostContext,
45 #[serde(skip)]
46 manifest: Entry,
47 #[serde(skip)]
48 local_config: Entry,
49 #[serde(skip)]
50 binding: String,
51}
52pub struct Approval(Preview);
53impl Approval {
54 pub fn from_preview(preview: Preview) -> Result<Self> {
55 if bind(&preview)? != preview.binding {
56 return Err(Error::Invalid(
57 "tool declaration preview was modified".into(),
58 ));
59 }
60 Ok(Self(preview))
61 }
62}
63fn bind(p: &Preview) -> Result<String> {
64 Ok(journal::digest(
65 journal::encode(&(p, &p.host, &p.manifest, &p.local_config))?.as_bytes(),
66 ))
67}
68fn parse(bytes: &[u8]) -> Result<Manifest> {
69 let text =
70 std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
71 Manifest::parse(text).map_err(|_| Error::Invalid("invalid manifest (content withheld)".into()))
72}
73fn entry(path: &Path) -> Result<Entry> {
74 let mut e = observation::inspect(path, false)?;
75 let fp = e.fingerprint.as_ref().filter(|f| e.kind == Kind::Regular && f.links == 1 && f.uid == rustix::process::geteuid().as_raw() && f.mode & 0o7000 == 0).ok_or_else(|| Error::Invalid("manifest must be an owned single-link regular file without special permission bits".into()))?;
76 let handle = observation::parent_handle(path)?;
77 let bytes = observation::read_checked(&handle, path, fp)?;
78 e.sha256 = Some(journal::digest(&bytes));
79 Ok(e)
80}
81fn clear_positions(table: &mut toml_edit::Table) {
82 table.set_position(None);
83 for (_, item) in table.iter_mut() {
84 match item {
85 toml_edit::Item::Table(t) => clear_positions(t),
86 toml_edit::Item::ArrayOfTables(a) => {
87 for t in a.iter_mut() {
88 clear_positions(t);
89 }
90 }
91 _ => (),
92 }
93 }
94}
95fn edit(
98 bytes: &[u8],
99 tool: &Tool,
100 host: &HostContext,
101 profiles: &[String],
102 repository: &Path,
103 change: Option<Change>,
104) -> Result<Option<Vec<u8>>> {
105 if journal::encode(tool)?.len() > 32 * 1024 {
106 return Err(Error::Invalid("tool declaration exceeds 32 KiB".into()));
107 }
108 let mut expected = parse(bytes)?;
109 let index = expected.tools.iter().position(|t| t.id == tool.id);
110 match (change, index) {
111 (Some(Change::Remove), Some(i)) => {
112 expected.tools.remove(i);
113 }
114 (Some(Change::Edit), Some(i)) => {
115 if journal::encode(&expected.tools[i])? == journal::encode(tool)? {
116 return Ok(None);
117 }
118 expected.tools[i] = tool.clone();
119 }
120 (Some(_), None) => return Err(Error::Invalid("tool declaration not found".into())),
121 (None, Some(i)) => {
122 if journal::encode(&expected.tools[i])? == journal::encode(tool)? {
123 return Ok(None);
124 }
125 return Err(Error::Invalid(
126 "tool ID already has a different declaration; use edit".into(),
127 ));
128 }
129 (None, None) => {
130 if expected.tools.len() >= MAX_TOOLS {
131 return Err(Error::Invalid("tool declaration limit".into()));
132 }
133 expected.tools.push(tool.clone());
134 }
135 }
136 expected.validate_for_host(host, profiles, Some(repository))?;
139 #[derive(Serialize)]
140 struct Addition<'a> {
141 tools: [&'a Tool; 1],
142 }
143 let addition = toml::to_string(&Addition { tools: [tool] })
144 .map_err(|_| Error::Invalid("cannot encode tool declaration".into()))?;
145 let added = addition
146 .parse::<toml_edit::DocumentMut>()
147 .map_err(|_| Error::Invalid("cannot encode tool tables".into()))?;
148 let mut tables = added["tools"]
149 .as_array_of_tables()
150 .ok_or_else(|| Error::Invalid("missing tool table".into()))?
151 .clone();
152 for t in tables.iter_mut() {
153 clear_positions(t);
154 }
155 let text =
156 std::str::from_utf8(bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
157 let mut doc = text
158 .parse::<toml_edit::DocumentMut>()
159 .map_err(|_| Error::Invalid("cannot edit manifest (content withheld)".into()))?;
160 if let Some(i) = index.filter(|_| change.is_some()) {
161 if let Some(a) = doc["tools"].as_array_of_tables_mut() {
162 if change == Some(Change::Remove) {
163 a.remove(i);
164 } else {
165 let mut replacement = tables
166 .get(0)
167 .ok_or_else(|| Error::Invalid("missing tool declaration table".into()))?
168 .clone();
169 replacement.set_position(
170 a.get(i)
171 .ok_or_else(|| Error::Invalid("missing tool table at index".into()))?
172 .position(),
173 );
174 let slot = a
175 .get_mut(i)
176 .ok_or_else(|| Error::Invalid("missing tool table at index".into()))?;
177 *slot = replacement;
178 }
179 } else if let Some(a) = doc["tools"].as_array_mut() {
180 if change == Some(Change::Remove) {
181 a.remove(i);
182 } else {
183 a.replace(
184 i,
185 tables
186 .get(0)
187 .ok_or_else(|| Error::Invalid("missing tool declaration table".into()))?
188 .clone()
189 .into_inline_table(),
190 );
191 }
192 } else {
193 return Err(Error::Invalid(
194 "unsupported manifest tools representation".into(),
195 ));
196 }
197 } else if doc.get("tools").is_none() {
198 doc["tools"] = toml_edit::Item::ArrayOfTables(tables);
199 } else if let Some(a) = doc["tools"].as_array_of_tables_mut() {
200 for t in &tables {
201 a.push(t.clone());
202 }
203 } else if let Some(a) = doc["tools"].as_array_mut() {
204 for t in &tables {
205 a.push(t.clone().into_inline_table());
206 }
207 } else {
208 return Err(Error::Invalid(
209 "unsupported manifest tools representation".into(),
210 ));
211 }
212 let result = doc.to_string().into_bytes();
213 if result.len() as u64 > journal::LIMIT
214 || journal::encode(&parse(&result)?)? != journal::encode(&expected)?
215 {
216 return Err(Error::Invalid(
217 "tool edit changed unrelated declarations or exceeded manifest limit".into(),
218 ));
219 }
220 Ok(Some(result))
221}
222pub fn preview(
224 host: &HostContext,
225 repository: &Path,
226 profiles: &[String],
227 tool: Tool,
228) -> Result<Preview> {
229 prepare(host, repository, profiles, tool, None)
230}
231pub fn preview_edit(
233 host: &HostContext,
234 repository: &Path,
235 profiles: &[String],
236 tool: Tool,
237) -> Result<Preview> {
238 prepare(host, repository, profiles, tool, Some(Change::Edit))
239}
240pub fn preview_remove(
242 host: &HostContext,
243 repository: &Path,
244 profiles: &[String],
245 id: &str,
246) -> Result<Preview> {
247 crate::context::validate_absolute(repository)?;
248 observation::validate_output_path(repository)?;
249 if !LocalConfig::load(host)?
250 .repositories
251 .values()
252 .any(|r| r.root == repository)
253 {
254 return Err(Error::Invalid(
255 "tool declarations require an already registered repository".into(),
256 ));
257 }
258 let manifest = entry(&repository.join("dort.toml"))?;
259 let tool = parse(&checked_bytes(&manifest)?)?
260 .tools
261 .into_iter()
262 .find(|t| t.id == id)
263 .ok_or_else(|| Error::Invalid("tool declaration not found".into()))?;
264 prepare(host, repository, profiles, tool, Some(Change::Remove))
265}
266fn prepare(
267 host: &HostContext,
268 repository: &Path,
269 profiles: &[String],
270 tool: Tool,
271 change: Option<Change>,
272) -> Result<Preview> {
273 crate::context::validate_absolute(repository)?;
274 observation::validate_output_path(repository)?;
275 let local = LocalConfig::load(host)?;
276 let repository_id = local
277 .repositories
278 .iter()
279 .find(|(_, r)| r.root == repository)
280 .map(|(id, _)| id.clone())
281 .ok_or_else(|| {
282 Error::Invalid("tool declarations require an already registered repository".into())
283 })?;
284 let manifest = entry(&repository.join("dort.toml"))?;
285 let bytes = checked_bytes(&manifest)?;
286 let before = change.and_then(|_| {
287 parse(&bytes)
288 .ok()?
289 .tools
290 .into_iter()
291 .find(|t| t.id == tool.id)
292 });
293 if change == Some(Change::Remove)
294 && before.as_ref().map(journal::encode).transpose()? != Some(journal::encode(&tool)?)
295 {
296 return Err(Error::Invalid(
297 "declaration changed during preparation; review again".into(),
298 ));
299 }
300 let no_op = edit(&bytes, &tool, host, profiles, repository, change)?.is_none();
301 let local_config = observation::inspect(&host.local_config_path(), false)?;
302 let mut p = Preview {
303 schema: if change.is_some() { 2 } else { 1 },
304 preview_only: true,
305 repository: repository.to_owned(),
306 repository_id,
307 tool,
308 change,
309 before,
310 profiles: profiles.to_vec(),
311 no_op,
312 effects: if no_op {
313 vec![]
314 } else {
315 vec![manifest.path.clone()]
316 },
317 host: host.clone(),
318 manifest,
319 local_config,
320 binding: String::new(),
321 };
322 p.binding = bind(&p)?;
323 Ok(p)
324}
325fn notify(
326 j: &Journal,
327 boundary: Boundary,
328 observer: &mut impl FnMut(&Event) -> Result<()>,
329) -> Result<()> {
330 observer(&Event {
331 transaction_id: j.record.header.transaction_id.clone(),
332 boundary,
333 sequence: j.record.sequence,
334 })
335}
336fn checkpoint(j: &mut Journal, observer: &mut impl FnMut(&Event) -> Result<()>) -> Result<()> {
337 j.save()?;
338 notify(j, Boundary::Checkpoint, observer)
339}
340fn stage_path(j: &Journal) -> PathBuf {
341 j.directory.path.join("op-0000")
342}
343fn check_parents(j: &Journal, e: &Entry) -> Result<()> {
344 if e.parents.iter().any(|p| {
345 j.record
346 .header
347 .anchors
348 .iter()
349 .find(|a| a.path == p.path)
350 .is_none_or(|a| !parent_identity(&a.fingerprint, &p.fingerprint))
351 }) {
352 return Err(Error::Invalid(
353 "declaration parent identity/permissions changed".into(),
354 ));
355 }
356 Ok(())
357}
358fn applied(j: &Journal) -> Result<bool> {
359 let h = &j.record.header;
360 let op = j
361 .record
362 .operation
363 .as_ref()
364 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?;
365 let live = entry(&h.manifest.path)?;
366 check_parents(j, &live)?;
367 let stage = entry(&stage_path(j))?;
368 let strict = op.progress == Progress::Pending;
369 let before = same(&h.manifest, &live, strict) && same(&op.staged, &stage, strict);
370 let after = same(&op.staged, &live, false) && same(&h.manifest, &stage, false);
371 match op.progress {
372 Progress::Pending if before => Ok(false),
373 Progress::Intent | Progress::UndoIntent if before => Ok(false),
374 Progress::Intent | Progress::UndoIntent if after => Ok(true),
375 Progress::Done if after && op.after.as_ref().is_some_and(|e| same(e, &live, true)) => {
376 Ok(true)
377 }
378 Progress::Undone if before => Ok(false),
379 _ => Err(Error::Invalid(
380 "manifest/stage changed; declaration recovery refused".into(),
381 )),
382 }
383}
384fn validate_scope(host: &HostContext, j: &Journal) -> Result<()> {
385 let h = &j.record.header;
386 journal::registered_root(host, &h.repository_id, &h.repository)?;
387 if h.local_config.path != host.local_config_path()
388 || h.manifest.path != h.repository.join("dort.toml")
389 {
390 return Err(Error::Invalid("declaration scope mismatch".into()));
391 }
392 if j.record.operation.is_none() {
393 return Ok(());
394 }
395 j.verify_backup()?;
396 let bytes = journal::read_bytes(&j.directory, "manifest.backup")?;
397 if edit(&bytes, &h.tool, host, &h.profiles, &h.repository, h.change)?
398 .as_ref()
399 .map(|b| journal::digest(b))
400 .as_ref()
401 != Some(&h.new_manifest_sha256)
402 {
403 return Err(Error::Invalid("declaration edit binding mismatch".into()));
404 }
405 Ok(())
406}
407fn validate_layout(host: &HostContext, j: &Journal) -> Result<()> {
408 journal::registered_root(
409 host,
410 &j.record.header.repository_id,
411 &j.record.header.repository,
412 )?;
413 j.verify_backup()?;
414 let config = observation::inspect(&host.local_config_path(), false)?;
415 if !same(&j.record.header.local_config, &config, true) {
416 return Err(Error::Invalid(
417 "local configuration changed since declaration approval".into(),
418 ));
419 }
420 check_parents(j, &config)?;
421 applied(j)?;
422 Ok(())
423}
424fn mutate(j: &Journal, undo: bool) -> Result<()> {
425 let path = &j.record.header.manifest.path;
426 let handle = observation::parent_handle(path)?;
427 let current = entry(path)?;
428 check_parents(j, ¤t)?;
429 if handle.missing
430 || handle.parents.len() != current.parents.len()
431 || handle
432 .parents
433 .iter()
434 .zip(¤t.parents)
435 .any(|(a, b)| a.path != b.path || !parent_identity(&a.fingerprint, &b.fingerprint))
436 || applied(j)? != undo
437 {
438 return Err(Error::Invalid(
439 "declaration mutation precondition changed".into(),
440 ));
441 }
442 fs::renameat_with(
443 &j.directory.file,
444 "op-0000",
445 &handle.directory,
446 &handle.name,
447 RenameFlags::EXCHANGE,
448 )
449 .map_err(|e| {
450 io_error(
451 "exchange declaration manifest (no unsafe fallback)",
452 path,
453 e,
454 )
455 })?;
456 handle
457 .directory
458 .sync_all()
459 .map_err(|e| io_error("sync declaration parent", path, e))?;
460 j.directory.sync()
461}
462pub fn execute(
463 host: &HostContext,
464 lock: &WriterLock,
465 approval: Approval,
466 mut observer: impl FnMut(&Event) -> Result<()>,
467) -> Result<Option<String>> {
468 lock.check_context(host)?;
469 journal::ensure_writable(host)?;
470 let old = approval.0;
471 if journal::encode(host)? != journal::encode(&old.host)? {
472 return Err(Error::Invalid(
473 "declaration approval belongs to another host".into(),
474 ));
475 }
476 let fresh = prepare(
477 host,
478 &old.repository,
479 &old.profiles,
480 old.tool.clone(),
481 old.change,
482 )?;
483 if old.binding != fresh.binding {
484 return Err(Error::Invalid(
485 "stale declaration preview; inspect and approve again".into(),
486 ));
487 }
488 if fresh.no_op {
489 return Ok(None);
490 }
491 let bytes = checked_bytes(&fresh.manifest)?;
492 let edited = edit(
493 &bytes,
494 &fresh.tool,
495 host,
496 &fresh.profiles,
497 &fresh.repository,
498 fresh.change,
499 )?
500 .ok_or_else(|| Error::Invalid("declaration unexpectedly became no-op".into()))?;
501 let h = Header {
502 repository_id: fresh.repository_id,
503 repository: fresh.repository,
504 transaction_id: adoption::transaction_id(),
505 approved_plan_sha256: old.binding,
506 tool: fresh.tool,
507 change: fresh.change,
508 profiles: fresh.profiles,
509 anchors: anchors(&[&fresh.manifest, &fresh.local_config]),
510 manifest: fresh.manifest,
511 local_config: fresh.local_config,
512 new_manifest_sha256: journal::digest(&edited),
513 };
514 let mut j = Journal::begin(host, h)?;
515 notify(&j, Boundary::Checkpoint, &mut observer)?;
516 j.directory.create("manifest.backup", &bytes)?;
517 j.verify_backup()?;
518 let fp = j
519 .record
520 .header
521 .manifest
522 .fingerprint
523 .as_ref()
524 .ok_or_else(|| Error::Invalid("missing manifest fingerprint".into()))?;
525 let device = fs::fstat(&j.directory.file)
526 .map_err(|e| io_error("inspect declaration filesystem", &j.directory.path, e))?
527 .st_dev;
528 if fp.device != device as u64
529 || j.record.header.manifest.parents.last().is_none_or(|p| {
530 p.fingerprint.device != fp.device
531 || p.fingerprint.uid != rustix::process::geteuid().as_raw()
532 })
533 {
534 return Err(Error::Invalid(
535 "declaration requires owned parent and same filesystem; no cross-device fallback"
536 .into(),
537 ));
538 }
539 j.directory.create("op-0000", &edited)?;
540 let file = File::from(
541 fs::openat(
542 &j.directory.file,
543 "op-0000",
544 OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
545 Mode::empty(),
546 )
547 .map_err(|e| io_error("open prepared declaration", &j.directory.path, e))?,
548 );
549 fs::fchown(&file, None, Some(rustix::process::Gid::from_raw(fp.gid)))
550 .map_err(|e| io_error("preserve manifest group", &j.directory.path, e))?;
551 fs::fchmod(&file, Mode::from_bits_truncate((fp.mode & 0o777) as _))
552 .map_err(|e| io_error("preserve manifest permissions", &j.directory.path, e))?;
553 file.sync_all()
554 .map_err(|e| io_error("sync prepared declaration", &j.directory.path, e))?;
555 j.directory.sync()?;
556 j.record.operation = Some(Operation {
557 staged: entry(&stage_path(&j))?,
558 after: None,
559 progress: Progress::Pending,
560 });
561 j.record.phase = Phase::Running;
562 checkpoint(&mut j, &mut observer)?;
563 validate_scope(host, &j)?;
564 validate_layout(host, &j)?;
565 j.record
566 .operation
567 .as_mut()
568 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
569 .progress = Progress::Intent;
570 checkpoint(&mut j, &mut observer)?;
571 validate_layout(host, &j)?;
572 mutate(&j, false)?;
573 notify(&j, Boundary::Mutation, &mut observer)?;
574 let after = entry(&j.record.header.manifest.path)?;
575 let staged = &j
576 .record
577 .operation
578 .as_ref()
579 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
580 .staged;
581 if !same(staged, &after, false) {
582 return Err(Error::Invalid("declaration postcondition mismatch".into()));
583 }
584 let op = j
585 .record
586 .operation
587 .as_mut()
588 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?;
589 op.after = Some(after);
590 op.progress = Progress::Done;
591 checkpoint(&mut j, &mut observer)?;
592 j.record.phase = Phase::Verifying;
593 checkpoint(&mut j, &mut observer)?;
594 validate_layout(host, &j)?;
595 j.record.phase = Phase::Completed;
596 checkpoint(&mut j, &mut observer)?;
597 Ok(Some(j.record.header.transaction_id))
598}
599pub(crate) fn rollback_preview(
600 host: &HostContext,
601 repository: &str,
602 tx: &str,
603) -> Result<(String, Vec<PathBuf>)> {
604 let j = Journal::open(host, repository, tx)?;
605 validate_scope(host, &j)?;
606 let effects = if matches!(j.record.phase, Phase::Preparing | Phase::RolledBack) {
607 vec![]
608 } else {
609 validate_layout(host, &j)?;
610 vec![j.record.header.manifest.path.clone()]
611 };
612 Ok((
613 journal::digest(journal::encode(&j.record)?.as_bytes()),
614 effects,
615 ))
616}
617pub(crate) fn rollback(
618 host: &HostContext,
619 lock: &WriterLock,
620 repository: &str,
621 tx: &str,
622 mut observer: impl FnMut(&Event) -> Result<()>,
623) -> Result<()> {
624 lock.check_context(host)?;
625 let mut j = Journal::open(host, repository, tx)?;
626 validate_scope(host, &j)?;
627 if j.record.phase == Phase::RolledBack {
628 return Ok(());
629 }
630 if j.record.phase == Phase::Preparing {
631 j.record.phase = Phase::RolledBack;
632 return checkpoint(&mut j, &mut observer);
633 }
634 validate_layout(host, &j)?;
635 if j.record.phase != Phase::RollingBack {
636 j.record.phase = Phase::RollingBack;
637 checkpoint(&mut j, &mut observer)?;
638 }
639 if j.record
640 .operation
641 .as_ref()
642 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
643 .progress
644 != Progress::Undone
645 {
646 let was_applied = applied(&j)?;
647 j.record
648 .operation
649 .as_mut()
650 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
651 .progress = Progress::UndoIntent;
652 checkpoint(&mut j, &mut observer)?;
653 validate_layout(host, &j)?;
654 if was_applied {
655 mutate(&j, true)?;
656 notify(&j, Boundary::Mutation, &mut observer)?;
657 }
658 j.record
659 .operation
660 .as_mut()
661 .ok_or_else(|| Error::Invalid("missing declaration operation".into()))?
662 .progress = Progress::Undone;
663 checkpoint(&mut j, &mut observer)?;
664 }
665 validate_layout(host, &j)?;
666 j.record.phase = Phase::RolledBack;
667 checkpoint(&mut j, &mut observer)
668}