Skip to main content

subc_daemon/config_gate/
project_layers.rs

1//! Shared input validation for workspace and project settings.
2
3use std::collections::{BTreeMap, BTreeSet};
4
5use regex::Regex;
6use serde_json::Value;
7use subc_config::{ApplyKind, Layer, LayerValue, ReviewedTuple, Schema, ValidationContext};
8use subc_protocol::config::ConfigView;
9
10use super::{capture, review, GateError, Result};
11
12/// Keep one wrapper per declared schema, not per tuple. Credential policy
13/// depends only on the normalized schema, including resolved local references.
14#[derive(Clone, Debug)]
15pub struct ProjectLayerSchema {
16    schema: Schema,
17    user_only_sections: BTreeSet<String>,
18    user_only_patterns: Vec<CredentialPattern>,
19}
20
21#[derive(Clone, Debug)]
22struct CredentialPattern {
23    pattern: Regex,
24    named: BTreeSet<String>,
25}
26
27/// An input parsed and recorded against its declaration. The parsed value is
28/// kept for merging; only the recorded projection is suitable for diagnostics.
29pub struct RecordedProjectLayer {
30    input: LayerValue,
31    pub recorded: Value,
32}
33
34impl ProjectLayerSchema {
35    pub fn new(schema: Schema) -> Self {
36        let mut user_only_sections = BTreeSet::new();
37        let mut user_only_patterns = Vec::new();
38        collect_sections(
39            schema.normalized(),
40            &mut user_only_sections,
41            &mut user_only_patterns,
42        );
43        Self {
44            schema,
45            user_only_sections,
46            user_only_patterns,
47        }
48    }
49
50    pub fn schema(&self) -> &Schema {
51        &self.schema
52    }
53
54    /// Record present workspace/project bytes, whether read from disk or from
55    /// approved snapshots. Absent layers are left out, not recorded as `{}`.
56    pub fn record_layer(
57        &self,
58        layer: Layer,
59        bytes: &[u8],
60        module: &str,
61        project: &str,
62    ) -> Result<RecordedProjectLayer> {
63        if !matches!(layer, Layer::Workspace | Layer::Project) {
64            return Err(GateError::new(
65                "layer_forbidden",
66                "expected a workspace or project layer",
67            ));
68        }
69        let value = capture::parse_layer(bytes)?;
70        capture::refuse_expansions(&value, module, "").map_err(|error| {
71            // The guard's path can include arbitrary JSON keys from the file.
72            GateError::new(
73                &error.code,
74                format!("{module}/{project}: configuration expansions are not supported"),
75            )
76        })?;
77        let recorded = self.schema.record(&value).map_err(|_| {
78            GateError::new(
79                "value_invalid",
80                format!("{module}/{project}: configuration could not be recorded"),
81            )
82        })?;
83        self.check_credentials(module, project, &value)?;
84        Ok(RecordedProjectLayer {
85            input: LayerValue::new(layer, value),
86            recorded,
87        })
88    }
89
90    /// Validate ordered layers without deriving any credential destinations.
91    pub fn review_tuple(
92        &self,
93        module: &str,
94        project: &str,
95        user: Option<Value>,
96        layers: &[RecordedProjectLayer],
97        base: Option<(&Schema, &ConfigView)>,
98    ) -> Result<ReviewedTuple> {
99        let mut inputs: Vec<_> = user
100            .into_iter()
101            .map(|value| LayerValue::new(Layer::User, value))
102            .collect();
103        for layer in layers {
104            self.check_credentials(module, project, &layer.input.value)?;
105            inputs.push(layer.input.clone());
106        }
107        let reviewed = self
108            .schema
109            .review_tuple(
110                &inputs,
111                &ValidationContext::new(module, Some(project.into())),
112            )
113            .map_err(|refusal| {
114                GateError::new(
115                    capture::refusal_code(refusal.code),
116                    format!("{module}/{project}: {}", refusal.path),
117                )
118            })?;
119        refuse_project_apply_kinds(module, project, base, &self.schema, &reviewed)?;
120        Ok(reviewed)
121    }
122
123    fn check_credentials(&self, module: &str, project: &str, value: &Value) -> Result<()> {
124        if let Some(section) = self
125            .user_only_sections
126            .iter()
127            .find(|section| value.get(section.as_str()).is_some())
128        {
129            return Err(GateError::new(
130                "credential_layer_unsupported",
131                format!("{module}/{project}: section {section} is user-layer only"),
132            ));
133        }
134        if value.as_object().is_some_and(|fields| {
135            fields.keys().any(|key| {
136                self.user_only_patterns
137                    .iter()
138                    .any(|section| !section.named.contains(key) && section.pattern.is_match(key))
139            })
140        }) {
141            return Err(GateError::new(
142                "credential_layer_unsupported",
143                format!("{module}/{project}: credential sections are user-layer only"),
144            ));
145        }
146        Ok(())
147    }
148}
149
150fn properties<'a>(schema: &'a Value, kind: &str) -> impl Iterator<Item = (&'a String, &'a Value)> {
151    schema
152        .get(kind)
153        .and_then(Value::as_object)
154        .into_iter()
155        .flatten()
156}
157
158fn branches(schema: &Value) -> impl Iterator<Item = &Value> {
159    schema
160        .get("oneOf")
161        .and_then(Value::as_array)
162        .into_iter()
163        .flatten()
164}
165
166fn collect_sections(
167    schema: &Value,
168    names: &mut BTreeSet<String>,
169    patterns: &mut Vec<CredentialPattern>,
170) {
171    for branch in branches(schema) {
172        collect_sections(branch, names, patterns);
173    }
174    names.extend(
175        properties(schema, "properties")
176            .filter(|(_, field)| contains_credential(field))
177            .map(|(name, _)| name.clone()),
178    );
179    for (pattern, field) in properties(schema, "patternProperties") {
180        if contains_credential(field) {
181            // Match using the schema's regex defaults. Exact properties take
182            // precedence over pattern matches.
183            if let Ok(pattern) = Regex::new(pattern) {
184                patterns.push(CredentialPattern {
185                    pattern,
186                    named: properties(schema, "properties")
187                        .map(|(name, _)| name.clone())
188                        .collect(),
189                });
190            }
191        }
192    }
193}
194
195fn contains_credential(schema: &Value) -> bool {
196    schema.get("x-ck-kind").and_then(Value::as_str) == Some("credential_ref")
197        || ["properties", "patternProperties"]
198            .iter()
199            .any(|kind| properties(schema, kind).any(|(_, child)| contains_credential(child)))
200        || schema.get("items").is_some_and(contains_credential)
201        || branches(schema).any(contains_credential)
202}
203
204/// Project layers cannot change a module's next supervision settings or
205/// rebind its routes. The user tuple still controls both for inherited values.
206pub fn refuse_project_apply_kinds(
207    module: &str,
208    project: &str,
209    base: Option<(&Schema, &ConfigView)>,
210    candidate_schema: &Schema,
211    candidate: &ReviewedTuple,
212) -> Result<()> {
213    let check = |schema: &Schema, effective: &Value, sources: &BTreeMap<String, Layer>| {
214        for path in review::leaf_paths(schema, effective) {
215            if matches!(
216                review::source(sources, &path),
217                Some(Layer::Workspace | Layer::Project)
218            ) && matches!(
219                review::apply_for_project(schema.normalized(), effective, &path)?,
220                ApplyKind::NextSupervision | ApplyKind::RouteRebind
221            ) {
222                return Err(GateError::new(
223                    "project_apply_kind_unsupported",
224                    format!("{module}/{project}: {path}"),
225                ));
226            }
227        }
228        Ok(())
229    };
230    if let Some((schema, view)) = base {
231        check(schema, &view.effective, &view.sources)?;
232    }
233    check(candidate_schema, &candidate.effective, &candidate.sources)
234}
235
236#[cfg(test)]
237mod tests;