Skip to main content

subc_daemon/config_gate/
edits.rs

1//! User-layer edits use approved documents when stamped and active files otherwise.
2
3use super::super::{capture::CapturedFile, GateSnapshot, InputKey};
4use super::*;
5use serde_json::{json, Value};
6use std::collections::{BTreeMap, BTreeSet};
7use subc_config::{Digest, InputState, Layer, LayerValue, RecordedValue, ValidationContext};
8use subc_control::config::{ConfigEdit, ConfigEditAction, ConfigPlanRefusal, ConfigPlanView};
9use subc_protocol::config::{ConfigLayerSnapshot, ConfigStatus, ConfigView};
10
11#[derive(Clone)]
12pub(crate) struct EditPlan {
13    pub baseline: GateSnapshot,
14    pub unstamped: bool,
15    pub refusals: Vec<ConfigPlanRefusal>,
16    pub files: Vec<WriteBack>,
17}
18
19#[derive(Clone)]
20pub(crate) struct WriteBack {
21    pub module: String,
22    pub path: std::path::PathBuf,
23    pub expected: InputState,
24    pub bytes: Vec<u8>,
25    pub plan_time_digest: Option<Digest>,
26    pub skipped: bool,
27}
28
29#[derive(serde::Serialize, serde::Deserialize)]
30pub(crate) struct WriteBackIntent {
31    pub module_id: String,
32    pub path: std::path::PathBuf,
33    pub expected: InputState,
34    pub plan_time_digest: Option<Digest>,
35    pub candidate_digest: Digest,
36    #[serde(default, skip_serializing_if = "Option::is_none")]
37    pub note: Option<String>,
38}
39
40impl WriteBack {
41    pub(crate) fn intent(&self) -> WriteBackIntent {
42        WriteBackIntent {
43            module_id: self.module.clone(),
44            path: self.path.clone(),
45            expected: self.expected.clone(),
46            plan_time_digest: self.plan_time_digest.clone(),
47            candidate_digest: subc_config::raw_digest(&self.bytes),
48            note: self
49                .skipped
50                .then(|| "the file has edits that aren't approved yet".into()),
51        }
52    }
53}
54
55fn invalid(message: &str) -> GateError {
56    GateError::new("invalid_params", message)
57}
58fn refused(edit: &ConfigEdit, code: &str, message: &str) -> ConfigPlanRefusal {
59    ConfigPlanRefusal {
60        module_id: edit.module_id.clone(),
61        path: edit.path.clone(),
62        code: code.into(),
63        message: message.into(),
64        project_id: None,
65        workspace_id: None,
66    }
67}
68
69pub(super) fn pointer(path: &str) -> Result<Vec<String>> {
70    if !path.starts_with('/') {
71        return Err(invalid(
72            "an edit path must name an object key with a JSON pointer",
73        ));
74    }
75    path[1..]
76        .split('/')
77        .map(|part| {
78            let mut chars = part.chars();
79            let mut key = String::new();
80            while let Some(c) = chars.next() {
81                if c != '~' {
82                    key.push(c);
83                    continue;
84                }
85                match chars.next() {
86                    Some('0') => key.push('~'),
87                    Some('1') => key.push('/'),
88                    _ => return Err(invalid("invalid JSON pointer escape")),
89                }
90            }
91            Ok(key)
92        })
93        .collect()
94}
95
96fn patch(document: &mut Value, keys: &[String], action: &ConfigEditAction) -> Result<()> {
97    let (key, parents) = keys
98        .split_last()
99        .ok_or_else(|| invalid("an edit must name a key"))?;
100    let mut object = document;
101    for parent in parents {
102        let map = object
103            .as_object_mut()
104            .ok_or_else(|| invalid("arrays must be set whole; a parent must be an object"))?;
105        if !map.contains_key(parent) {
106            if matches!(action, ConfigEditAction::Remove { .. }) {
107                return Ok(());
108            }
109            map.insert(parent.clone(), json!({}));
110        }
111        object = map.get_mut(parent).expect("parent exists");
112    }
113    let map = object
114        .as_object_mut()
115        .ok_or_else(|| invalid("arrays must be set whole; a parent must be an object"))?;
116    match action {
117        ConfigEditAction::Set { set } => {
118            map.insert(key.clone(), set.clone());
119        }
120        ConfigEditAction::Remove { remove: true } => {
121            map.remove(key);
122        }
123        _ => return Err(invalid("remove must be true")),
124    }
125    Ok(())
126}
127
128fn schema_path<'a>(
129    mut schema: &'a Value,
130    mut effective: Option<&Value>,
131    keys: &[String],
132) -> Result<&'a Value> {
133    for key in keys {
134        if schema.get("type").and_then(Value::as_str) == Some("array") {
135            return Err(invalid("arrays must be set whole"));
136        }
137        if let Some(branches) = schema.get("oneOf").and_then(Value::as_array) {
138            schema = branches
139                .iter()
140                .find(|branch| {
141                    branch
142                        .get("properties")
143                        .and_then(Value::as_object)
144                        .is_some_and(|properties| {
145                            properties.iter().any(|(name, property)| {
146                                property.get("const").is_some_and(|tag| {
147                                    effective.and_then(|value| value.get(name)) == Some(tag)
148                                })
149                            })
150                        })
151                })
152                .ok_or_else(|| {
153                    GateError::new("value_invalid", "the path has no selected schema variant")
154                })?;
155        }
156        schema = schema
157            .get("properties")
158            .and_then(|properties| properties.get(key))
159            .or_else(|| {
160                schema
161                    .get("additionalProperties")
162                    .filter(|value| value.is_object())
163            })
164            .ok_or_else(|| {
165                GateError::new(
166                    "value_invalid",
167                    "the path is not declared by the admitted schema",
168                )
169            })?;
170        effective = effective.and_then(|value| value.get(key));
171        if schema
172            .get("x-ck-layers")
173            .and_then(Value::as_array)
174            .is_some_and(|layers| !layers.iter().any(|layer| layer == "user"))
175        {
176            return Err(GateError::new(
177                "layer_forbidden",
178                "the field does not allow the user layer",
179            ));
180        }
181    }
182    Ok(schema)
183}
184
185impl RuntimeOwner {
186    pub fn write_back_status(&self) -> Result<BTreeMap<String, String>> {
187        let mut state = self.lock()?;
188        state.check_authority_for_read()?;
189        if state.store_read(ConfigStore::status).state != StoreState::Stamped {
190            return Ok(BTreeMap::new());
191        }
192        let body = state.checked_body()?;
193        let entry = body
194            .generations
195            .get(&super::placement::last_approved_generation(body));
196        let Some(entry) = entry else {
197            return Ok(BTreeMap::new());
198        };
199        let Some(intents) = entry
200            .generation
201            .changeset
202            .apply_plan
203            .pointer("/edit_plan/write_back")
204        else {
205            return Ok(BTreeMap::new());
206        };
207        let intents: Vec<WriteBackIntent> =
208            serde_json::from_value(intents.clone()).map_err(|_| {
209                GateError::new(
210                    "config_unavailable",
211                    "approved write-back intents are invalid",
212                )
213            })?;
214        let mut behind = BTreeMap::new();
215        for intent in intents {
216            let disk = CapturedFile::open(&intent.path);
217            let raw = disk
218                .as_ref()
219                .ok()
220                .and_then(|file| file.bytes.as_deref())
221                .map(subc_config::raw_digest);
222            if raw.as_ref() == Some(&intent.candidate_digest) {
223                continue;
224            }
225            let reason = if let Some(note) = intent.note {
226                note
227            } else if disk.is_ok() && raw == intent.plan_time_digest {
228                let bytes = entry
229                    .delivery
230                    .as_ref()
231                    .and_then(|delivery| delivery.modules.get(&intent.module_id))
232                    .and_then(|view| view.layers.first())
233                    .and_then(|layer| layer.bytes.clone());
234                if let Some(bytes) =
235                    bytes.filter(|bytes| subc_config::raw_digest(bytes) == intent.candidate_digest)
236                {
237                    let file = WriteBack {
238                        module: intent.module_id.clone(),
239                        path: intent.path,
240                        expected: intent.expected,
241                        bytes,
242                        plan_time_digest: intent.plan_time_digest,
243                        skipped: false,
244                    };
245                    if file.write_back().is_ok() {
246                        continue;
247                    }
248                }
249                "the approved settings could not be safely written back".into()
250            } else {
251                "the file changed after this was approved".into()
252            };
253            behind.insert(intent.module_id, reason);
254        }
255        Ok(behind)
256    }
257
258    pub(super) fn edit_baseline(
259        &self,
260        state: &mut OwnerState,
261        modules: Option<&BTreeSet<String>>,
262    ) -> Result<CapturedConfiguration> {
263        if state.store.status().state == StoreState::Unstamped {
264            return match modules {
265                Some(modules) => self.capture_modules(state, modules),
266                None => self.capture(state),
267            };
268        }
269        let admitted = modules.map(|_| Self::declarations(state)).transpose()?;
270        let body = state.store.body()?;
271        let target = GateSnapshot::from_store(&body.approved)?;
272        let delivery = body
273            .generations
274            .get(&super::placement::last_approved_generation(body))
275            .and_then(|entry| entry.delivery.as_ref())
276            .ok_or_else(|| {
277                GateError::new(
278                    "approved_schema_unavailable",
279                    "approved layer documents are unavailable",
280                )
281            })?;
282        if let (Some(modules), Some(admitted)) = (modules, admitted) {
283            let mut declarations = delivery.declarations.clone();
284            for module in modules {
285                if declarations.contains_key(module) {
286                    if let Some(declaration) = admitted.get(module) {
287                        declarations.insert(module.clone(), declaration.clone());
288                    }
289                }
290            }
291            self.capturer
292                .capture_retained_declared(&target, delivery, &declarations)
293        } else {
294            self.capturer.capture_retained(&target, delivery)
295        }
296    }
297
298    pub(crate) fn prepare_edits(
299        &self,
300        base_generations: BTreeMap<String, u64>,
301        edits: Vec<ConfigEdit>,
302    ) -> Result<PreparedPlan> {
303        if edits.is_empty() {
304            return Err(invalid("edits must not be empty"));
305        }
306        let mut state = self.lock()?;
307        Self::check_authority(&mut state, false)?;
308        let unstamped = state.store.status().state == StoreState::Unstamped;
309        let touched: BTreeSet<_> = edits.iter().map(|edit| edit.module_id.clone()).collect();
310        let approved = self.edit_baseline(&mut state, unstamped.then_some(&touched))?;
311        for module in &touched {
312            let wanted = base_generations
313                .get(module)
314                .ok_or_else(|| invalid("every touched module needs a base generation"))?;
315            let actual = crate::config_gate::module_base_generation(state.store.body()?, module);
316            if *wanted != actual {
317                return Err(GateError::new(
318                    "config_changed_since_review",
319                    "a touched module's approved generation changed",
320                ));
321            }
322        }
323        let mut bases = BTreeMap::new();
324        let mut base_schemas = BTreeMap::new();
325        for module in &touched {
326            if let Some(captured) = approved.modules.get(module) {
327                let mut view = captured.view.clone();
328                view.generation = base_generations[module];
329                bases.insert(module.clone(), view);
330                base_schemas.insert(module.clone(), captured.schema.clone());
331            }
332        }
333        let mut candidate = if unstamped {
334            approved
335        } else {
336            self.edit_baseline(&mut state, Some(&touched))?
337        };
338        let baseline = candidate.diagnostic.clone();
339        let mut refusals = Vec::new();
340        let mut accepted: BTreeMap<String, Vec<ConfigEdit>> = BTreeMap::new();
341        for edit in edits {
342            let result: Result<()> = (|| {
343                if edit.module_id == "subc" {
344                    return Err(GateError::new(
345                        "value_invalid",
346                        "daemon settings cannot be edited in this version",
347                    ));
348                }
349                if matches!(edit.layer.as_str(), "workspace" | "project") {
350                    return Err(GateError::new(
351                        "layer_not_served",
352                        "workspace and project settings are not served yet",
353                    ));
354                }
355                if edit.layer != "user" || edit.workspace_id.is_some() || edit.project_id.is_some()
356                {
357                    return Err(invalid("a user edit cannot select a workspace or project"));
358                }
359                let keys = pointer(&edit.path)?;
360                let captured = candidate.modules.get_mut(&edit.module_id).ok_or_else(|| {
361                    GateError::new(
362                        "unknown_module",
363                        "the module has no admitted settings schema",
364                    )
365                })?;
366                schema_path(
367                    captured.schema.normalized(),
368                    Some(&captured.view.effective),
369                    &keys,
370                )?;
371                let mut document = captured.file.parse()?;
372                patch(&mut document, &keys, &edit.action)?;
373                crate::config_gate::strict_json::check_canonical(&document, "")?;
374                let reviewed = captured
375                    .schema
376                    .review_tuple(
377                        &[LayerValue::new(Layer::User, document.clone())],
378                        &ValidationContext::new(&edit.module_id, None),
379                    )
380                    .map_err(|refusal| {
381                        GateError::new(
382                            super::super::capture::refusal_code(refusal.code),
383                            "the edit is refused by the admitted schema",
384                        )
385                    })?;
386                let bytes = edit_text(captured.file.bytes.as_deref(), std::slice::from_ref(&edit))?;
387                if captured.file.bytes.as_deref() != Some(bytes.as_slice()) {
388                    captured.file.state = InputState::Present {
389                        digest: subc_config::raw_digest(&bytes),
390                    };
391                }
392                captured.file.bytes = Some(bytes.clone());
393                captured.view = ConfigView::new(
394                    0,
395                    reviewed.effective,
396                    reviewed.sources,
397                    vec![ConfigLayerSnapshot::file(
398                        &edit.module_id,
399                        subc_protocol::config::ConfigLayer::User,
400                        captured.file.path.to_string_lossy(),
401                        Some(bytes),
402                    )],
403                    ConfigStatus::Pending,
404                );
405                let input = candidate
406                    .diagnostic
407                    .inputs
408                    .get_mut(&InputKey::Layer {
409                        module: edit.module_id.clone(),
410                        path: captured.file.path.to_string_lossy().into_owned(),
411                    })
412                    .ok_or_else(|| invalid("approved layer input is absent"))?;
413                input.state = captured.file.state.clone();
414                input.value = RecordedValue::new(
415                    captured
416                        .schema
417                        .record(&document)
418                        .map_err(GateError::invalid)?,
419                );
420                Ok(())
421            })();
422            match result {
423                Ok(()) => accepted
424                    .entry(edit.module_id.clone())
425                    .or_default()
426                    .push(edit),
427                Err(error) => refusals.push(refused(&edit, &error.code, &error.detail)),
428            }
429        }
430        let mut files = Vec::new();
431        let mut observed_handles = Vec::new();
432        for (module, _) in accepted {
433            let captured = &candidate.modules[&module];
434            let mut disk = CapturedFile::open(&captured.file.path)?;
435            // Never sweep an unrelated dirty file value into an approved edit.
436            // If it differs from the baseline, retain the approval but leave reconciliation pending.
437            let base = bases[&module].layers[0].bytes.as_deref();
438            let skipped = disk.bytes.as_deref() != base;
439            let bytes = captured.file.bytes.clone().unwrap_or_default();
440            files.push(WriteBack {
441                module,
442                path: disk.path.clone(),
443                expected: disk.state.clone(),
444                bytes,
445                plan_time_digest: disk.bytes.as_deref().map(subc_config::raw_digest),
446                skipped,
447            });
448            observed_handles.append(&mut disk.take_handles());
449        }
450        let active_generations = if unstamped {
451            BTreeMap::new()
452        } else {
453            state
454                .store
455                .body()?
456                .versions
457                .iter()
458                .filter(|(tuple, _)| touched.contains(&tuple.module))
459                .map(|(tuple, versions)| (tuple.clone(), versions.active))
460                .collect()
461        };
462        let read_set = baseline.read_set(&touched)?;
463        let program_keys = baseline
464            .inputs
465            .keys()
466            .filter(|key| {
467                key.is_program() && key.module().is_some_and(|module| touched.contains(module))
468            })
469            .cloned()
470            .collect();
471        let review_modules = touched
472            .iter()
473            .filter(|module| candidate.modules.contains_key(*module))
474            .cloned()
475            .collect();
476        Ok(PreparedPlan {
477            projects: None,
478            candidate,
479            bases,
480            base_schemas,
481            kind: PlanKind::Change,
482            review_modules,
483            rereview_modules: BTreeSet::new(),
484            base_revision: state.store.status().base_revision,
485            active_generations,
486            touched_modules: touched,
487            read_set,
488            program_keys,
489            observed_handles,
490            edits: Some(EditPlan {
491                baseline,
492                unstamped,
493                refusals,
494                files,
495            }),
496        })
497    }
498}
499
500fn edit_text(bytes: Option<&[u8]>, edits: &[ConfigEdit]) -> Result<Vec<u8>> {
501    let mut text = match bytes {
502        Some(bytes) => std::str::from_utf8(bytes)
503            .map_err(|_| invalid("invalid UTF-8"))?
504            .to_owned(),
505        None => "{}\n".to_owned(),
506    };
507    for edit in edits {
508        let keys = pointer(&edit.path)?;
509        let path: Vec<_> = keys.iter().map(String::as_str).collect();
510        match &edit.action {
511            ConfigEditAction::Set { set } => subc_jsonc::set_member(&mut text, &path, set),
512            ConfigEditAction::Remove { .. } => {
513                subc_jsonc::remove_member(&mut text, &path).map(|_| ())
514            }
515        }
516        .map_err(|_| invalid("the layer document cannot be safely edited at this pointer"))?;
517    }
518    Ok(text.into_bytes())
519}
520
521impl WriteBack {
522    fn unchanged(&self) -> Result<()> {
523        if CapturedFile::open(&self.path)?.state != self.expected {
524            return Err(GateError::new(
525                "config_changed_since_review",
526                "the user file changed since planning",
527            ));
528        }
529        Ok(())
530    }
531
532    /// Use the daemon's normal atomic replacement for user-layer files. It
533    /// keeps the file's mode, but not explicit ACLs or extended attributes.
534    /// Repository layers need retained ancestor handles and an ACL-preserving
535    /// replacement before their write-back can be supported.
536    pub(super) fn write_back(&self) -> Result<()> {
537        use std::io::Write;
538        self.unchanged()?;
539        if self.skipped {
540            return Err(GateError::new(
541                "file_has_unapplied_edits",
542                "the user file contains unapproved edits",
543            ));
544        }
545        let parent = self
546            .path
547            .parent()
548            .ok_or_else(|| invalid("a user file needs a parent"))?;
549        let mut nonce = [0u8; 16];
550        getrandom::getrandom(&mut nonce).map_err(|_| {
551            GateError::new("config_unavailable", "could not allocate a temporary file")
552        })?;
553        let name: String = nonce.iter().map(|byte| format!("{byte:02x}")).collect();
554        let temporary = parent.join(format!(".config-{name}.tmp"));
555        let result = (|| {
556            let mut options = std::fs::OpenOptions::new();
557            options.create_new(true).write(true);
558            #[cfg(unix)]
559            {
560                use std::os::unix::fs::OpenOptionsExt;
561                options.mode(0o600);
562            }
563            let mut file = options
564                .open(&temporary)
565                .map_err(|_| invalid("could not create the replacement file"))?;
566            if let Ok(metadata) = std::fs::metadata(&self.path) {
567                file.set_permissions(metadata.permissions())
568                    .map_err(|_| invalid("could not preserve file permissions"))?;
569            }
570            file.write_all(&self.bytes)
571                .and_then(|_| file.sync_all())
572                .map_err(|_| invalid("could not flush the replacement file"))?;
573            drop(file);
574            self.unchanged()?;
575            subc_os::durable_replace(&temporary, &self.path)
576                .map_err(|_| invalid("could not atomically replace the user file"))
577        })();
578        if result.is_err() {
579            let _ = std::fs::remove_file(&temporary);
580        }
581        result
582    }
583}
584
585impl RuntimeOwner {
586    pub(crate) fn plan_get(&self, digest: &Digest) -> Result<ConfigPlanView> {
587        let mut state = self.lock()?;
588        let base_revision = state.store.status().base_revision;
589        let plan = state
590            .gate
591            .plans
592            .get(digest)
593            .ok_or_else(|| GateError::new("unknown_plan", "the plan is no longer pending"))?;
594        if base_revision != plan.view.base_revision {
595            return Err(GateError::new(
596                "unknown_plan",
597                "the plan has been superseded",
598            ));
599        }
600        Ok(plan.view.clone())
601    }
602
603    pub(crate) fn plan_discard(&self, digest: &Digest) -> Result<()> {
604        let mut state = self.lock()?;
605        let base_revision = state.store.status().base_revision;
606        if !state
607            .gate
608            .plans
609            .get(digest)
610            .is_some_and(|plan| plan.view.base_revision == base_revision)
611        {
612            return Err(GateError::new(
613                "unknown_plan",
614                "the plan is no longer pending",
615            ));
616        }
617        if state.gate.has_open_approval(digest) {
618            return Err(GateError::new(
619                "plan_in_review",
620                "the plan is being approved",
621            ));
622        }
623        state.gate.expire_plan(digest);
624        state.plan_deadlines.remove(digest);
625        state.retained_plan_files.remove(digest);
626        state.desktop_views.retain(|_, (shown, _)| shown != digest);
627        Ok(())
628    }
629
630    /// Returns generation zero only for unstamped edit plans. No approval or
631    /// approved-store write takes place while files remain authoritative.
632    pub(crate) fn apply_unstamped_edits(&self, digest: &Digest) -> Result<Option<u64>> {
633        let mut state = self.lock()?;
634        let Some(plan) = state.gate.plans.get(digest) else {
635            return Ok(None);
636        };
637        if plan.edits.is_none() {
638            return Ok(None);
639        }
640        if !plan.view.refusals.is_empty() {
641            return Err(GateError::new(
642                "plan_refused",
643                "the plan contains refused edits",
644            ));
645        }
646        let Some(edit) = plan.edits.as_ref().filter(|edit| edit.unstamped).cloned() else {
647            return Ok(None);
648        };
649        let base_revision = plan.view.base_revision;
650        Self::check_authority(&mut state, false)?;
651        let status = state.store.status();
652        if status.state != StoreState::Unstamped || status.base_revision != base_revision {
653            return Err(GateError::new(
654                "config_changed_since_review",
655                "configuration authority changed since planning",
656            ));
657        }
658        for file in &edit.files {
659            file.unchanged()?;
660        }
661        for file in &edit.files {
662            file.write_back()?;
663        }
664        state.gate.expire_plan(digest);
665        state.plan_deadlines.remove(digest);
666        state.retained_plan_files.remove(digest);
667        self.notify_delivery_changed();
668        Ok(Some(0))
669    }
670}
671
672impl PreparedPlan {
673    pub(crate) fn is_edit_plan(&self) -> bool {
674        self.edits.is_some()
675    }
676    pub(crate) fn add_edit_refusals(&mut self, refusals: Vec<ConfigPlanRefusal>) {
677        if let Some(edits) = &mut self.edits {
678            edits.refusals.extend(refusals);
679        }
680    }
681}
682
683impl PreparedPlan {
684    pub(crate) fn refused_fields(&self, module: &str) -> Result<Vec<subc_config::FieldChange>> {
685        let candidate = self.candidate.modules.get(module).ok_or_else(|| {
686            GateError::new(
687                "unknown_module",
688                "the module has no admitted settings schema",
689            )
690        })?;
691        super::super::review::expected_fields(
692            module,
693            &candidate.schema,
694            self.bases.get(module),
695            self.base_schemas.get(module),
696            &candidate.view,
697        )
698        .map(|fields| fields.into_values().collect())
699    }
700}