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