Skip to main content

qualia_client_core/identity_plane/
fleet_jobs.rs

1//! Multi-apparatus job delivery: sign, POST, accept, outbox.
2//!
3//! Local jobs stay on the local queue. Jobs aimed at a registered remote
4//! apparatus are signed by the person principal and delivered to that device's
5//! `control_base_url` (`POST /api/fleet/jobs`). Failures land in a durable
6//! outbox for retry. Unknown targets still fail closed.
7
8use super::fleet::{ensure_local_apparatus, resolve_job_placement, JobPlacement};
9use super::person::PersonPrincipal;
10use crate::local_job_scheduler::{LocalJob, LocalJobKind, LocalJobScheduler};
11use serde::{Deserialize, Serialize};
12use sha2::{Digest, Sha256};
13use std::path::PathBuf;
14use std::time::{SystemTime, UNIX_EPOCH};
15
16pub const FLEET_JOB_FORMAT: &str = "qualia.fleet.job.v1";
17
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct FleetJobEnvelope {
20    pub format: String,
21    pub person_id: String,
22    pub person_verifying_key_hex: String,
23    pub source_device_id: String,
24    pub target_device_id: String,
25    pub kind: LocalJobKind,
26    pub created_at_unix: u64,
27    /// Hex-encoded Ed25519 signature over [`signing_payload`].
28    pub signature_hex: String,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct RemoteOutboxEntry {
33    pub id: String,
34    pub envelope: FleetJobEnvelope,
35    pub target_url: String,
36    pub attempts: u32,
37    pub last_error: Option<String>,
38    pub last_attempt_unix: u64,
39    pub created_at_unix: u64,
40    pub delivered: bool,
41}
42
43fn now_unix() -> u64 {
44    SystemTime::now()
45        .duration_since(UNIX_EPOCH)
46        .map(|d| d.as_secs())
47        .unwrap_or(0)
48}
49
50fn outbox_path() -> PathBuf {
51    crate::state::app_meta_dir().join("remote_job_outbox.json")
52}
53
54fn load_outbox() -> Vec<RemoteOutboxEntry> {
55    let path = outbox_path();
56    std::fs::read_to_string(path)
57        .ok()
58        .and_then(|s| serde_json::from_str(&s).ok())
59        .unwrap_or_default()
60}
61
62fn save_outbox(entries: &[RemoteOutboxEntry]) -> Result<(), String> {
63    let path = outbox_path();
64    if let Some(parent) = path.parent() {
65        std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
66    }
67    let json = serde_json::to_string_pretty(entries).map_err(|e| e.to_string())?;
68    std::fs::write(path, json).map_err(|e| e.to_string())
69}
70
71/// Canonical bytes signed by the person principal.
72pub fn signing_payload(
73    person_id: &str,
74    source_device_id: &str,
75    target_device_id: &str,
76    kind: &LocalJobKind,
77    created_at_unix: u64,
78) -> Result<Vec<u8>, String> {
79    let kind_json = serde_json::to_string(kind).map_err(|e| e.to_string())?;
80    let mut h = Sha256::new();
81    h.update(FLEET_JOB_FORMAT.as_bytes());
82    h.update(b"|");
83    h.update(person_id.as_bytes());
84    h.update(b"|");
85    h.update(source_device_id.as_bytes());
86    h.update(b"|");
87    h.update(target_device_id.as_bytes());
88    h.update(b"|");
89    h.update(created_at_unix.to_le_bytes());
90    h.update(b"|");
91    h.update(kind_json.as_bytes());
92    Ok(h.finalize().to_vec())
93}
94
95impl FleetJobEnvelope {
96    /// Builds.
97    pub fn build(
98        person: &PersonPrincipal,
99        source_device_id: &str,
100        target_device_id: &str,
101        kind: LocalJobKind,
102    ) -> Result<Self, String> {
103        let created_at_unix = now_unix();
104        let payload = signing_payload(
105            &person.person_id,
106            source_device_id,
107            target_device_id,
108            &kind,
109            created_at_unix,
110        )?;
111        let sig = person.sign_message(&payload);
112        Ok(Self {
113            format: FLEET_JOB_FORMAT.to_string(),
114            person_id: person.person_id.clone(),
115            person_verifying_key_hex: person.verifying_key_hex(),
116            source_device_id: source_device_id.to_string(),
117            target_device_id: target_device_id.to_string(),
118            kind,
119            created_at_unix,
120            signature_hex: hex::encode(sig),
121        })
122    }
123
124    /// Verifies.
125    pub fn verify(&self) -> Result<(), String> {
126        if self.format != FLEET_JOB_FORMAT {
127            return Err(format!("unsupported fleet job format: {}", self.format));
128        }
129        let payload = signing_payload(
130            &self.person_id,
131            &self.source_device_id,
132            &self.target_device_id,
133            &self.kind,
134            self.created_at_unix,
135        )?;
136        let sig_bytes = hex::decode(&self.signature_hex).map_err(|e| e.to_string())?;
137        if sig_bytes.len() != 64 {
138            return Err("signature must be 64 bytes".into());
139        }
140        let mut sig = [0u8; 64];
141        sig.copy_from_slice(&sig_bytes);
142        PersonPrincipal::verify_message(
143            &self.person_id,
144            &self.person_verifying_key_hex,
145            &payload,
146            &sig,
147        )
148    }
149}
150
151/// Deliver a job to a remote apparatus, or queue to outbox on failure.
152pub fn deliver_or_queue_remote_job(
153    kind: LocalJobKind,
154    target_device_id: &str,
155) -> Result<RemoteOutboxEntry, String> {
156    let plane = ensure_local_apparatus(None)?;
157    let placement = resolve_job_placement(Some(target_device_id))?;
158    let (device_id, label) = match placement {
159        JobPlacement::RemoteRegistered { device_id, label } => (device_id, label),
160        JobPlacement::Local { .. } => {
161            return Err("target is the local apparatus — use the local job queue".into());
162        }
163        JobPlacement::Unknown { device_id } => {
164            return Err(format!("unknown device {device_id}"));
165        }
166    };
167    let peer = plane
168        .devices
169        .iter()
170        .find(|d| d.device_id == device_id)
171        .ok_or("peer missing from fleet")?;
172    if peer.control_base_url.trim().is_empty() {
173        return Err(format!(
174            "Peer '{label}' has no control_base_url. On that machine, set a LAN URL (Settings → Person & devices) so jobs can be delivered."
175        ));
176    }
177    let person = PersonPrincipal::load_or_create(None)?;
178    let envelope = FleetJobEnvelope::build(&person, &plane.local_device_id, &device_id, kind)?;
179    let url = format!(
180        "{}/api/fleet/jobs",
181        peer.control_base_url.trim_end_matches('/')
182    );
183    let mut entry = RemoteOutboxEntry {
184        id: uuid::Uuid::new_v4().to_string(),
185        envelope: envelope.clone(),
186        target_url: url.clone(),
187        attempts: 0,
188        last_error: None,
189        last_attempt_unix: 0,
190        created_at_unix: now_unix(),
191        delivered: false,
192    };
193
194    match try_deliver(&url, &envelope) {
195        Ok(()) => {
196            entry.delivered = true;
197            entry.attempts = 1;
198            entry.last_attempt_unix = now_unix();
199        }
200        Err(e) => {
201            entry.attempts = 1;
202            entry.last_error = Some(e);
203            entry.last_attempt_unix = now_unix();
204            let mut box_ = load_outbox();
205            box_.push(entry.clone());
206            // Cap outbox
207            if box_.len() > 64 {
208                box_.retain(|e| !e.delivered);
209                if box_.len() > 64 {
210                    box_.drain(0..box_.len() - 64);
211                }
212            }
213            save_outbox(&box_)?;
214        }
215    }
216    if entry.delivered {
217        // Keep a short delivered audit trail
218        let mut box_ = load_outbox();
219        box_.push(entry.clone());
220        if box_.len() > 64 {
221            box_.drain(0..box_.len() - 64);
222        }
223        let _ = save_outbox(&box_);
224    }
225    Ok(entry)
226}
227
228fn try_deliver(url: &str, envelope: &FleetJobEnvelope) -> Result<(), String> {
229    let client = reqwest::blocking::Client::builder()
230        .timeout(std::time::Duration::from_secs(15))
231        .build()
232        .map_err(|e| e.to_string())?;
233    let resp = client
234        .post(url)
235        .json(envelope)
236        .send()
237        .map_err(|e| format!("fleet deliver: {e}"))?;
238    if !resp.status().is_success() {
239        let status = resp.status();
240        let body = resp.text().unwrap_or_default();
241        return Err(format!("fleet deliver HTTP {status}: {body}"));
242    }
243    Ok(())
244}
245
246/// Accept a signed fleet job on this apparatus (HTTP handler body).
247pub fn accept_fleet_job_envelope(envelope: FleetJobEnvelope) -> Result<LocalJob, String> {
248    envelope.verify()?;
249    let plane = ensure_local_apparatus(None)?;
250    if envelope.target_device_id != plane.local_device_id {
251        return Err(format!(
252            "job targets {} but this apparatus is {}",
253            envelope.target_device_id, plane.local_device_id
254        ));
255    }
256    // Same person principal required (imported on both machines).
257    if envelope.person_id != plane.person.person_id {
258        return Err(
259            "fleet job person_id does not match this install's person principal — import the same person transfer bundle on both machines"
260                .into(),
261        );
262    }
263    // Enqueue as local work; placement already verified as this apparatus.
264    let mut job = LocalJobScheduler::global()
265        .enqueue_for_device(envelope.kind, Some(plane.local_device_id.clone()))?;
266    job.originating_device_id = Some(envelope.source_device_id.clone());
267    job.person_id = Some(envelope.person_id.clone());
268    job.message = format!("Accepted from fleet peer {}", envelope.source_device_id);
269    LocalJobScheduler::global().update_job_meta(&job)?;
270    Ok(job)
271}
272
273/// Lists the remote outbox.
274pub fn list_remote_outbox() -> Result<Vec<RemoteOutboxEntry>, String> {
275    Ok(load_outbox())
276}
277
278/// Retry undelivered outbox entries (best-effort).
279pub fn retry_remote_outbox() -> Result<usize, String> {
280    let mut box_ = load_outbox();
281    let mut delivered = 0usize;
282    for entry in box_.iter_mut() {
283        if entry.delivered {
284            continue;
285        }
286        entry.attempts = entry.attempts.saturating_add(1);
287        entry.last_attempt_unix = now_unix();
288        match try_deliver(&entry.target_url, &entry.envelope) {
289            Ok(()) => {
290                entry.delivered = true;
291                entry.last_error = None;
292                delivered += 1;
293            }
294            Err(e) => entry.last_error = Some(e),
295        }
296    }
297    save_outbox(&box_)?;
298    Ok(delivered)
299}
300
301#[cfg(test)]
302mod tests {
303    use super::*;
304
305    #[test]
306    fn envelope_round_trip_verifies() {
307        let person = PersonPrincipal::generate("t").unwrap();
308        let kind = LocalJobKind::DaemonGraphReload;
309        let env = FleetJobEnvelope::build(&person, "did:q42:device:aa", "did:q42:device:bb", kind)
310            .unwrap();
311        env.verify().unwrap();
312        let mut bad = env.clone();
313        bad.signature_hex = "00".repeat(64);
314        assert!(bad.verify().is_err());
315    }
316}