use std::collections::HashMap;
use std::fmt::Write as _;
use serde::de::DeserializeOwned;
use serde_json::{json, Value as Json};
use stratum_node_core::{
check_schedule_secs, render_offered, ApplicationId, Catalogue, CatalogueEntry, CleanupRequest,
CleanupResponse, ConsentRequest, ConsentResponse, ContainerPath, CreateInstallationRequest,
CreateInstallationResponse, DidNostr, GrantState, InstallationActionRequest, InstallationId,
InstallationList, InstallationState, InstallationView, JobList, NostrSecretKey, OfferedGrant,
PodPath, ResumeInstallationResponse, RunRequest, RunResponse, WithdrawResponse, WorkspaceMode,
};
use crate::acl::{self, AclDocument, Authorisation, Governing};
use crate::client::MAX_RESPONSE_BYTES;
use crate::error::CliError;
use crate::exit;
use crate::gate::{GateClient, Precondition, Request, Route, ANY, JSON};
use crate::origin::GateTarget;
use crate::output::sanitize;
use crate::session::{operation_id, to_body, Confirmation, Session};
const CATALOGUE: &str = "/api/v1/catalogue";
const INSTALLATIONS: &str = "/api/v1/installations";
const TURTLE: &str = "text/turtle";
const MAX_ACL_BYTES: u64 = 1024 * 1024;
pub(crate) const MAX_ACL_ATTEMPTS: u32 = 5;
pub const OPERATOR_STATEMENT: &str = "The node's operator has root on the host: they can read \
workspaces, the tenant daemon's data (where this application's containers run) and backups, \
which hold your pod. Stratum states this; it does not prevent it.";
#[derive(Debug, Clone)]
pub struct InstallOptions {
pub application: ApplicationId,
pub schedule_secs: u64,
pub workspace: WorkspaceMode,
pub operation_id: Option<String>,
pub confirmation: Confirmation,
}
#[derive(Debug, Clone)]
struct Planned {
container: PodPath,
acl: PodPath,
fingerprint: Fingerprint,
previous: Option<Vec<u8>>,
document: AclDocument,
text: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Fingerprint {
Own(String),
Inherited(PodPath, String),
Planned(PodPath),
Nothing,
}
#[derive(Debug, Clone)]
struct Written {
acl: PodPath,
previous: Option<Vec<u8>>,
etag: String,
}
enum Put {
Done,
Lost,
}
struct Tenant<'a> {
session: &'a Session,
gate: GateClient,
key: NostrSecretKey,
owner: DidNostr,
}
impl Session {
pub fn app_catalogue(&self, target: &GateTarget) -> Result<u8, CliError> {
self.with_tenant(target, |tenant| {
let (catalogue, raw): (Catalogue, Json) = tenant.get(CATALOGUE)?;
self.output().json(&raw)?;
if catalogue.applications.is_empty() {
self.output()
.line("no applications are approved on this node")?;
}
for entry in &catalogue.applications {
for line in describe_entry(entry) {
self.output().line(&line)?;
}
}
Ok(exit::OK)
})
}
pub fn app_install(
&self,
target: &GateTarget,
options: &InstallOptions,
) -> Result<u8, CliError> {
check_schedule_secs(options.schedule_secs).map_err(|_| {
CliError::Usage(
"--schedule must be 0 (manual runs only) or 300 to 604800 seconds".to_owned(),
)
})?;
let operation = operation_id(options.operation_id.as_deref())?;
self.with_tenant(target, |tenant| tenant.install(options, &operation))
}
pub fn app_list(&self, target: &GateTarget) -> Result<u8, CliError> {
self.with_tenant(target, |tenant| {
let (list, raw): (InstallationList, Json) = tenant.get(INSTALLATIONS)?;
for view in &list.installations {
if view.owner != tenant.owner {
return Err(CliError::Refused(format!(
"the node listed installation {} of {} among yours",
view.installation, view.owner
)));
}
}
self.output().json(&raw)?;
if list.installations.is_empty() {
self.output().line("no installations")?;
}
for view in &list.installations {
self.output().line(&summary_line(view))?;
}
Ok(exit::OK)
})
}
pub fn app_show(
&self,
target: &GateTarget,
installation: &InstallationId,
) -> Result<u8, CliError> {
self.with_tenant(target, |tenant| {
let (view, raw) = tenant.installation(installation)?;
self.output().json(&raw)?;
for line in describe_view(&view) {
self.output().line(&line)?;
}
Ok(exit::OK)
})
}
pub fn app_jobs(
&self,
target: &GateTarget,
installation: &InstallationId,
) -> Result<u8, CliError> {
self.with_tenant(target, |tenant| {
let path = format!("{INSTALLATIONS}/{installation}/jobs");
let (jobs, raw): (JobList, Json) = tenant.get(&path)?;
if jobs.installation != *installation {
return Err(CliError::Refused(format!(
"asked for the jobs of {installation}, the node answered with {}",
jobs.installation
)));
}
self.output().json(&raw)?;
if jobs.jobs.is_empty() {
self.output().line("no jobs")?;
}
for job in &jobs.jobs {
let mut line = format!(
"period {} {} job {} attempts {}",
job.period, job.state, job.job, job.attempts
);
if let Some(outcome) = job.outcome {
let _ = write!(line, " outcome {outcome}");
}
if let Some(resource) = &job.resource {
let _ = write!(line, " resource {}", sanitize(resource));
}
if let Some(sha256) = &job.sha256 {
let _ = write!(line, " sha256 {sha256}");
}
if let Some(length) = job.length {
let _ = write!(line, " {length} bytes");
}
if let Some(code) = job.exit_code {
let _ = write!(line, " exit {code}");
}
if let Some(at) = job.next_eligible_at {
let _ = write!(line, " next attempt after {at}");
}
self.output().line(&line)?;
}
Ok(exit::OK)
})
}
pub fn app_run(
&self,
target: &GateTarget,
installation: &InstallationId,
period: u64,
operation_id_arg: Option<&str>,
confirmation: Confirmation,
) -> Result<u8, CliError> {
let operation = operation_id(operation_id_arg)?;
self.with_tenant(target, |tenant| {
if !self.confirmed(
&format!("run period {period} of installation {installation} now?"),
confirmation,
)? {
return Err(CliError::NotConfirmed);
}
tenant.note_operation(&operation, "")?;
let body = to_body(&RunRequest {
operation_id: operation.clone(),
period,
})?;
let (answer, _raw): (RunResponse, Json) =
tenant.post(&format!("{INSTALLATIONS}/{installation}/run"), &body)?;
self.output().json(&json!({
"operation_id": operation.as_str(),
"installation": installation,
"period": period,
"job": answer.job,
"state": answer.state,
}))?;
self.output().line(&format!(
"period {period}: job {} is {}",
answer.job, answer.state
))?;
Ok(exit::OK)
})
}
pub fn app_withdraw(
&self,
target: &GateTarget,
installation: &InstallationId,
operation_id_arg: Option<&str>,
confirmation: Confirmation,
) -> Result<u8, CliError> {
let operation = operation_id(operation_id_arg)?;
self.with_tenant(target, |tenant| {
let question = format!(
"withdraw installation {installation}? Its key is disabled and its jobs stop; \
then its authorisation is removed from each granted container's ACL"
);
if !self.confirmed(&question, confirmation)? {
return Err(CliError::NotConfirmed);
}
tenant.note_operation(&operation, "")?;
let body = to_body(&InstallationActionRequest {
operation_id: operation.clone(),
})?;
let (answer, raw): (WithdrawResponse, Json) =
tenant.post(&format!("{INSTALLATIONS}/{installation}/withdraw"), &body)?;
if answer.state != InstallationState::Withdrawn {
return Err(CliError::Refused(format!(
"the node reports installation {installation} as {} after withdraw",
answer.state
)));
}
self.output().line(&format!(
"installation {installation}: withdrawn; authorisation {}",
answer.authorisation
))?;
let (view, _raw) = tenant.installation(installation)?;
let report = tenant.cleanup(&view, &answer.cleanup_pending)?;
self.output().json(&json!({
"operation_id": operation.as_str(),
"installation": installation,
"withdraw": raw,
"cleanup": report.json(),
}))?;
report.finish(installation)
})
}
pub fn app_cleanup(
&self,
target: &GateTarget,
installation: &InstallationId,
confirmation: Confirmation,
) -> Result<u8, CliError> {
self.with_tenant(target, |tenant| {
let (view, _raw) = tenant.installation(installation)?;
if view.grant != GrantState::Withdrawn || view.cleanup_pending.is_empty() {
self.output().json(&json!({
"installation": installation,
"grant": view.grant,
"cleanup_pending": [],
}))?;
self.output().line(&format!(
"installation {installation}: no ACL cleanup is pending (grant {})",
view.grant
))?;
return Ok(exit::OK);
}
let question = format!(
"remove installation {installation}'s authorisation from {} container ACL(s)?",
view.cleanup_pending.len()
);
if !self.confirmed(&question, confirmation)? {
return Err(CliError::NotConfirmed);
}
let report = tenant.cleanup(&view, &view.cleanup_pending)?;
self.output().json(&json!({
"installation": installation,
"cleanup": report.json(),
}))?;
report.finish(installation)
})
}
pub fn app_resume(
&self,
target: &GateTarget,
installation: &InstallationId,
operation_id_arg: Option<&str>,
confirmation: Confirmation,
) -> Result<u8, CliError> {
let operation = operation_id(operation_id_arg)?;
self.with_tenant(target, |tenant| {
if !self.confirmed(
&format!("enable installation {installation}'s key again after the restore?"),
confirmation,
)? {
return Err(CliError::NotConfirmed);
}
tenant.note_operation(&operation, "")?;
let body = to_body(&InstallationActionRequest {
operation_id: operation.clone(),
})?;
let (answer, _raw): (ResumeInstallationResponse, Json) =
tenant.post(&format!("{INSTALLATIONS}/{installation}/resume"), &body)?;
self.output().json(&json!({
"operation_id": operation.as_str(),
"installation": installation,
"keys": answer.keys,
}))?;
self.output()
.line(&format!("installation {installation}: key {}", answer.keys))?;
Ok(exit::OK)
})
}
fn with_tenant(
&self,
target: &GateTarget,
command: impl FnOnce(&Tenant<'_>) -> Result<u8, CliError>,
) -> Result<u8, CliError> {
let key = self.key()?;
let tenant = Tenant {
session: self,
gate: GateClient::new(target.clone()).with_busy_retries(*self.output()),
owner: key.public(),
key,
};
let result = command(&tenant);
tenant.show_pending_cleanup();
result
}
}
impl Tenant<'_> {
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<(T, Json), CliError> {
self.gate
.fetch(
&Request::new("GET", path, JSON),
Some(&self.key),
MAX_RESPONSE_BYTES,
)?
.into_json(Route::Admission)
}
fn post<T: DeserializeOwned>(&self, path: &str, body: &[u8]) -> Result<(T, Json), CliError> {
self.gate
.fetch(
&Request::new("POST", path, JSON).with_body(body, JSON),
Some(&self.key),
MAX_RESPONSE_BYTES,
)?
.into_json(Route::Admission)
}
fn note_operation(
&self,
operation: &stratum_node_core::OperationId,
flags: &str,
) -> Result<(), CliError> {
self.session.output().note(&format!(
"operation id: {operation} (to retry after a lost response, pass --operation-id \
{operation}{flags}: the retry must send the same request)"
))
}
fn installation(
&self,
installation: &InstallationId,
) -> Result<(InstallationView, Json), CliError> {
let (view, raw): (InstallationView, Json) =
self.get(&format!("{INSTALLATIONS}/{installation}"))?;
if view.installation != *installation || view.owner != self.owner {
return Err(CliError::Refused(format!(
"asked for installation {installation} of {}, the node answered with {} of {}",
self.owner, view.installation, view.owner
)));
}
Ok((view, raw))
}
fn show_pending_cleanup(&self) {
let Ok((list, _raw)) = self.get::<InstallationList>(INSTALLATIONS) else {
return;
};
for view in &list.installations {
if view.owner != self.owner
|| view.grant != GrantState::Withdrawn
|| view.cleanup_pending.is_empty()
{
continue;
}
let paths: Vec<&str> = view
.cleanup_pending
.iter()
.map(ContainerPath::as_str)
.collect();
let _noted = self.session.output().note(&format!(
"installation {} was withdrawn and its ACL cleanup is pending for {}: run \
`stratum app cleanup {}`",
view.installation,
paths.join(", "),
view.installation
));
}
}
fn read_acl(&self, acl: &PodPath) -> Result<Option<(Vec<u8>, String)>, CliError> {
let response = self.gate.fetch(
&Request::new("GET", acl.as_str(), ANY),
Some(&self.key),
MAX_ACL_BYTES,
)?;
if response.head.status == 404 {
return Ok(None);
}
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
let Some(etag) = response.head.etag.clone() else {
return Err(CliError::Protocol(format!(
"{acl} was read without an entity tag, so it cannot be written conditionally"
)));
};
Ok(Some((response.body, etag)))
}
fn put_acl(
&self,
acl: &PodPath,
body: &[u8],
precondition: Precondition<'_>,
) -> Result<Put, CliError> {
let request = Request::new("PUT", acl.as_str(), ANY)
.with_body(body, TURTLE)
.with_precondition(precondition);
let response = self
.gate
.fetch(&request, Some(&self.key), MAX_RESPONSE_BYTES)?;
if response.head.status == 412 {
return Ok(Put::Lost);
}
if !response.head.is_success() {
return Err(response.into_error(Route::Pod));
}
Ok(Put::Done)
}
fn parse(&self, acl: &PodPath, bytes: &[u8]) -> Result<AclDocument, CliError> {
let origin = self.gate.target().origin();
acl::parse(&origin.url(acl.as_str()), acl, &origin.as_str(), bytes)
}
fn read_governing(
&self,
container: &PodPath,
planned: &HashMap<PodPath, AclDocument>,
) -> Result<(Governing, Fingerprint, Option<Vec<u8>>), CliError> {
for candidate in acl::governing_candidates(container) {
let Some(acl) = candidate.acl_path() else {
continue;
};
let own = candidate == *container;
if !own {
if let Some(document) = planned.get(&acl) {
return Ok((
Governing::Inherited {
acl: acl.clone(),
document: document.clone(),
},
Fingerprint::Planned(acl),
None,
));
}
}
let Some((bytes, etag)) = self.read_acl(&acl)? else {
continue;
};
let document = self.parse(&acl, &bytes)?;
return Ok(if own {
(
Governing::Own(document),
Fingerprint::Own(etag),
Some(bytes),
)
} else {
(
Governing::Inherited {
acl: acl.clone(),
document,
},
Fingerprint::Inherited(acl, etag),
None,
)
});
}
Ok((Governing::Nothing, Fingerprint::Nothing, None))
}
fn plan(
&self,
container: &PodPath,
app: &DidNostr,
offered_text: &str,
planned: &HashMap<PodPath, AclDocument>,
) -> Result<Planned, CliError> {
let acl = container
.acl_path()
.ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
let url = self.gate.target().origin().url(acl.as_str());
let offered = self
.parse(&acl, offered_text.as_bytes())
.map_err(|_| {
CliError::Protocol(format!("the offered rule for {container} does not parse"))
})?
.authorisations;
let [offered] = <[Authorisation; 1]>::try_from(offered).map_err(|_| {
CliError::Protocol(format!(
"the offered rule for {container} is not exactly one authorisation"
))
})?;
let (governing, fingerprint, previous) = self.read_governing(container, planned)?;
let document = acl::materialise(&acl::Materialise {
owner: &self.owner,
app,
container,
url: &url,
governing: &governing,
offered: &offered,
})?;
let text = acl::serialise(&document)?;
let reparsed = self.parse(&acl, text.as_bytes())?;
if !reparsed.same_statements(&document) {
return Err(CliError::Local(format!(
"the ACL built for {container} does not parse back to its own statements"
)));
}
Ok(Planned {
container: container.clone(),
acl,
fingerprint,
previous,
document,
text,
})
}
fn describe_plan(planned: &Planned) -> Vec<String> {
let governed = match &planned.fingerprint {
Fingerprint::Own(_) => "governed now by its own ACL, which is kept".to_owned(),
Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => format!(
"governed now by {acl}: its rules that reach this container by acl:default are \
copied into a new ACL, so every principal keeps exactly its access"
),
Fingerprint::Nothing => "governed now by no ACL".to_owned(),
};
let old = planned
.previous
.as_deref()
.map(String::from_utf8_lossy)
.unwrap_or_default();
let mut lines = vec![
format!("container {} (ACL {})", planned.container, planned.acl),
format!(" {governed}"),
];
lines.extend(
acl::diff(&old, &planned.text)
.into_iter()
.map(|line| format!(" {}", sanitize(&line))),
);
lines
}
#[expect(
clippy::too_many_lines,
reason = "the install sequence reads best as one ordered procedure"
)]
fn install(
&self,
options: &InstallOptions,
operation: &stratum_node_core::OperationId,
) -> Result<u8, CliError> {
let output = self.session.output();
let (catalogue, _raw): (Catalogue, Json) = self.get(CATALOGUE)?;
let Some(entry) = catalogue
.applications
.into_iter()
.find(|entry| entry.application == options.application)
else {
return Err(CliError::Usage(format!(
"application {} is not in this node's catalogue: only approved applications can \
be installed; `stratum app catalogue` lists them",
options.application
)));
};
let manifest = &entry.manifest;
if options.workspace > manifest.workspace {
return Err(CliError::Usage(format!(
"--workspace {} is more than application {} allows ({})",
options.workspace, options.application, manifest.workspace
)));
}
let schedule_flag = if options.schedule_secs == 0 {
String::new()
} else {
format!(" --schedule {}", options.schedule_secs)
};
let workspace_flag = if options.workspace == WorkspaceMode::None {
String::new()
} else {
format!(" --workspace {}", options.workspace)
};
self.note_operation(operation, &format!("{schedule_flag}{workspace_flag}"))?;
let body = to_body(&CreateInstallationRequest {
operation_id: operation.clone(),
application: options.application,
schedule_secs: options.schedule_secs,
workspace: options.workspace,
})?;
let (created, _raw): (CreateInstallationResponse, Json) =
self.post(INSTALLATIONS, &body)?;
let installation = created.installation;
if created.state != InstallationState::PendingConsent {
return Err(CliError::Refused(format!(
"the node reports installation {installation} as {}, not pending_consent",
created.state
)));
}
let app = created.app_did;
if app == self.owner {
return Err(CliError::Refused(
"the node offered your own key as the application key".to_owned(),
));
}
let expected = render_offered(&app, &self.owner, &manifest.containers);
if created.grant != expected {
return Err(CliError::Refused(format!(
"the grant the node offered for installation {installation} is not the one the \
manifest renders for key {app} (offered sha256 {}, rendered {})",
created.grant.sha256, expected.sha256
)));
}
let grant: OfferedGrant = created.grant;
let mut planned_documents: HashMap<PodPath, AclDocument> = HashMap::new();
let mut plans = Vec::with_capacity(grant.containers.len());
for offered in &grant.containers {
let container = offered.path.under(&self.owner);
let plan = self.plan(&container, &app, &offered.turtle, &planned_documents)?;
planned_documents.insert(plan.acl.clone(), plan.document.clone());
plans.push(plan);
}
let mut preview = vec![
format!("installation: {installation} (pending consent)"),
format!("owner: {}", self.owner),
format!(
"application: {} {} (version {})",
entry.application,
sanitize(&manifest.name),
sanitize(&manifest.version)
),
format!("image: {}", manifest.image_id),
format!("application key: {app}"),
format!(
"schedule: {}",
if options.schedule_secs == 0 {
"manual runs only".to_owned()
} else {
format!("every {} s", options.schedule_secs)
}
),
format!("workspace: {}", options.workspace),
format!("grant sha256: {}", grant.sha256),
];
for plan in &plans {
preview.extend(Self::describe_plan(plan));
}
preview.push(OPERATOR_STATEMENT.to_owned());
for line in &preview {
output.line(line)?;
}
let mut report = json!({
"operation_id": operation.as_str(),
"installation": installation,
"application": entry.application,
"name": manifest.name,
"version": manifest.version,
"image_id": manifest.image_id,
"owner": self.owner,
"app_did": app,
"grant_sha256": grant.sha256,
"statement": OPERATOR_STATEMENT,
"containers": plans.iter().map(|plan| json!({
"path": plan.container,
"acl": plan.acl,
"governed_by": match &plan.fingerprint {
Fingerprint::Own(_) => Json::from(plan.acl.as_str()),
Fingerprint::Inherited(acl, _) | Fingerprint::Planned(acl) => Json::from(acl.as_str()),
Fingerprint::Nothing => Json::Null,
},
"acl_text": plan.text,
"diff": acl::diff(
&plan.previous.as_deref().map(String::from_utf8_lossy).unwrap_or_default(),
&plan.text,
),
})).collect::<Vec<_>>(),
"consented": false,
"state": InstallationState::PendingConsent,
});
let question = format!(
"write these ACLs and consent to installation {installation} of {}?",
sanitize(&manifest.name)
);
if !self.session.confirmed(&question, options.confirmation)? {
output.json(&report)?;
output.note(&format!(
"nothing was written; installation {installation} stays pending_consent. Withdraw \
it with `stratum app withdraw {installation}`, or continue it by running install \
again with --operation-id {operation}{schedule_flag}{workspace_flag}"
))?;
return Err(CliError::NotConfirmed);
}
let mut written: Vec<Written> = Vec::new();
for (index, approved) in plans.iter().enumerate() {
let offered_text = &grant.containers[index].turtle;
if let Err(err) = self.write_container(
&installation,
&app,
approved,
offered_text,
options,
&mut written,
) {
let left = self.remove_written(&written);
return Err(with_removal(err, &left));
}
}
let body = to_body(&ConsentRequest {
operation_id: operation_id(None)?,
grant_sha256: grant.sha256,
read_back: true,
})?;
let consent: Result<(ConsentResponse, Json), CliError> =
self.post(&format!("{INSTALLATIONS}/{installation}/consent"), &body);
let consent = match consent {
Ok((answer, _raw)) => answer,
Err(err) if is_definite_refusal(&err) => {
let left = self.remove_written(&written);
return Err(with_removal(
CliError::ConsentRefused(format!(
"the node refused consent to installation {installation}: {err}"
)),
&left,
));
}
Err(err) => {
output.note(&format!(
"the consent's outcome is unknown; the ACLs were left in place. `stratum app \
show {installation}` reports whether it is active, and `stratum app \
withdraw {installation}` removes them if not"
))?;
return Err(err);
}
};
if consent.state != InstallationState::Active {
return Err(CliError::Refused(format!(
"the node reports installation {installation} as {} after consent",
consent.state
)));
}
report["consented"] = Json::Bool(true);
report["state"] = json!(consent.state);
report["workspace"] = json!(consent.workspace);
output.json(&report)?;
output.line(&format!(
"installation {installation}: active; {} container ACL(s) written and read back",
written.len()
))?;
Ok(exit::OK)
}
fn write_container(
&self,
installation: &InstallationId,
app: &DidNostr,
approved: &Planned,
offered_text: &str,
options: &InstallOptions,
written: &mut Vec<Written>,
) -> Result<(), CliError> {
let output = self.session.output();
let mut approved_text = approved.text.clone();
let none = HashMap::new();
for attempt in 1..=MAX_ACL_ATTEMPTS {
let plan = self.plan(&approved.container, app, offered_text, &none)?;
if plan.text != approved_text {
output.note(&format!(
"the ACL governing {} changed since the preview; the new ACL is:",
plan.container
))?;
for line in Self::describe_plan(&plan) {
output.note(&line)?;
}
if !self.session.confirmed(
&format!("write this ACL for {}?", plan.container),
options.confirmation,
)? {
return Err(CliError::NotConfirmed);
}
approved_text.clone_from(&plan.text);
}
let (view, _raw) = self.installation(installation)?;
if view.state != InstallationState::PendingConsent {
return Err(CliError::ConsentRefused(format!(
"installation {installation} is {} and no longer pending_consent, so no more \
of its grant is written",
view.state
)));
}
let (_governing, fingerprint, _previous) =
self.read_governing(&plan.container, &none)?;
if fingerprint != plan.fingerprint {
output.note(&format!(
"the ACL governing {} changed while it was being written; reading it again \
(attempt {attempt} of {MAX_ACL_ATTEMPTS})",
plan.container
))?;
continue;
}
let precondition = match &plan.fingerprint {
Fingerprint::Own(etag) => Precondition::IfMatch(etag),
_ => Precondition::CreateOnly,
};
match self.put_acl(&plan.acl, plan.text.as_bytes(), precondition)? {
Put::Lost => {
output.note(&format!(
"{} changed before the write landed; reading it again (attempt {attempt} \
of {MAX_ACL_ATTEMPTS})",
plan.acl
))?;
continue;
}
Put::Done => {}
}
let Some((bytes, etag)) = self.read_acl(&plan.acl)? else {
return Err(CliError::ReadBackMismatch(format!(
"{}: its ACL {} was absent when read back; consent was not sent",
plan.container, plan.acl
)));
};
let back = self.parse(&plan.acl, &bytes).map_err(|err| {
CliError::ReadBackMismatch(format!(
"{}: its ACL did not read back as written ({err}); consent was not sent",
plan.container
))
})?;
if !back.same_statements(&plan.document) {
return Err(CliError::ReadBackMismatch(format!(
"{}: its ACL {} did not read back with the statements written and was left \
in place; consent was not sent",
plan.container, plan.acl
)));
}
acl::check_no_app_control(&back, app, &plan.container)?;
written.push(Written {
acl: plan.acl.clone(),
previous: plan.previous.clone(),
etag,
});
output.note(&format!("{}: ACL written and read back", plan.container))?;
return Ok(());
}
Err(CliError::Server {
status: 412,
code: "precondition_failed".to_owned(),
message: format!(
"the ACL governing {} changed {MAX_ACL_ATTEMPTS} times while it was being \
written; nothing more was written",
approved.container
),
details: Vec::new(),
})
}
fn remove_written(&self, written: &[Written]) -> Vec<String> {
let mut left = Vec::new();
for entry in written.iter().rev() {
let precondition = Precondition::IfMatch(&entry.etag);
let result = match &entry.previous {
None => self
.gate
.fetch(
&Request::new("DELETE", entry.acl.as_str(), ANY)
.with_precondition(precondition),
Some(&self.key),
MAX_RESPONSE_BYTES,
)
.map(|response| response.head.status),
Some(previous) => self
.gate
.fetch(
&Request::new("PUT", entry.acl.as_str(), ANY)
.with_body(previous, TURTLE)
.with_precondition(precondition),
Some(&self.key),
MAX_RESPONSE_BYTES,
)
.map(|response| response.head.status),
};
match result {
Ok(status) if (200..300).contains(&status) => {}
Ok(status) => left.push(format!("{} (HTTP {status})", entry.acl)),
Err(err) => left.push(format!("{} ({err})", entry.acl)),
}
}
left
}
fn cleanup(
&self,
view: &InstallationView,
pending: &[ContainerPath],
) -> Result<CleanupReport, CliError> {
let output = self.session.output();
let installation = view.installation;
let mut report = CleanupReport::default();
for path in pending {
let outcome = match &view.app_did {
None => Ok(()),
Some(app) => self.clean_container(&path.under(&self.owner), app),
};
match outcome {
Ok(()) => {
let body = to_body(&CleanupRequest {
operation_id: operation_id(None)?,
containers: vec![path.clone()],
read_back: true,
})?;
let (answer, _raw): (CleanupResponse, Json) =
self.post(&format!("{INSTALLATIONS}/{installation}/cleanup"), &body)?;
output.note(&format!("{path}: cleaned, read back and reported"))?;
report.cleaned.push(path.clone());
report.grant = Some(answer.grant);
report.pending = answer.cleanup_pending;
}
Err(err) => {
output.note(&format!("{path}: not cleaned: {err}"))?;
report.not_evaluated |= matches!(err, CliError::AclNotEvaluated(_));
report.failed.push((path.clone(), err.to_string()));
}
}
}
if report.grant.is_none() {
report.pending = pending.to_vec();
report.grant = Some(view.grant);
}
Ok(report)
}
fn clean_container(&self, container: &PodPath, app: &DidNostr) -> Result<(), CliError> {
let output = self.session.output();
let acl = container
.acl_path()
.ok_or_else(|| CliError::Protocol(format!("{container} has no ACL path")))?;
for attempt in 1..=MAX_ACL_ATTEMPTS {
let Some((bytes, etag)) = self.read_acl(&acl)? else {
return Ok(());
};
let document = self.parse(&acl, &bytes)?;
let others = acl::other_mentions(&document, app);
if others > 0 {
output.note(&format!(
"{acl}: {others} other authorisation(s) name the application key; they were \
not written by this installation and are left as they are"
))?;
}
let Some(cleaned) = acl::remove_installation(&document, app) else {
return Ok(());
};
let text = acl::serialise(&cleaned)?;
match self.put_acl(&acl, text.as_bytes(), Precondition::IfMatch(&etag))? {
Put::Lost => {
output.note(&format!(
"{acl} changed before the edit landed; reading it again (attempt \
{attempt} of {MAX_ACL_ATTEMPTS})"
))?;
continue;
}
Put::Done => {}
}
let Some((back, _etag)) = self.read_acl(&acl)? else {
return Err(CliError::Protocol(format!(
"{acl} was absent when read back"
)));
};
if !self.parse(&acl, &back)?.same_statements(&cleaned) {
return Err(CliError::Protocol(format!(
"{acl} did not read back with the statements written"
)));
}
return Ok(());
}
Err(CliError::Protocol(format!(
"{acl} changed {MAX_ACL_ATTEMPTS} times while it was being edited"
)))
}
}
#[derive(Debug, Default)]
struct CleanupReport {
cleaned: Vec<ContainerPath>,
failed: Vec<(ContainerPath, String)>,
pending: Vec<ContainerPath>,
grant: Option<GrantState>,
not_evaluated: bool,
}
impl CleanupReport {
fn json(&self) -> Json {
json!({
"cleaned": self.cleaned,
"failed": self.failed.iter().map(|(path, why)| json!({"path": path, "error": why})).collect::<Vec<_>>(),
"cleanup_pending": self.pending,
"grant": self.grant,
})
}
fn finish(&self, installation: &InstallationId) -> Result<u8, CliError> {
if self.pending.is_empty() && self.failed.is_empty() {
return Ok(exit::OK);
}
let paths: Vec<&str> = self
.pending
.iter()
.map(ContainerPath::as_str)
.chain(self.failed.iter().map(|(path, _)| path.as_str()))
.collect::<std::collections::BTreeSet<_>>()
.into_iter()
.collect();
let message = format!(
"installation {installation}: ACL cleanup is still pending for {}",
paths.join(", ")
);
if self.not_evaluated {
return Err(CliError::AclNotEvaluated(message));
}
Err(CliError::CleanupPending(message))
}
}
fn is_definite_refusal(err: &CliError) -> bool {
match err {
CliError::Server { status, code, .. } => {
(400..500).contains(status) || (*status == 503 && code == "gate_unavailable")
}
_ => false,
}
}
fn with_removal(err: CliError, left: &[String]) -> CliError {
if left.is_empty() {
return err;
}
let tail = format!("; NOT removed: {}", left.join(", "));
match err {
CliError::ReadBackMismatch(message) => {
CliError::ReadBackMismatch(format!("{message}{tail}"))
}
CliError::ConsentRefused(message) => CliError::ConsentRefused(format!("{message}{tail}")),
CliError::AclNotEvaluated(message) => CliError::AclNotEvaluated(format!("{message}{tail}")),
CliError::Refused(message) => CliError::Refused(format!("{message}{tail}")),
other => CliError::ConsentRefused(format!("{other}{tail}")),
}
}
fn describe_entry(entry: &CatalogueEntry) -> Vec<String> {
let manifest = &entry.manifest;
let mut lines = vec![format!(
"{} {} {} image {} workspace up to {}",
entry.application,
sanitize(&manifest.name),
sanitize(&manifest.version),
manifest.image_id,
manifest.workspace
)];
for container in &manifest.containers {
let modes: Vec<&str> = container.modes.iter().map(|m| m.as_str()).collect();
let operations: Vec<&str> = container.operations.iter().map(|o| o.as_str()).collect();
lines.push(format!(
" {} {} ({})",
container.path,
modes.join(", "),
operations.join(", ")
));
}
lines
}
pub(crate) fn summary_line(view: &InstallationView) -> String {
let mut line = format!(
"{} {} application {} grant {} jobs {} (pending {}, running {}, succeeded {}, failed {})",
view.installation,
view.state,
view.application,
view.grant,
view.jobs.total(),
view.jobs.pending,
view.jobs.running,
view.jobs.succeeded,
view.jobs.failed,
);
if !view.key_reasons.is_empty() {
let reasons: Vec<&str> = view.key_reasons.iter().map(|r| r.as_str()).collect();
let _ = write!(line, " key disabled: {}", reasons.join(", "));
}
if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
let paths: Vec<&str> = view
.cleanup_pending
.iter()
.map(ContainerPath::as_str)
.collect();
let _ = write!(line, " ACL cleanup pending: {}", paths.join(", "));
}
line
}
fn describe_view(view: &InstallationView) -> Vec<String> {
let time = |t: Option<stratum_node_core::UnixTime>| {
t.map_or_else(|| "-".to_owned(), |t| t.to_string())
};
let mut lines = vec![
format!("installation: {}", view.installation),
format!("state: {}", view.state),
format!("application: {}", view.application),
format!("owner: {}", view.owner),
format!("generation: {}", view.generation),
format!(
"application key: {}",
view.app_did
.map_or_else(|| "-".to_owned(), |d| d.to_string())
),
format!(
"schedule: {}",
if view.schedule_secs == 0 {
"manual runs only".to_owned()
} else {
format!("every {} s", view.schedule_secs)
}
),
format!("workspace: {}", view.workspace),
format!("created at: {}", view.created_at),
format!("activated at: {}", time(view.activated_at)),
format!("withdrawn at: {}", time(view.withdrawn_at)),
format!(
"key disabled by: {}",
if view.key_reasons.is_empty() {
"-".to_owned()
} else {
view.key_reasons
.iter()
.map(|r| r.as_str())
.collect::<Vec<_>>()
.join(", ")
}
),
format!(
"grant: {} (as your client reported it to the node)",
view.grant
),
];
if view.grant == GrantState::Withdrawn && !view.cleanup_pending.is_empty() {
let paths: Vec<&str> = view
.cleanup_pending
.iter()
.map(ContainerPath::as_str)
.collect();
lines.push(format!(
"ACL cleanup pending: {} (run `stratum app cleanup {}`)",
paths.join(", "),
view.installation
));
}
if let Some(parts) = &view.enforcement {
lines.push(format!(
"enforcement: authorisation {}, keys {}, work {}",
parts.authorisation, parts.keys, parts.work
));
}
lines.push(format!(
"jobs: {} (pending {}, running {}, succeeded {}, failed {}, cancelled {}, conflict {}, skipped {})",
view.jobs.total(),
view.jobs.pending,
view.jobs.running,
view.jobs.succeeded,
view.jobs.failed,
view.jobs.cancelled,
view.jobs.conflict,
view.jobs.skipped
));
lines
}