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 self.capture(state);
265        }
266        let admitted = modules.map(|_| Self::declarations(state)).transpose()?;
267        let body = state.store.body()?;
268        let target = GateSnapshot::from_store(&body.approved)?;
269        let delivery = body
270            .generations
271            .get(&super::placement::last_approved_generation(body))
272            .and_then(|entry| entry.delivery.as_ref())
273            .ok_or_else(|| {
274                GateError::new(
275                    "approved_schema_unavailable",
276                    "approved layer documents are unavailable",
277                )
278            })?;
279        if let (Some(modules), Some(admitted)) = (modules, admitted) {
280            let mut declarations = delivery.declarations.clone();
281            for module in modules {
282                if declarations.contains_key(module) {
283                    if let Some(declaration) = admitted.get(module) {
284                        declarations.insert(module.clone(), declaration.clone());
285                    }
286                }
287            }
288            self.capturer
289                .capture_retained_declared(&target, delivery, &declarations)
290        } else {
291            self.capturer.capture_retained(&target, delivery)
292        }
293    }
294
295    pub(crate) fn prepare_edits(
296        &self,
297        base_generations: BTreeMap<String, u64>,
298        edits: Vec<ConfigEdit>,
299    ) -> Result<PreparedPlan> {
300        if edits.is_empty() {
301            return Err(invalid("edits must not be empty"));
302        }
303        let mut state = self.lock()?;
304        Self::check_authority(&mut state, false)?;
305        let unstamped = state.store.status().state == StoreState::Unstamped;
306        let touched: BTreeSet<_> = edits.iter().map(|edit| edit.module_id.clone()).collect();
307        let approved = self.edit_baseline(&mut state, None)?;
308        for module in &touched {
309            let wanted = base_generations
310                .get(module)
311                .ok_or_else(|| invalid("every touched module needs a base generation"))?;
312            let actual = crate::config_gate::module_base_generation(state.store.body()?, module);
313            if *wanted != actual {
314                return Err(GateError::new(
315                    "config_changed_since_review",
316                    "a touched module's approved generation changed",
317                ));
318            }
319        }
320        let mut bases = BTreeMap::new();
321        let mut base_schemas = BTreeMap::new();
322        for module in &touched {
323            if let Some(captured) = approved.modules.get(module) {
324                let mut view = captured.view.clone();
325                view.generation = base_generations[module];
326                bases.insert(module.clone(), view);
327                base_schemas.insert(module.clone(), captured.schema.clone());
328            }
329        }
330        let mut candidate = if unstamped {
331            approved
332        } else {
333            self.edit_baseline(&mut state, Some(&touched))?
334        };
335        let baseline = candidate.diagnostic.clone();
336        let mut refusals = Vec::new();
337        let mut accepted: BTreeMap<String, Vec<ConfigEdit>> = BTreeMap::new();
338        for edit in edits {
339            let result: Result<()> = (|| {
340                if edit.module_id == "subc" {
341                    return Err(GateError::new(
342                        "value_invalid",
343                        "daemon settings cannot be edited in this version",
344                    ));
345                }
346                if matches!(edit.layer.as_str(), "workspace" | "project") {
347                    return Err(GateError::new(
348                        "layer_not_served",
349                        "workspace and project settings are not served yet",
350                    ));
351                }
352                if edit.layer != "user" || edit.workspace_id.is_some() || edit.project_id.is_some()
353                {
354                    return Err(invalid("a user edit cannot select a workspace or project"));
355                }
356                let keys = pointer(&edit.path)?;
357                let captured = candidate.modules.get_mut(&edit.module_id).ok_or_else(|| {
358                    GateError::new(
359                        "unknown_module",
360                        "the module has no admitted settings schema",
361                    )
362                })?;
363                schema_path(
364                    captured.schema.normalized(),
365                    Some(&captured.view.effective),
366                    &keys,
367                )?;
368                let mut document = captured.file.parse()?;
369                patch(&mut document, &keys, &edit.action)?;
370                let reviewed = captured
371                    .schema
372                    .review_tuple(
373                        &[LayerValue::new(Layer::User, document.clone())],
374                        &ValidationContext::new(&edit.module_id, None),
375                    )
376                    .map_err(|refusal| {
377                        GateError::new(
378                            super::super::capture::refusal_code(refusal.code),
379                            "the edit is refused by the admitted schema",
380                        )
381                    })?;
382                let bytes = edit_text(captured.file.bytes.as_deref(), std::slice::from_ref(&edit))?;
383                if captured.file.bytes.as_deref() != Some(bytes.as_slice()) {
384                    captured.file.state = InputState::Present {
385                        digest: subc_config::raw_digest(&bytes),
386                    };
387                }
388                captured.file.bytes = Some(bytes.clone());
389                captured.view = ConfigView::new(
390                    0,
391                    reviewed.effective,
392                    reviewed.sources,
393                    vec![ConfigLayerSnapshot::file(
394                        &edit.module_id,
395                        subc_protocol::config::ConfigLayer::User,
396                        captured.file.path.to_string_lossy(),
397                        Some(bytes),
398                    )],
399                    ConfigStatus::Pending,
400                );
401                let input = candidate
402                    .diagnostic
403                    .inputs
404                    .get_mut(&InputKey::Layer {
405                        module: edit.module_id.clone(),
406                        path: captured.file.path.to_string_lossy().into_owned(),
407                    })
408                    .ok_or_else(|| invalid("approved layer input is absent"))?;
409                input.state = captured.file.state.clone();
410                input.value = RecordedValue::new(
411                    captured
412                        .schema
413                        .record(&document)
414                        .map_err(GateError::invalid)?,
415                );
416                Ok(())
417            })();
418            match result {
419                Ok(()) => accepted
420                    .entry(edit.module_id.clone())
421                    .or_default()
422                    .push(edit),
423                Err(error) => refusals.push(refused(&edit, &error.code, &error.detail)),
424            }
425        }
426        let mut files = Vec::new();
427        let mut observed_handles = Vec::new();
428        for (module, _) in accepted {
429            let captured = &candidate.modules[&module];
430            let mut disk = CapturedFile::open(&captured.file.path)?;
431            // Never sweep an unrelated dirty file value into an approved edit.
432            // If it differs from the baseline, retain the approval but leave reconciliation pending.
433            let base = bases[&module].layers[0].bytes.as_deref();
434            let skipped = disk.bytes.as_deref() != base;
435            let bytes = captured.file.bytes.clone().unwrap_or_default();
436            files.push(WriteBack {
437                module,
438                path: disk.path.clone(),
439                expected: disk.state.clone(),
440                bytes,
441                plan_time_digest: disk.bytes.as_deref().map(subc_config::raw_digest),
442                skipped,
443            });
444            observed_handles.append(&mut disk.take_handles());
445        }
446        let active_generations = if unstamped {
447            BTreeMap::new()
448        } else {
449            state
450                .store
451                .body()?
452                .versions
453                .iter()
454                .filter(|(tuple, _)| touched.contains(&tuple.module))
455                .map(|(tuple, versions)| (tuple.clone(), versions.active))
456                .collect()
457        };
458        let read_set = baseline.read_set(&touched)?;
459        let program_keys = baseline
460            .inputs
461            .keys()
462            .filter(|key| {
463                key.is_program() && key.module().is_some_and(|module| touched.contains(module))
464            })
465            .cloned()
466            .collect();
467        let review_modules = touched
468            .iter()
469            .filter(|module| candidate.modules.contains_key(*module))
470            .cloned()
471            .collect();
472        Ok(PreparedPlan {
473            candidate,
474            bases,
475            base_schemas,
476            kind: PlanKind::Change,
477            review_modules,
478            rereview_modules: BTreeSet::new(),
479            base_revision: state.store.status().base_revision,
480            active_generations,
481            touched_modules: touched,
482            read_set,
483            program_keys,
484            observed_handles,
485            edits: Some(EditPlan {
486                baseline,
487                unstamped,
488                refusals,
489                files,
490            }),
491        })
492    }
493}
494
495fn edit_text(bytes: Option<&[u8]>, edits: &[ConfigEdit]) -> Result<Vec<u8>> {
496    let mut text = match bytes {
497        Some(bytes) => std::str::from_utf8(bytes)
498            .map_err(|_| invalid("invalid UTF-8"))?
499            .to_owned(),
500        None => "{}\n".to_owned(),
501    };
502    for edit in edits {
503        let keys = pointer(&edit.path)?;
504        let path: Vec<_> = keys.iter().map(String::as_str).collect();
505        match &edit.action {
506            ConfigEditAction::Set { set } => subc_jsonc::set_member(&mut text, &path, set),
507            ConfigEditAction::Remove { .. } => {
508                subc_jsonc::remove_member(&mut text, &path).map(|_| ())
509            }
510        }
511        .map_err(|_| invalid("the layer document cannot be safely edited at this pointer"))?;
512    }
513    Ok(text.into_bytes())
514}
515
516impl WriteBack {
517    fn unchanged(&self) -> Result<()> {
518        if CapturedFile::open(&self.path)?.state != self.expected {
519            return Err(GateError::new(
520                "config_changed_since_review",
521                "the user file changed since planning",
522            ));
523        }
524        Ok(())
525    }
526
527    /// Use the daemon's normal atomic replacement for user-layer files. It
528    /// keeps the file's mode, but not explicit ACLs or extended attributes.
529    /// Repository layers need retained ancestor handles and an ACL-preserving
530    /// replacement before their write-back can be supported.
531    pub(super) fn write_back(&self) -> Result<()> {
532        use std::io::Write;
533        self.unchanged()?;
534        if self.skipped {
535            return Err(GateError::new(
536                "file_has_unapplied_edits",
537                "the user file contains unapproved edits",
538            ));
539        }
540        let parent = self
541            .path
542            .parent()
543            .ok_or_else(|| invalid("a user file needs a parent"))?;
544        let mut nonce = [0u8; 16];
545        getrandom::getrandom(&mut nonce).map_err(|_| {
546            GateError::new("config_unavailable", "could not allocate a temporary file")
547        })?;
548        let name: String = nonce.iter().map(|byte| format!("{byte:02x}")).collect();
549        let temporary = parent.join(format!(".config-{name}.tmp"));
550        let result = (|| {
551            let mut options = std::fs::OpenOptions::new();
552            options.create_new(true).write(true);
553            #[cfg(unix)]
554            {
555                use std::os::unix::fs::OpenOptionsExt;
556                options.mode(0o600);
557            }
558            let mut file = options
559                .open(&temporary)
560                .map_err(|_| invalid("could not create the replacement file"))?;
561            if let Ok(metadata) = std::fs::metadata(&self.path) {
562                file.set_permissions(metadata.permissions())
563                    .map_err(|_| invalid("could not preserve file permissions"))?;
564            }
565            file.write_all(&self.bytes)
566                .and_then(|_| file.sync_all())
567                .map_err(|_| invalid("could not flush the replacement file"))?;
568            drop(file);
569            self.unchanged()?;
570            subc_os::durable_replace(&temporary, &self.path)
571                .map_err(|_| invalid("could not atomically replace the user file"))
572        })();
573        if result.is_err() {
574            let _ = std::fs::remove_file(&temporary);
575        }
576        result
577    }
578}
579
580impl RuntimeOwner {
581    pub(crate) fn plan_get(&self, digest: &Digest) -> Result<ConfigPlanView> {
582        let mut state = self.lock()?;
583        let base_revision = state.store.status().base_revision;
584        let plan = state
585            .gate
586            .plans
587            .get(digest)
588            .ok_or_else(|| GateError::new("unknown_plan", "the plan is no longer pending"))?;
589        if base_revision != plan.view.base_revision {
590            return Err(GateError::new(
591                "unknown_plan",
592                "the plan has been superseded",
593            ));
594        }
595        Ok(plan.view.clone())
596    }
597
598    pub(crate) fn plan_discard(&self, digest: &Digest) -> Result<()> {
599        let mut state = self.lock()?;
600        let base_revision = state.store.status().base_revision;
601        if !state
602            .gate
603            .plans
604            .get(digest)
605            .is_some_and(|plan| plan.view.base_revision == base_revision)
606        {
607            return Err(GateError::new(
608                "unknown_plan",
609                "the plan is no longer pending",
610            ));
611        }
612        if state.gate.has_open_approval(digest) {
613            return Err(GateError::new(
614                "plan_in_review",
615                "the plan is being approved",
616            ));
617        }
618        state.gate.expire_plan(digest);
619        state.plan_deadlines.remove(digest);
620        state.retained_plan_files.remove(digest);
621        state.desktop_views.retain(|_, (shown, _)| shown != digest);
622        Ok(())
623    }
624
625    /// Returns generation zero only for unstamped edit plans. No approval or
626    /// approved-store write takes place while files remain authoritative.
627    pub(crate) fn apply_unstamped_edits(&self, digest: &Digest) -> Result<Option<u64>> {
628        let mut state = self.lock()?;
629        let Some(plan) = state.gate.plans.get(digest) else {
630            return Ok(None);
631        };
632        if plan.edits.is_none() {
633            return Ok(None);
634        }
635        if !plan.view.refusals.is_empty() {
636            return Err(GateError::new(
637                "plan_refused",
638                "the plan contains refused edits",
639            ));
640        }
641        let Some(edit) = plan.edits.as_ref().filter(|edit| edit.unstamped).cloned() else {
642            return Ok(None);
643        };
644        let base_revision = plan.view.base_revision;
645        Self::check_authority(&mut state, false)?;
646        let status = state.store.status();
647        if status.state != StoreState::Unstamped || status.base_revision != base_revision {
648            return Err(GateError::new(
649                "config_changed_since_review",
650                "configuration authority changed since planning",
651            ));
652        }
653        for file in &edit.files {
654            file.unchanged()?;
655        }
656        for file in &edit.files {
657            file.write_back()?;
658        }
659        state.gate.expire_plan(digest);
660        state.plan_deadlines.remove(digest);
661        state.retained_plan_files.remove(digest);
662        self.notify_delivery_changed();
663        Ok(Some(0))
664    }
665}
666
667impl PreparedPlan {
668    pub(crate) fn is_edit_plan(&self) -> bool {
669        self.edits.is_some()
670    }
671    pub(crate) fn add_edit_refusals(&mut self, refusals: Vec<ConfigPlanRefusal>) {
672        if let Some(edits) = &mut self.edits {
673            edits.refusals.extend(refusals);
674        }
675    }
676}
677
678impl PreparedPlan {
679    pub(crate) fn refused_fields(&self, module: &str) -> Result<Vec<subc_config::FieldChange>> {
680        let candidate = self.candidate.modules.get(module).ok_or_else(|| {
681            GateError::new(
682                "unknown_module",
683                "the module has no admitted settings schema",
684            )
685        })?;
686        super::super::review::expected_fields(
687            module,
688            &candidate.schema,
689            self.bases.get(module),
690            self.base_schemas.get(module),
691            &candidate.view,
692        )
693        .map(|fields| fields.into_values().collect())
694    }
695}