Skip to main content

stratum_node_cli/
app.rs

1//! `stratum app …`: a member's applications, through the gate. The
2//! catalogue, installing with the ACL preview, conditional writes and
3//! read-back, the installation reads, manual runs, withdrawal with its ACL
4//! cleanup, and resume after a restore.
5
6use std::collections::HashMap;
7use std::fmt::Write as _;
8
9use serde::de::DeserializeOwned;
10use serde_json::{json, Value as Json};
11use stratum_node_core::{
12    check_schedule_secs, render_offered, ApplicationId, Catalogue, CatalogueEntry, CleanupRequest,
13    CleanupResponse, ConsentRequest, ConsentResponse, ContainerPath, CreateInstallationRequest,
14    CreateInstallationResponse, DidNostr, GrantState, InstallationActionRequest, InstallationId,
15    InstallationList, InstallationState, InstallationView, JobList, NostrSecretKey, OfferedGrant,
16    PodPath, ResumeInstallationResponse, RunRequest, RunResponse, WithdrawResponse, WorkspaceMode,
17};
18
19use crate::acl::{self, AclDocument, Authorisation, Governing};
20use crate::client::MAX_RESPONSE_BYTES;
21use crate::error::CliError;
22use crate::exit;
23use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
24use crate::origin::GateTarget;
25use crate::output::sanitize;
26use crate::session::{operation_id, to_body, Confirmation, Session};
27
28/// `GET` route: the catalogue of approved applications.
29const CATALOGUE: &str = "/api/v1/catalogue";
30/// The installations route; each installation is `INSTALLATIONS/<id>`.
31const INSTALLATIONS: &str = "/api/v1/installations";
32/// The media type an ACL is written with.
33const TURTLE: &str = "text/turtle";
34/// The largest ACL read.
35const MAX_ACL_BYTES: u64 = 1024 * 1024;
36/// How many times one container's write starts again from its read, after
37/// the governing ACL changed or a conditional write lost a race.
38pub(crate) const MAX_ACL_ATTEMPTS: u32 = 5;
39
40/// The statement `app install` prints before it asks (ADR D12, contract
41/// "The client previews").
42///
43/// # Examples
44///
45/// ```
46/// assert!(stratum_node_cli::OPERATOR_STATEMENT.contains("root on the host"));
47/// ```
48pub const OPERATOR_STATEMENT: &str = "The node's operator has root on the host: they can read \
49     workspaces, the tenant daemon's data (where this application's containers run) and backups, \
50     which hold your pod. Stratum states this; it does not prevent it.";
51
52/// Options for [`Session::app_install`].
53///
54/// # Examples
55///
56/// ```
57/// use stratum_node_cli::{Confirmation, InstallOptions};
58/// use stratum_node_core::WorkspaceMode;
59///
60/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
61/// // `stratum app install <application> --schedule 3600 --yes`
62/// let options = InstallOptions {
63///     application: "0123456789abcdef0123456789abcdef".parse()?,
64///     schedule_secs: 3600,
65///     workspace: WorkspaceMode::None,
66///     operation_id: None,
67///     confirmation: Confirmation::Assumed,
68/// };
69/// assert_eq!(options.schedule_secs, 3600);
70/// # Ok(())
71/// # }
72/// ```
73#[derive(Debug, Clone)]
74pub struct InstallOptions {
75    /// The application to install, as the catalogue lists it.
76    pub application: ApplicationId,
77    /// The schedule interval in seconds: 0 for manual runs only, otherwise
78    /// 300 to 604800.
79    pub schedule_secs: u64,
80    /// The workspace asked for; no more than the manifest allows. Every mode
81    /// other than `none` is refused by a node without workspace slots.
82    pub workspace: WorkspaceMode,
83    /// The operation ID of the create request; random when `None`. Pass the
84    /// one a previous run printed, with the same application, schedule and
85    /// workspace, to continue that installation rather than create another.
86    pub operation_id: Option<String>,
87    /// Whether to ask before writing the grant.
88    pub confirmation: Confirmation,
89}
90
91/// One container of an install: what governs it now and the ACL the client
92/// would write.
93#[derive(Debug, Clone)]
94struct Planned {
95    /// The granted container.
96    container: PodPath,
97    /// Its ACL.
98    acl: PodPath,
99    /// What governs the container now.
100    fingerprint: Fingerprint,
101    /// The container's own ACL, byte for byte, if it has one.
102    previous: Option<Vec<u8>>,
103    /// The new ACL's statements.
104    document: AclDocument,
105    /// The new ACL's text.
106    text: String,
107}
108
109/// Which ACL governs a container, and its entity tag: what the reread
110/// before a write compares.
111#[derive(Debug, Clone, PartialEq, Eq)]
112enum Fingerprint {
113    /// The container's own ACL.
114    Own(String),
115    /// An ancestor's ACL.
116    Inherited(PodPath, String),
117    /// A planned ancestor ACL of this install, not yet written.
118    Planned(PodPath),
119    /// No ACL.
120    Nothing,
121}
122
123/// An ACL this run wrote, kept so it can be removed again.
124#[derive(Debug, Clone)]
125struct Written {
126    /// The ACL path.
127    acl: PodPath,
128    /// The container's own ACL before the write, or `None` if the client
129    /// created it.
130    previous: Option<Vec<u8>>,
131    /// The entity tag read back after the write.
132    etag: String,
133}
134
135/// The result of a conditional `PUT`.
136enum Put {
137    /// Written.
138    Done,
139    /// 412: the condition did not hold.
140    Lost,
141}
142
143/// A tenant's context for one command: the gate, the key and its DID.
144struct Tenant<'a> {
145    session: &'a Session,
146    gate: GateClient,
147    key: NostrSecretKey,
148    owner: DidNostr,
149}
150
151impl Session {
152    /// `stratum app catalogue`: lists the applications this node has
153    /// approved, each with its manifest's name, version, image ID, granted
154    /// containers and the most workspace it may be given. Signed.
155    ///
156    /// # Errors
157    ///
158    /// Key, transport, protocol and server errors (`suspended` while the
159    /// membership is suspended).
160    pub fn app_catalogue(&self, target: &GateTarget) -> Result<u8, CliError> {
161        self.with_tenant(target, |tenant| {
162            let (catalogue, raw): (Catalogue, Json) = tenant.get(CATALOGUE)?;
163            self.output().json(&raw)?;
164            if catalogue.applications.is_empty() {
165                self.output()
166                    .line("no applications are approved on this node")?;
167            }
168            for entry in &catalogue.applications {
169                for line in describe_entry(entry) {
170                    self.output().line(&line)?;
171                }
172            }
173            Ok(exit::OK)
174        })
175    }
176
177    /// `stratum app install <application> [--schedule <secs>] [--workspace
178    /// none|read|write] [--yes]`: installs an application in the caller's
179    /// pod. Signed.
180    ///
181    /// 1. Reads the catalogue entry, and creates the installation
182    ///    (`pending_consent`), which gives the application's key and the
183    ///    offered grant.
184    /// 2. Renders the grant again from the manifest with
185    ///    [`render_offered`] and refuses unless every byte and hash matches
186    ///    the offer.
187    /// 3. For each granted container, reads the ACL that governs it now
188    ///    (its own, or the nearest ancestor's) and builds its new ACL: the
189    ///    owner's control, every rule of its own ACL unchanged, inherited
190    ///    `acl:default` rules materialised, `acl:accessTo`-only ones not
191    ///    copied, and the offered rule. A statement the client does not
192    ///    evaluate is refused, and the application is never given
193    ///    `Control`.
194    /// 4. Prints the diff of each ACL, the owner, the application, its
195    ///    version and image ID and [`OPERATOR_STATEMENT`], and asks.
196    /// 5. For each container: checks the installation is still
197    ///    `pending_consent`, rereads the governing ACL and starts again if
198    ///    its entity tag changed, writes with `If-Match` (or
199    ///    `If-None-Match: *` when the container had no ACL), starts again on
200    ///    412, and reads the ACL back, comparing parsed statements.
201    /// 6. Sends consent only if every read-back matched. On a mismatch, a
202    ///    refused consent or an installation that is no longer
203    ///    `pending_consent`, removes what it wrote.
204    ///
205    /// The operation ID of the create request is printed first; declining
206    /// leaves the installation `pending_consent` with nothing written.
207    ///
208    /// # Errors
209    ///
210    /// [`CliError::Usage`] for a schedule out of range, a workspace above
211    /// the manifest's or an application not in the catalogue;
212    /// [`CliError::NotConfirmed`]; [`CliError::Refused`] for an offer that
213    /// is not the one the manifest renders, or an ACL that would give the
214    /// application `Control`; [`CliError::AclNotEvaluated`];
215    /// [`CliError::ReadBackMismatch`]; [`CliError::ConsentRefused`]; and
216    /// key, transport, protocol and server errors (`workspace_unavailable`,
217    /// `application_unavailable`, `precondition_failed` when a container
218    /// kept changing).
219    pub fn app_install(
220        &self,
221        target: &GateTarget,
222        options: &InstallOptions,
223    ) -> Result<u8, CliError> {
224        check_schedule_secs(options.schedule_secs).map_err(|_| {
225            CliError::Usage(
226                "--schedule must be 0 (manual runs only) or 300 to 604800 seconds".to_owned(),
227            )
228        })?;
229        let operation = operation_id(options.operation_id.as_deref())?;
230        self.with_tenant(target, |tenant| tenant.install(options, &operation))
231    }
232
233    /// `stratum app list`: lists the caller's installations with their
234    /// state, grant and job counts, and any ACL cleanup still pending.
235    /// Signed.
236    ///
237    /// # Errors
238    ///
239    /// Key, transport, protocol and server errors.
240    pub fn app_list(&self, target: &GateTarget) -> Result<u8, CliError> {
241        self.with_tenant(target, |tenant| {
242            let (list, raw): (InstallationList, Json) = tenant.get(INSTALLATIONS)?;
243            for view in &list.installations {
244                if view.owner != tenant.owner {
245                    return Err(CliError::Refused(format!(
246                        "the node listed installation {} of {} among yours",
247                        view.installation, view.owner
248                    )));
249                }
250            }
251            self.output().json(&raw)?;
252            if list.installations.is_empty() {
253                self.output().line("no installations")?;
254            }
255            for view in &list.installations {
256                self.output().line(&summary_line(view))?;
257            }
258            Ok(exit::OK)
259        })
260    }
261
262    /// `stratum app show <installation>`: prints one installation: state,
263    /// application and key, schedule, workspace, key-disable reasons, grant
264    /// and pending cleanup, the enforcement parts while a withdrawal or
265    /// suspension is being enforced, and job counts. Signed.
266    ///
267    /// # Errors
268    ///
269    /// [`CliError::Refused`] for an answer naming another installation or
270    /// owner, and key, transport, protocol and server errors.
271    pub fn app_show(
272        &self,
273        target: &GateTarget,
274        installation: &InstallationId,
275    ) -> Result<u8, CliError> {
276        self.with_tenant(target, |tenant| {
277            let (view, raw) = tenant.installation(installation)?;
278            self.output().json(&raw)?;
279            for line in describe_view(&view) {
280                self.output().line(&line)?;
281            }
282            Ok(exit::OK)
283        })
284    }
285
286    /// `stratum app jobs <installation>`: lists the installation's jobs:
287    /// period, state, attempts, outcome and the result the job reported.
288    /// Signed.
289    ///
290    /// # Errors
291    ///
292    /// Key, transport, protocol and server errors.
293    pub fn app_jobs(
294        &self,
295        target: &GateTarget,
296        installation: &InstallationId,
297    ) -> Result<u8, CliError> {
298        self.with_tenant(target, |tenant| {
299            let path = format!("{INSTALLATIONS}/{installation}/jobs");
300            let (jobs, raw): (JobList, Json) = tenant.get(&path)?;
301            if jobs.installation != *installation {
302                return Err(CliError::Refused(format!(
303                    "asked for the jobs of {installation}, the node answered with {}",
304                    jobs.installation
305                )));
306            }
307            self.output().json(&raw)?;
308            if jobs.jobs.is_empty() {
309                self.output().line("no jobs")?;
310            }
311            for job in &jobs.jobs {
312                let mut line = format!(
313                    "period {}  {}  job {}  attempts {}",
314                    job.period, job.state, job.job, job.attempts
315                );
316                if let Some(outcome) = job.outcome {
317                    let _ = write!(line, "  outcome {outcome}");
318                }
319                if let Some(resource) = &job.resource {
320                    let _ = write!(line, "  resource {}", sanitize(resource));
321                }
322                if let Some(sha256) = &job.sha256 {
323                    let _ = write!(line, "  sha256 {sha256}");
324                }
325                if let Some(length) = job.length {
326                    let _ = write!(line, "  {length} bytes");
327                }
328                if let Some(code) = job.exit_code {
329                    let _ = write!(line, "  exit {code}");
330                }
331                if let Some(at) = job.next_eligible_at {
332                    let _ = write!(line, "  next attempt after {at}");
333                }
334                self.output().line(&line)?;
335            }
336            Ok(exit::OK)
337        })
338    }
339
340    /// `stratum app run <installation> --period <n> [--yes]`: creates the
341    /// job for period `n` if none exists. Asks first. Signed. A period that
342    /// already has a job answers that job.
343    ///
344    /// # Errors
345    ///
346    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
347    /// errors.
348    pub fn app_run(
349        &self,
350        target: &GateTarget,
351        installation: &InstallationId,
352        period: u64,
353        operation_id_arg: Option<&str>,
354        confirmation: Confirmation,
355    ) -> Result<u8, CliError> {
356        let operation = operation_id(operation_id_arg)?;
357        self.with_tenant(target, |tenant| {
358            if !self.confirmed(
359                &format!("run period {period} of installation {installation} now?"),
360                confirmation,
361            )? {
362                return Err(CliError::NotConfirmed);
363            }
364            tenant.note_operation(&operation, "")?;
365            let body = to_body(&RunRequest {
366                operation_id: operation.clone(),
367                period,
368            })?;
369            let (answer, _raw): (RunResponse, Json) =
370                tenant.post(&format!("{INSTALLATIONS}/{installation}/run"), &body)?;
371            self.output().json(&json!({
372                "operation_id": operation.as_str(),
373                "installation": installation,
374                "period": period,
375                "job": answer.job,
376                "state": answer.state,
377            }))?;
378            self.output().line(&format!(
379                "period {period}: job {} is {}",
380                answer.job, answer.state
381            ))?;
382            Ok(exit::OK)
383        })
384    }
385
386    /// `stratum app withdraw <installation> [--yes]`: withdraws the
387    /// installation, then removes its authorisation from every granted
388    /// container's ACL and reports the cleanup, as
389    /// [`app_cleanup`](Self::app_cleanup) does. Asks first. Signed.
390    ///
391    /// The node answers at once with `authorisation: enforcing`: its gate
392    /// and proxy refuse the key once they take the new revision, or within
393    /// 310 s. The ACL cleanup is the member's part: if it is interrupted,
394    /// every `stratum app` command shows it pending until
395    /// `stratum app cleanup` finishes it.
396    ///
397    /// # Errors
398    ///
399    /// [`CliError::NotConfirmed`]; [`CliError::CleanupPending`] (or
400    /// [`CliError::AclNotEvaluated`]) when a container's ACL could not be
401    /// cleaned; key, transport, protocol and server errors (`suspended`
402    /// while the membership is suspended).
403    pub fn app_withdraw(
404        &self,
405        target: &GateTarget,
406        installation: &InstallationId,
407        operation_id_arg: Option<&str>,
408        confirmation: Confirmation,
409    ) -> Result<u8, CliError> {
410        let operation = operation_id(operation_id_arg)?;
411        self.with_tenant(target, |tenant| {
412            let question = format!(
413                "withdraw installation {installation}? Its key is disabled and its jobs stop; \
414                 then its authorisation is removed from each granted container's ACL"
415            );
416            if !self.confirmed(&question, confirmation)? {
417                return Err(CliError::NotConfirmed);
418            }
419            tenant.note_operation(&operation, "")?;
420            let body = to_body(&InstallationActionRequest {
421                operation_id: operation.clone(),
422            })?;
423            let (answer, raw): (WithdrawResponse, Json) =
424                tenant.post(&format!("{INSTALLATIONS}/{installation}/withdraw"), &body)?;
425            if answer.state != InstallationState::Withdrawn {
426                return Err(CliError::Refused(format!(
427                    "the node reports installation {installation} as {} after withdraw",
428                    answer.state
429                )));
430            }
431            self.output().line(&format!(
432                "installation {installation}: withdrawn; authorisation {}",
433                answer.authorisation
434            ))?;
435            let (view, _raw) = tenant.installation(installation)?;
436            let report = tenant.cleanup(&view, &answer.cleanup_pending)?;
437            self.output().json(&json!({
438                "operation_id": operation.as_str(),
439                "installation": installation,
440                "withdraw": raw,
441                "cleanup": report.json(),
442            }))?;
443            report.finish(installation)
444        })
445    }
446
447    /// `stratum app cleanup <installation> [--yes]`: finishes a withdrawn
448    /// installation's ACL cleanup. Asks first. Signed.
449    ///
450    /// For each container the node lists as pending, the client reads its
451    /// ACL, removes only the installation's authorisation, writes the ACL
452    /// back with `If-Match` (starting again on 412), reads it back and
453    /// compares the parsed statements, and reports that container cleaned
454    /// at once, so an interruption keeps what was done. An ACL that no
455    /// longer holds the authorisation counts as clean. Nothing is kept on
456    /// this machine: the pending list is the node's.
457    ///
458    /// # Errors
459    ///
460    /// [`CliError::NotConfirmed`]; [`CliError::CleanupPending`] when a
461    /// container could not be cleaned, or [`CliError::AclNotEvaluated`]
462    /// when its ACL holds a statement the client does not evaluate; key,
463    /// transport, protocol and server errors.
464    pub fn app_cleanup(
465        &self,
466        target: &GateTarget,
467        installation: &InstallationId,
468        confirmation: Confirmation,
469    ) -> Result<u8, CliError> {
470        self.with_tenant(target, |tenant| {
471            let (view, _raw) = tenant.installation(installation)?;
472            if view.grant != GrantState::Withdrawn || view.cleanup_pending.is_empty() {
473                self.output().json(&json!({
474                    "installation": installation,
475                    "grant": view.grant,
476                    "cleanup_pending": [],
477                }))?;
478                self.output().line(&format!(
479                    "installation {installation}: no ACL cleanup is pending (grant {})",
480                    view.grant
481                ))?;
482                return Ok(exit::OK);
483            }
484            let question = format!(
485                "remove installation {installation}'s authorisation from {} container ACL(s)?",
486                view.cleanup_pending.len()
487            );
488            if !self.confirmed(&question, confirmation)? {
489                return Err(CliError::NotConfirmed);
490            }
491            let report = tenant.cleanup(&view, &view.cleanup_pending)?;
492            self.output().json(&json!({
493                "installation": installation,
494                "cleanup": report.json(),
495            }))?;
496            report.finish(installation)
497        })
498    }
499
500    /// `stratum app resume <installation> [--yes]`: after a restore, enables
501    /// the installation's key again by removing its `restore` reason. Asks
502    /// first. Signed. Only an `active` installation of an `active` member
503    /// can be resumed.
504    ///
505    /// # Errors
506    ///
507    /// [`CliError::NotConfirmed`], and key, transport, protocol and server
508    /// errors (`conflict` for an installation that cannot be resumed).
509    pub fn app_resume(
510        &self,
511        target: &GateTarget,
512        installation: &InstallationId,
513        operation_id_arg: Option<&str>,
514        confirmation: Confirmation,
515    ) -> Result<u8, CliError> {
516        let operation = operation_id(operation_id_arg)?;
517        self.with_tenant(target, |tenant| {
518            if !self.confirmed(
519                &format!("enable installation {installation}'s key again after the restore?"),
520                confirmation,
521            )? {
522                return Err(CliError::NotConfirmed);
523            }
524            tenant.note_operation(&operation, "")?;
525            let body = to_body(&InstallationActionRequest {
526                operation_id: operation.clone(),
527            })?;
528            let (answer, _raw): (ResumeInstallationResponse, Json) =
529                tenant.post(&format!("{INSTALLATIONS}/{installation}/resume"), &body)?;
530            self.output().json(&json!({
531                "operation_id": operation.as_str(),
532                "installation": installation,
533                "keys": answer.keys,
534            }))?;
535            self.output()
536                .line(&format!("installation {installation}: key {}", answer.keys))?;
537            Ok(exit::OK)
538        })
539    }
540
541    /// Runs `command` as the key's tenant, then shows every withdrawn grant
542    /// whose cleanup is not yet reported, whatever the command's outcome
543    /// (contract "Grant": every `stratum app` command shows it).
544    fn with_tenant(
545        &self,
546        target: &GateTarget,
547        command: impl FnOnce(&Tenant<'_>) -> Result<u8, CliError>,
548    ) -> Result<u8, CliError> {
549        let key = self.key()?;
550        let tenant = Tenant {
551            session: self,
552            gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
553            owner: key.public(),
554            key,
555        };
556        let result = command(&tenant);
557        tenant.show_pending_cleanup();
558        result
559    }
560}
561
562impl Tenant<'_> {
563    /// `GET path` on a tenant route, parsed as `T`.
564    fn get<T: DeserializeOwned>(&self, path: &str) -> Result<(T, Json), CliError> {
565        self.gate
566            .fetch(
567                &Request::new("GET", path, JSON),
568                Some(&self.key),
569                MAX_RESPONSE_BYTES,
570            )?
571            .into_json(Route::Admission)
572    }
573
574    /// `POST path` with a JSON body on a tenant route, parsed as `T`.
575    fn post<T: DeserializeOwned>(&self, path: &str, body: &[u8]) -> Result<(T, Json), CliError> {
576        self.gate
577            .fetch(
578                &Request::new("POST", path, JSON).with_body(body, JSON),
579                Some(&self.key),
580                MAX_RESPONSE_BYTES,
581            )?
582            .into_json(Route::Admission)
583    }
584
585    /// Notes the operation ID before a `POST`, for a retry.
586    fn note_operation(
587        &self,
588        operation: &stratum_node_core::OperationId,
589        flags: &str,
590    ) -> Result<(), CliError> {
591        self.session.output().note(&format!(
592            "operation id: {operation} (to retry after a lost response, pass --operation-id \
593             {operation}{flags}: the retry must send the same request)"
594        ))
595    }
596
597    /// `GET /api/v1/installations/<id>`, checked to name `installation` and
598    /// this owner.
599    fn installation(
600        &self,
601        installation: &InstallationId,
602    ) -> Result<(InstallationView, Json), CliError> {
603        let (view, raw): (InstallationView, Json) =
604            self.get(&format!("{INSTALLATIONS}/{installation}"))?;
605        if view.installation != *installation || view.owner != self.owner {
606            return Err(CliError::Refused(format!(
607                "asked for installation {installation} of {}, the node answered with {} of {}",
608                self.owner, view.installation, view.owner
609            )));
610        }
611        Ok((view, raw))
612    }
613
614    /// Notes every withdrawn grant whose cleanup is not reported. Any
615    /// failure is ignored: while the owner is suspended the list is
616    /// refused, and the contract does not show it then.
617    fn show_pending_cleanup(&self) {
618        let Ok((list, _raw)) = self.get::<InstallationList>(INSTALLATIONS) else {
619            return;
620        };
621        for view in &list.installations {
622            if view.owner != self.owner
623                || view.grant != GrantState::Withdrawn
624                || view.cleanup_pending.is_empty()
625            {
626                continue;
627            }
628            let paths: Vec<&str> = view
629                .cleanup_pending
630                .iter()
631                .map(ContainerPath::as_str)
632                .collect();
633            // Nowhere useful to report a failed note.
634            let _noted = self.session.output().note(&format!(
635                "installation {} was withdrawn and its ACL cleanup is pending for {}: run \
636                 `stratum app cleanup {}`",
637                view.installation,
638                paths.join(", "),
639                view.installation
640            ));
641        }
642    }
643
644    /// Reads an ACL: `None` for 404, else its bytes and entity tag.
645    fn read_acl(&self, acl: &PodPath) -> Result<Option<(Vec<u8>, String)>, CliError> {
646        let response = self.gate.fetch(
647            &Request::new("GET", acl.as_str(), ANY),
648            Some(&self.key),
649            MAX_ACL_BYTES,
650        )?;
651        if response.head.status == 404 {
652            return Ok(None);
653        }
654        if !response.head.is_success() {
655            return Err(response.into_error(Route::Pod));
656        }
657        let Some(etag) = response.head.etag.clone() else {
658            return Err(CliError::Protocol(format!(
659                "{acl} was read without an entity tag, so it cannot be written conditionally"
660            )));
661        };
662        Ok(Some((response.body, etag)))
663    }
664
665    /// Writes `body` to `acl` under `precondition`.
666    fn put_acl(
667        &self,
668        acl: &PodPath,
669        body: &[u8],
670        precondition: Precondition<'_>,
671    ) -> Result<Put, CliError> {
672        let request = Request::new("PUT", acl.as_str(), ANY)
673            .with_body(body, TURTLE)
674            .with_precondition(precondition);
675        let response = self
676            .gate
677            .fetch(&request, Some(&self.key), MAX_RESPONSE_BYTES)?;
678        if response.head.status == 412 {
679            return Ok(Put::Lost);
680        }
681        if !response.head.is_success() {
682            return Err(response.into_error(Route::Pod));
683        }
684        Ok(Put::Done)
685    }
686
687    /// Parses an ACL read from `acl`.
688    fn parse(&self, acl: &PodPath, bytes: &[u8]) -> Result<AclDocument, CliError> {
689        let origin = self.gate.target().origin();
690        acl::parse(&origin.url(acl.as_str()), acl, &origin.as_str(), bytes)
691    }
692
693    /// Reads what governs `container`, nearest first: its own ACL, then each
694    /// ancestor's. An ancestor ACL this install has planned but not written
695    /// is taken from `planned`. Only a 404 moves up a level; any other
696    /// failure is an error, never a miss.
697    fn read_governing(
698        &self,
699        container: &PodPath,
700        planned: &HashMap<PodPath, AclDocument>,
701    ) -> Result<(Governing, Fingerprint, Option<Vec<u8>>), CliError> {
702        for candidate in acl::governing_candidates(container) {
703            let Some(acl) = candidate.acl_path() else {
704                continue;
705            };
706            let own = candidate == *container;
707            if !own {
708                if let Some(document) = planned.get(&acl) {
709                    return Ok((
710                        Governing::Inherited {
711                            acl: acl.clone(),
712                            document: document.clone(),
713                        },
714                        Fingerprint::Planned(acl),
715                        None,
716                    ));
717                }
718            }
719            let Some((bytes, etag)) = self.read_acl(&acl)? else {
720                continue;
721            };
722            let document = self.parse(&acl, &bytes)?;
723            return Ok(if own {
724                (
725                    Governing::Own(document),
726                    Fingerprint::Own(etag),
727                    Some(bytes),
728                )
729            } else {
730                (
731                    Governing::Inherited {
732                        acl: acl.clone(),
733                        document,
734                    },
735                    Fingerprint::Inherited(acl, etag),
736                    None,
737                )
738            });
739        }
740        Ok((Governing::Nothing, Fingerprint::Nothing, None))
741    }
742
743    /// Plans one container's ACL from what governs it now.
744    fn plan(
745        &self,
746        container: &PodPath,
747        app: &DidNostr,
748        offered_text: &str,
749        planned: &HashMap<PodPath, AclDocument>,
750    ) -> Result<Planned, CliError> {
751        let acl = container
752            .acl_path()
753            .ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
754        let url = self.gate.target().origin().url(acl.as_str());
755        let offered = self
756            .parse(&acl, offered_text.as_bytes())
757            .map_err(|_| {
758                CliError::Protocol(format!("the offered rule for {container} does not parse"))
759            })?
760            .authorisations;
761        let [offered] = <[Authorisation; 1]>::try_from(offered).map_err(|_| {
762            CliError::Protocol(format!(
763                "the offered rule for {container} is not exactly one authorisation"
764            ))
765        })?;
766        let (governing, fingerprint, previous) = self.read_governing(container, planned)?;
767        let document = acl::materialise(&acl::Materialise {
768            owner: &self.owner,
769            app,
770            container,
771            url: &url,
772            governing: &governing,
773            offered: &offered,
774        })?;
775        let text = acl::serialise(&document)?;
776        // The text must say exactly what was built.
777        let reparsed = self.parse(&acl, text.as_bytes())?;
778        if !reparsed.same_statements(&document) {
779            return Err(CliError::Local(format!(
780                "the ACL built for {container} does not parse back to its own statements"
781            )));
782        }
783        Ok(Planned {
784            container: container.clone(),
785            acl,
786            fingerprint,
787            previous,
788            document,
789            text,
790        })
791    }
792
793    /// The preview lines of one container.
794    fn describe_plan(planned: &Planned) -> Vec<String> {
795        let governed = match &planned.fingerprint {
796            Fingerprint::Own(_) => "governed now by its own ACL, which is kept".to_owned(),
797            Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => format!(
798                "governed now by {acl}: its rules that reach this container by acl:default are \
799                 copied into a new ACL, so every principal keeps exactly its access"
800            ),
801            Fingerprint::Nothing => "governed now by no ACL".to_owned(),
802        };
803        let old = planned
804            .previous
805            .as_deref()
806            .map(String::from_utf8_lossy)
807            .unwrap_or_default();
808        let mut lines = vec![
809            format!("container {} (ACL {})", planned.container, planned.acl),
810            format!("  {governed}"),
811        ];
812        lines.extend(
813            acl::diff(&old, &planned.text)
814                .into_iter()
815                .map(|line| format!("  {}", sanitize(&line))),
816        );
817        lines
818    }
819
820    /// `app install`, after the local checks.
821    #[expect(
822        clippy::too_many_lines,
823        reason = "the install sequence reads best as one ordered procedure"
824    )]
825    fn install(
826        &self,
827        options: &InstallOptions,
828        operation: &stratum_node_core::OperationId,
829    ) -> Result<u8, CliError> {
830        let output = self.session.output();
831        let (catalogue, _raw): (Catalogue, Json) = self.get(CATALOGUE)?;
832        let Some(entry) = catalogue
833            .applications
834            .into_iter()
835            .find(|entry| entry.application == options.application)
836        else {
837            return Err(CliError::Usage(format!(
838                "application {} is not in this node's catalogue: only approved applications can \
839                 be installed; `stratum app catalogue` lists them",
840                options.application
841            )));
842        };
843        let manifest = &entry.manifest;
844        if options.workspace > manifest.workspace {
845            return Err(CliError::Usage(format!(
846                "--workspace {} is more than application {} allows ({})",
847                options.workspace, options.application, manifest.workspace
848            )));
849        }
850        let schedule_flag = if options.schedule_secs == 0 {
851            String::new()
852        } else {
853            format!(" --schedule {}", options.schedule_secs)
854        };
855        let workspace_flag = if options.workspace == WorkspaceMode::None {
856            String::new()
857        } else {
858            format!(" --workspace {}", options.workspace)
859        };
860        self.note_operation(operation, &format!("{schedule_flag}{workspace_flag}"))?;
861        let body = to_body(&CreateInstallationRequest {
862            operation_id: operation.clone(),
863            application: options.application,
864            schedule_secs: options.schedule_secs,
865            workspace: options.workspace,
866        })?;
867        let (created, _raw): (CreateInstallationResponse, Json) =
868            self.post(INSTALLATIONS, &body)?;
869        let installation = created.installation;
870        if created.state != InstallationState::PendingConsent {
871            return Err(CliError::Refused(format!(
872                "the node reports installation {installation} as {}, not pending_consent",
873                created.state
874            )));
875        }
876        let app = created.app_did;
877        if app == self.owner {
878            return Err(CliError::Refused(
879                "the node offered your own key as the application key".to_owned(),
880            ));
881        }
882        let expected = render_offered(&app, &self.owner, &manifest.containers);
883        if created.grant != expected {
884            return Err(CliError::Refused(format!(
885                "the grant the node offered for installation {installation} is not the one the \
886                 manifest renders for key {app} (offered sha256 {}, rendered {})",
887                created.grant.sha256, expected.sha256
888            )));
889        }
890        let grant: OfferedGrant = created.grant;
891
892        // Plan every container before asking, in manifest order; a granted
893        // container nested in another sees that one's planned ACL.
894        let mut planned_documents: HashMap<PodPath, AclDocument> = HashMap::new();
895        let mut plans = Vec::with_capacity(grant.containers.len());
896        for offered in &grant.containers {
897            let container = offered.path.under(&self.owner);
898            let plan = self.plan(&container, &app, &offered.turtle, &planned_documents)?;
899            planned_documents.insert(plan.acl.clone(), plan.document.clone());
900            plans.push(plan);
901        }
902
903        let mut preview = vec![
904            format!("installation: {installation} (pending consent)"),
905            format!("owner: {}", self.owner),
906            format!(
907                "application: {} {} (version {})",
908                entry.application,
909                sanitize(&manifest.name),
910                sanitize(&manifest.version)
911            ),
912            format!("image: {}", manifest.image_id),
913            format!("application key: {app}"),
914            format!(
915                "schedule: {}",
916                if options.schedule_secs == 0 {
917                    "manual runs only".to_owned()
918                } else {
919                    format!("every {} s", options.schedule_secs)
920                }
921            ),
922            format!("workspace: {}", options.workspace),
923            format!("grant sha256: {}", grant.sha256),
924        ];
925        for plan in &plans {
926            preview.extend(Self::describe_plan(plan));
927        }
928        preview.push(OPERATOR_STATEMENT.to_owned());
929        for line in &preview {
930            output.line(line)?;
931        }
932        let mut report = json!({
933            "operation_id": operation.as_str(),
934            "installation": installation,
935            "application": entry.application,
936            "name": manifest.name,
937            "version": manifest.version,
938            "image_id": manifest.image_id,
939            "owner": self.owner,
940            "app_did": app,
941            "grant_sha256": grant.sha256,
942            "statement": OPERATOR_STATEMENT,
943            "containers": plans.iter().map(|plan| json!({
944                "path": plan.container,
945                "acl": plan.acl,
946                "governed_by": match &plan.fingerprint {
947                    Fingerprint::Own(_) => Json::from(plan.acl.as_str()),
948                    Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => Json::from(acl.as_str()),
949                    Fingerprint::Nothing => Json::Null,
950                },
951                "acl_text": plan.text,
952                "diff": acl::diff(
953                    &plan.previous.as_deref().map(String::from_utf8_lossy).unwrap_or_default(),
954                    &plan.text,
955                ),
956            })).collect::<Vec<_>>(),
957            "consented": false,
958            "state": InstallationState::PendingConsent,
959        });
960        let question = format!(
961            "write these ACLs and consent to installation {installation} of {}?",
962            sanitize(&manifest.name)
963        );
964        if !self.session.confirmed(&question, options.confirmation)? {
965            output.json(&report)?;
966            output.note(&format!(
967                "nothing was written; installation {installation} stays pending_consent. Withdraw \
968                 it with `stratum app withdraw {installation}`, or continue it by running install \
969                 again with --operation-id {operation}{schedule_flag}{workspace_flag}"
970            ))?;
971            return Err(CliError::NotConfirmed);
972        }
973
974        let mut written: Vec<Written> = Vec::new();
975        for (index, approved) in plans.iter().enumerate() {
976            let offered_text = &grant.containers[index].turtle;
977            if let Err(err) = self.write_container(
978                &installation,
979                &app,
980                approved,
981                offered_text,
982                options,
983                &mut written,
984            ) {
985                let left = self.remove_written(&written);
986                return Err(with_removal(err, &left));
987            }
988        }
989
990        let body = to_body(&ConsentRequest {
991            operation_id: operation_id(None)?,
992            grant_sha256: grant.sha256,
993            read_back: true,
994        })?;
995        let consent: Result<(ConsentResponse, Json), CliError> =
996            self.post(&format!("{INSTALLATIONS}/{installation}/consent"), &body);
997        let consent = match consent {
998            Ok((answer, _raw)) => answer,
999            Err(err) if is_definite_refusal(&err) => {
1000                let left = self.remove_written(&written);
1001                return Err(with_removal(
1002                    CliError::ConsentRefused(format!(
1003                        "the node refused consent to installation {installation}: {err}"
1004                    )),
1005                    &left,
1006                ));
1007            }
1008            // A lost answer, or a 5xx from behind the gate: the consent may
1009            // have been recorded, so the ACLs stay, and the person is told
1010            // how to find out.
1011            Err(err) => {
1012                output.note(&format!(
1013                    "the consent's outcome is unknown; the ACLs were left in place. `stratum app \
1014                     show {installation}` reports whether it is active, and `stratum app \
1015                     withdraw {installation}` removes them if not"
1016                ))?;
1017                return Err(err);
1018            }
1019        };
1020        if consent.state != InstallationState::Active {
1021            return Err(CliError::Refused(format!(
1022                "the node reports installation {installation} as {} after consent",
1023                consent.state
1024            )));
1025        }
1026        report["consented"] = Json::Bool(true);
1027        report["state"] = json!(consent.state);
1028        report["workspace"] = json!(consent.workspace);
1029        output.json(&report)?;
1030        output.line(&format!(
1031            "installation {installation}: active; {} container ACL(s) written and read back",
1032            written.len()
1033        ))?;
1034        Ok(exit::OK)
1035    }
1036
1037    /// Writes one container's ACL: the reread, the conditional write and
1038    /// the read-back, starting again from the read when the governing ACL
1039    /// changed or the write lost a race.
1040    fn write_container(
1041        &self,
1042        installation: &InstallationId,
1043        app: &DidNostr,
1044        approved: &Planned,
1045        offered_text: &str,
1046        options: &InstallOptions,
1047        written: &mut Vec<Written>,
1048    ) -> Result<(), CliError> {
1049        let output = self.session.output();
1050        let mut approved_text = approved.text.clone();
1051        let none = HashMap::new();
1052        for attempt in 1..=MAX_ACL_ATTEMPTS {
1053            let plan = self.plan(&approved.container, app, offered_text, &none)?;
1054            if plan.text != approved_text {
1055                output.note(&format!(
1056                    "the ACL governing {} changed since the preview; the new ACL is:",
1057                    plan.container
1058                ))?;
1059                for line in Self::describe_plan(&plan) {
1060                    output.note(&line)?;
1061                }
1062                if !self.session.confirmed(
1063                    &format!("write this ACL for {}?", plan.container),
1064                    options.confirmation,
1065                )? {
1066                    return Err(CliError::NotConfirmed);
1067                }
1068                approved_text.clone_from(&plan.text);
1069            }
1070            let (view, _raw) = self.installation(installation)?;
1071            if view.state != InstallationState::PendingConsent {
1072                return Err(CliError::ConsentRefused(format!(
1073                    "installation {installation} is {} and no longer pending_consent, so no more \
1074                     of its grant is written",
1075                    view.state
1076                )));
1077            }
1078            // Reread immediately before the write.
1079            let (_governing, fingerprint, _previous) =
1080                self.read_governing(&plan.container, &none)?;
1081            if fingerprint != plan.fingerprint {
1082                output.note(&format!(
1083                    "the ACL governing {} changed while it was being written; reading it again \
1084                     (attempt {attempt} of {MAX_ACL_ATTEMPTS})",
1085                    plan.container
1086                ))?;
1087                continue;
1088            }
1089            let precondition = match &plan.fingerprint {
1090                Fingerprint::Own(etag) => Precondition::IfMatch(etag),
1091                _ => Precondition::CreateOnly,
1092            };
1093            match self.put_acl(&plan.acl, plan.text.as_bytes(), precondition)? {
1094                Put::Lost => {
1095                    output.note(&format!(
1096                        "{} changed before the write landed; reading it again (attempt {attempt} \
1097                         of {MAX_ACL_ATTEMPTS})",
1098                        plan.acl
1099                    ))?;
1100                    continue;
1101                }
1102                Put::Done => {}
1103            }
1104            let Some((bytes, etag)) = self.read_acl(&plan.acl)? else {
1105                return Err(CliError::ReadBackMismatch(format!(
1106                    "{}: its ACL {} was absent when read back; consent was not sent",
1107                    plan.container, plan.acl
1108                )));
1109            };
1110            let back = self.parse(&plan.acl, &bytes).map_err(|err| {
1111                CliError::ReadBackMismatch(format!(
1112                    "{}: its ACL did not read back as written ({err}); consent was not sent",
1113                    plan.container
1114                ))
1115            })?;
1116            if !back.same_statements(&plan.document) {
1117                return Err(CliError::ReadBackMismatch(format!(
1118                    "{}: its ACL {} did not read back with the statements written and was left \
1119                     in place; consent was not sent",
1120                    plan.container, plan.acl
1121                )));
1122            }
1123            acl::check_no_app_control(&back, app, &plan.container)?;
1124            // Record the rollback ETag only after confirming the read-back
1125            // matches what we wrote, so rollback can never delete or overwrite
1126            // a concurrent editor's ACL.
1127            written.push(Written {
1128                acl: plan.acl.clone(),
1129                previous: plan.previous.clone(),
1130                etag,
1131            });
1132            output.note(&format!("{}: ACL written and read back", plan.container))?;
1133            return Ok(());
1134        }
1135        Err(CliError::Server {
1136            status: 412,
1137            code: "precondition_failed".to_owned(),
1138            message: format!(
1139                "the ACL governing {} changed {MAX_ACL_ATTEMPTS} times while it was being \
1140                 written; nothing more was written",
1141                approved.container
1142            ),
1143            details: Vec::new(),
1144        })
1145    }
1146
1147    /// Removes what this run wrote, newest first: an ACL the client created
1148    /// is deleted, one it replaced gets its earlier bytes back, each only if
1149    /// it is still what the client read back. Returns what could not be
1150    /// removed.
1151    fn remove_written(&self, written: &[Written]) -> Vec<String> {
1152        let mut left = Vec::new();
1153        for entry in written.iter().rev() {
1154            let precondition = Precondition::IfMatch(&entry.etag);
1155            let result = match &entry.previous {
1156                None => self
1157                    .gate
1158                    .fetch(
1159                        &Request::new("DELETE", entry.acl.as_str(), ANY)
1160                            .with_precondition(precondition),
1161                        Some(&self.key),
1162                        MAX_RESPONSE_BYTES,
1163                    )
1164                    .map(|response| response.head.status),
1165                Some(previous) => self
1166                    .gate
1167                    .fetch(
1168                        &Request::new("PUT", entry.acl.as_str(), ANY)
1169                            .with_body(previous, TURTLE)
1170                            .with_precondition(precondition),
1171                        Some(&self.key),
1172                        MAX_RESPONSE_BYTES,
1173                    )
1174                    .map(|response| response.head.status),
1175            };
1176            match result {
1177                Ok(status) if (200..300).contains(&status) => {}
1178                Ok(status) => left.push(format!("{} (HTTP {status})", entry.acl)),
1179                Err(err) => left.push(format!("{} ({err})", entry.acl)),
1180            }
1181        }
1182        left
1183    }
1184
1185    /// Cleans every container in `pending` for the withdrawn installation
1186    /// `view`, reporting each to the node as soon as it is clean.
1187    fn cleanup(
1188        &self,
1189        view: &InstallationView,
1190        pending: &[ContainerPath],
1191    ) -> Result<CleanupReport, CliError> {
1192        let output = self.session.output();
1193        let installation = view.installation;
1194        let mut report = CleanupReport::default();
1195        for path in pending {
1196            let outcome = match &view.app_did {
1197                // No key was ever recorded, so no grant naming it was
1198                // written by this or any client.
1199                None => Ok(()),
1200                Some(app) => self.clean_container(&path.under(&self.owner), app),
1201            };
1202            match outcome {
1203                Ok(()) => {
1204                    let body = to_body(&CleanupRequest {
1205                        operation_id: operation_id(None)?,
1206                        containers: vec![path.clone()],
1207                        read_back: true,
1208                    })?;
1209                    let (answer, _raw): (CleanupResponse, Json) =
1210                        self.post(&format!("{INSTALLATIONS}/{installation}/cleanup"), &body)?;
1211                    output.note(&format!("{path}: cleaned, read back and reported"))?;
1212                    report.cleaned.push(path.clone());
1213                    report.grant = Some(answer.grant);
1214                    report.pending = answer.cleanup_pending;
1215                }
1216                Err(err) => {
1217                    output.note(&format!("{path}: not cleaned: {err}"))?;
1218                    report.not_evaluated |= matches!(err, CliError::AclNotEvaluated(_));
1219                    report.failed.push((path.clone(), err.to_string()));
1220                }
1221            }
1222        }
1223        if report.grant.is_none() {
1224            report.pending = pending.to_vec();
1225            report.grant = Some(view.grant);
1226        }
1227        Ok(report)
1228    }
1229
1230    /// Removes the installation's authorisation from one container's ACL,
1231    /// with `If-Match`, then reads it back.
1232    fn clean_container(&self, container: &PodPath, app: &DidNostr) -> Result<(), CliError> {
1233        let output = self.session.output();
1234        let acl = container
1235            .acl_path()
1236            .ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
1237        for attempt in 1..=MAX_ACL_ATTEMPTS {
1238            let Some((bytes, etag)) = self.read_acl(&acl)? else {
1239                return Ok(());
1240            };
1241            let document = self.parse(&acl, &bytes)?;
1242            let others = acl::other_mentions(&document, app);
1243            if others > 0 {
1244                output.note(&format!(
1245                    "{acl}: {others} other authorisation(s) name the application key; they were \
1246                     not written by this installation and are left as they are"
1247                ))?;
1248            }
1249            let Some(cleaned) = acl::remove_installation(&document, app) else {
1250                return Ok(());
1251            };
1252            let text = acl::serialise(&cleaned)?;
1253            match self.put_acl(&acl, text.as_bytes(), Precondition::IfMatch(&etag))? {
1254                Put::Lost => {
1255                    output.note(&format!(
1256                        "{acl} changed before the edit landed; reading it again (attempt \
1257                         {attempt} of {MAX_ACL_ATTEMPTS})"
1258                    ))?;
1259                    continue;
1260                }
1261                Put::Done => {}
1262            }
1263            let Some((back, _etag)) = self.read_acl(&acl)? else {
1264                return Err(CliError::Protocol(format!(
1265                    "{acl} was absent when read back"
1266                )));
1267            };
1268            if !self.parse(&acl, &back)?.same_statements(&cleaned) {
1269                return Err(CliError::Protocol(format!(
1270                    "{acl} did not read back with the statements written"
1271                )));
1272            }
1273            return Ok(());
1274        }
1275        Err(CliError::Protocol(format!(
1276            "{acl} changed {MAX_ACL_ATTEMPTS} times while it was being edited"
1277        )))
1278    }
1279}
1280
1281/// What a cleanup did.
1282#[derive(Debug, Default)]
1283struct CleanupReport {
1284    cleaned: Vec<ContainerPath>,
1285    failed: Vec<(ContainerPath, String)>,
1286    pending: Vec<ContainerPath>,
1287    grant: Option<GrantState>,
1288    not_evaluated: bool,
1289}
1290
1291impl CleanupReport {
1292    /// The report as JSON.
1293    fn json(&self) -> Json {
1294        json!({
1295            "cleaned": self.cleaned,
1296            "failed": self.failed.iter().map(|(path, why)| json!({"path": path, "error": why})).collect::<Vec<_>>(),
1297            "cleanup_pending": self.pending,
1298            "grant": self.grant,
1299        })
1300    }
1301
1302    /// Prints the outcome and returns the exit: success when nothing is
1303    /// pending.
1304    fn finish(&self, installation: &InstallationId) -> Result<u8, CliError> {
1305        if self.pending.is_empty() && self.failed.is_empty() {
1306            return Ok(exit::OK);
1307        }
1308        let paths: Vec<&str> = self
1309            .pending
1310            .iter()
1311            .map(ContainerPath::as_str)
1312            .chain(self.failed.iter().map(|(path, _)| path.as_str()))
1313            .collect::<std::collections::BTreeSet<_>>()
1314            .into_iter()
1315            .collect();
1316        let message = format!(
1317            "installation {installation}: ACL cleanup is still pending for {}",
1318            paths.join(", ")
1319        );
1320        if self.not_evaluated {
1321            return Err(CliError::AclNotEvaluated(message));
1322        }
1323        Err(CliError::CleanupPending(message))
1324    }
1325}
1326
1327/// Whether a failed consent was certainly not recorded: a 4xx refusal, or
1328/// the gate's 503 `gate_unavailable`, which forwarded nothing. A transport
1329/// failure or any other 5xx (`bad_gateway`, `gateway_timeout`, `internal`)
1330/// leaves the outcome unknown: the node may have committed the consent
1331/// before the answer was lost.
1332fn is_definite_refusal(err: &CliError) -> bool {
1333    match err {
1334        CliError::Server { status, code, .. } => {
1335            (400..500).contains(status) || (*status == 503 && code == "gate_unavailable")
1336        }
1337        _ => false,
1338    }
1339}
1340
1341/// Adds what could not be removed to an install failure.
1342fn with_removal(err: CliError, left: &[String]) -> CliError {
1343    if left.is_empty() {
1344        return err;
1345    }
1346    let tail = format!("; NOT removed: {}", left.join(", "));
1347    match err {
1348        CliError::ReadBackMismatch(message) => {
1349            CliError::ReadBackMismatch(format!("{message}{tail}"))
1350        }
1351        CliError::ConsentRefused(message) => CliError::ConsentRefused(format!("{message}{tail}")),
1352        CliError::AclNotEvaluated(message) => CliError::AclNotEvaluated(format!("{message}{tail}")),
1353        CliError::Refused(message) => CliError::Refused(format!("{message}{tail}")),
1354        other => CliError::ConsentRefused(format!("{other}{tail}")),
1355    }
1356}
1357
1358/// The human lines of one catalogue entry.
1359fn describe_entry(entry: &CatalogueEntry) -> Vec<String> {
1360    let manifest = &entry.manifest;
1361    let mut lines = vec![format!(
1362        "{}  {} {}  image {}  workspace up to {}",
1363        entry.application,
1364        sanitize(&manifest.name),
1365        sanitize(&manifest.version),
1366        manifest.image_id,
1367        manifest.workspace
1368    )];
1369    for container in &manifest.containers {
1370        let modes: Vec<&str> = container.modes.iter().map(|m| m.as_str()).collect();
1371        let operations: Vec<&str> = container.operations.iter().map(|o| o.as_str()).collect();
1372        lines.push(format!(
1373            "  {}  {}  ({})",
1374            container.path,
1375            modes.join(", "),
1376            operations.join(", ")
1377        ));
1378    }
1379    lines
1380}
1381
1382/// One line per installation for `app list` and `stratum installations`.
1383pub(crate) fn summary_line(view: &InstallationView) -> String {
1384    let mut line = format!(
1385        "{}  {}  application {}  grant {}  jobs {} (pending {}, running {}, succeeded {}, failed {})",
1386        view.installation,
1387        view.state,
1388        view.application,
1389        view.grant,
1390        view.jobs.total(),
1391        view.jobs.pending,
1392        view.jobs.running,
1393        view.jobs.succeeded,
1394        view.jobs.failed,
1395    );
1396    if !view.key_reasons.is_empty() {
1397        let reasons: Vec<&str> = view.key_reasons.iter().map(|r| r.as_str()).collect();
1398        let _ = write!(line, "  key disabled: {}", reasons.join(", "));
1399    }
1400    if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
1401        let paths: Vec<&str> = view
1402            .cleanup_pending
1403            .iter()
1404            .map(ContainerPath::as_str)
1405            .collect();
1406        let _ = write!(line, "  ACL cleanup pending: {}", paths.join(", "));
1407    }
1408    line
1409}
1410
1411/// The human lines of `app show`.
1412fn describe_view(view: &InstallationView) -> Vec<String> {
1413    let time = |t: Option<stratum_node_core::UnixTime>| {
1414        t.map_or_else(|| "-".to_owned(), |t| t.to_string())
1415    };
1416    let mut lines = vec![
1417        format!("installation: {}", view.installation),
1418        format!("state: {}", view.state),
1419        format!("application: {}", view.application),
1420        format!("owner: {}", view.owner),
1421        format!("generation: {}", view.generation),
1422        format!(
1423            "application key: {}",
1424            view.app_did
1425                .map_or_else(|| "-".to_owned(), |d| d.to_string())
1426        ),
1427        format!(
1428            "schedule: {}",
1429            if view.schedule_secs == 0 {
1430                "manual runs only".to_owned()
1431            } else {
1432                format!("every {} s", view.schedule_secs)
1433            }
1434        ),
1435        format!("workspace: {}", view.workspace),
1436        format!("created at: {}", view.created_at),
1437        format!("activated at: {}", time(view.activated_at)),
1438        format!("withdrawn at: {}", time(view.withdrawn_at)),
1439        format!(
1440            "key disabled by: {}",
1441            if view.key_reasons.is_empty() {
1442                "-".to_owned()
1443            } else {
1444                view.key_reasons
1445                    .iter()
1446                    .map(|r| r.as_str())
1447                    .collect::<Vec<_>>()
1448                    .join(", ")
1449            }
1450        ),
1451        format!(
1452            "grant: {} (as your client reported it to the node)",
1453            view.grant
1454        ),
1455    ];
1456    if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
1457        let paths: Vec<&str> = view
1458            .cleanup_pending
1459            .iter()
1460            .map(ContainerPath::as_str)
1461            .collect();
1462        lines.push(format!(
1463            "ACL cleanup pending: {} (run `stratum app cleanup {}`)",
1464            paths.join(", "),
1465            view.installation
1466        ));
1467    }
1468    if let Some(parts) = &view.enforcement {
1469        lines.push(format!(
1470            "enforcement: authorisation {}, keys {}, work {}",
1471            parts.authorisation, parts.keys, parts.work
1472        ));
1473    }
1474    lines.push(format!(
1475        "jobs: {} (pending {}, running {}, succeeded {}, failed {}, cancelled {}, conflict {}, skipped {})",
1476        view.jobs.total(),
1477        view.jobs.pending,
1478        view.jobs.running,
1479        view.jobs.succeeded,
1480        view.jobs.failed,
1481        view.jobs.cancelled,
1482        view.jobs.conflict,
1483        view.jobs.skipped
1484    ));
1485    lines
1486}