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 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 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 candidate,
478 bases,
479 base_schemas,
480 kind: PlanKind::Change,
481 review_modules,
482 rereview_modules: BTreeSet::new(),
483 base_revision: state.store.status().base_revision,
484 active_generations,
485 touched_modules: touched,
486 read_set,
487 program_keys,
488 observed_handles,
489 edits: Some(EditPlan {
490 baseline,
491 unstamped,
492 refusals,
493 files,
494 }),
495 })
496 }
497}
498
499fn edit_text(bytes: Option<&[u8]>, edits: &[ConfigEdit]) -> Result<Vec<u8>> {
500 let mut text = match bytes {
501 Some(bytes) => std::str::from_utf8(bytes)
502 .map_err(|_| invalid("invalid UTF-8"))?
503 .to_owned(),
504 None => "{}\n".to_owned(),
505 };
506 for edit in edits {
507 let keys = pointer(&edit.path)?;
508 let path: Vec<_> = keys.iter().map(String::as_str).collect();
509 match &edit.action {
510 ConfigEditAction::Set { set } => subc_jsonc::set_member(&mut text, &path, set),
511 ConfigEditAction::Remove { .. } => {
512 subc_jsonc::remove_member(&mut text, &path).map(|_| ())
513 }
514 }
515 .map_err(|_| invalid("the layer document cannot be safely edited at this pointer"))?;
516 }
517 Ok(text.into_bytes())
518}
519
520impl WriteBack {
521 fn unchanged(&self) -> Result<()> {
522 if CapturedFile::open(&self.path)?.state != self.expected {
523 return Err(GateError::new(
524 "config_changed_since_review",
525 "the user file changed since planning",
526 ));
527 }
528 Ok(())
529 }
530
531 pub(super) fn write_back(&self) -> Result<()> {
536 use std::io::Write;
537 self.unchanged()?;
538 if self.skipped {
539 return Err(GateError::new(
540 "file_has_unapplied_edits",
541 "the user file contains unapproved edits",
542 ));
543 }
544 let parent = self
545 .path
546 .parent()
547 .ok_or_else(|| invalid("a user file needs a parent"))?;
548 let mut nonce = [0u8; 16];
549 getrandom::getrandom(&mut nonce).map_err(|_| {
550 GateError::new("config_unavailable", "could not allocate a temporary file")
551 })?;
552 let name: String = nonce.iter().map(|byte| format!("{byte:02x}")).collect();
553 let temporary = parent.join(format!(".config-{name}.tmp"));
554 let result = (|| {
555 let mut options = std::fs::OpenOptions::new();
556 options.create_new(true).write(true);
557 #[cfg(unix)]
558 {
559 use std::os::unix::fs::OpenOptionsExt;
560 options.mode(0o600);
561 }
562 let mut file = options
563 .open(&temporary)
564 .map_err(|_| invalid("could not create the replacement file"))?;
565 if let Ok(metadata) = std::fs::metadata(&self.path) {
566 file.set_permissions(metadata.permissions())
567 .map_err(|_| invalid("could not preserve file permissions"))?;
568 }
569 file.write_all(&self.bytes)
570 .and_then(|_| file.sync_all())
571 .map_err(|_| invalid("could not flush the replacement file"))?;
572 drop(file);
573 self.unchanged()?;
574 subc_os::durable_replace(&temporary, &self.path)
575 .map_err(|_| invalid("could not atomically replace the user file"))
576 })();
577 if result.is_err() {
578 let _ = std::fs::remove_file(&temporary);
579 }
580 result
581 }
582}
583
584impl RuntimeOwner {
585 pub(crate) fn plan_get(&self, digest: &Digest) -> Result<ConfigPlanView> {
586 let mut state = self.lock()?;
587 let base_revision = state.store.status().base_revision;
588 let plan = state
589 .gate
590 .plans
591 .get(digest)
592 .ok_or_else(|| GateError::new("unknown_plan", "the plan is no longer pending"))?;
593 if base_revision != plan.view.base_revision {
594 return Err(GateError::new(
595 "unknown_plan",
596 "the plan has been superseded",
597 ));
598 }
599 Ok(plan.view.clone())
600 }
601
602 pub(crate) fn plan_discard(&self, digest: &Digest) -> Result<()> {
603 let mut state = self.lock()?;
604 let base_revision = state.store.status().base_revision;
605 if !state
606 .gate
607 .plans
608 .get(digest)
609 .is_some_and(|plan| plan.view.base_revision == base_revision)
610 {
611 return Err(GateError::new(
612 "unknown_plan",
613 "the plan is no longer pending",
614 ));
615 }
616 if state.gate.has_open_approval(digest) {
617 return Err(GateError::new(
618 "plan_in_review",
619 "the plan is being approved",
620 ));
621 }
622 state.gate.expire_plan(digest);
623 state.plan_deadlines.remove(digest);
624 state.retained_plan_files.remove(digest);
625 state.desktop_views.retain(|_, (shown, _)| shown != digest);
626 Ok(())
627 }
628
629 pub(crate) fn apply_unstamped_edits(&self, digest: &Digest) -> Result<Option<u64>> {
632 let mut state = self.lock()?;
633 let Some(plan) = state.gate.plans.get(digest) else {
634 return Ok(None);
635 };
636 if plan.edits.is_none() {
637 return Ok(None);
638 }
639 if !plan.view.refusals.is_empty() {
640 return Err(GateError::new(
641 "plan_refused",
642 "the plan contains refused edits",
643 ));
644 }
645 let Some(edit) = plan.edits.as_ref().filter(|edit| edit.unstamped).cloned() else {
646 return Ok(None);
647 };
648 let base_revision = plan.view.base_revision;
649 Self::check_authority(&mut state, false)?;
650 let status = state.store.status();
651 if status.state != StoreState::Unstamped || status.base_revision != base_revision {
652 return Err(GateError::new(
653 "config_changed_since_review",
654 "configuration authority changed since planning",
655 ));
656 }
657 for file in &edit.files {
658 file.unchanged()?;
659 }
660 for file in &edit.files {
661 file.write_back()?;
662 }
663 state.gate.expire_plan(digest);
664 state.plan_deadlines.remove(digest);
665 state.retained_plan_files.remove(digest);
666 self.notify_delivery_changed();
667 Ok(Some(0))
668 }
669}
670
671impl PreparedPlan {
672 pub(crate) fn is_edit_plan(&self) -> bool {
673 self.edits.is_some()
674 }
675 pub(crate) fn add_edit_refusals(&mut self, refusals: Vec<ConfigPlanRefusal>) {
676 if let Some(edits) = &mut self.edits {
677 edits.refusals.extend(refusals);
678 }
679 }
680}
681
682impl PreparedPlan {
683 pub(crate) fn refused_fields(&self, module: &str) -> Result<Vec<subc_config::FieldChange>> {
684 let candidate = self.candidate.modules.get(module).ok_or_else(|| {
685 GateError::new(
686 "unknown_module",
687 "the module has no admitted settings schema",
688 )
689 })?;
690 super::super::review::expected_fields(
691 module,
692 &candidate.schema,
693 self.bases.get(module),
694 self.base_schemas.get(module),
695 &candidate.view,
696 )
697 .map(|fields| fields.into_values().collect())
698 }
699}