1use std::collections::{BTreeMap, BTreeSet};
4
5use regex::Regex;
6use serde_json::Value;
7use subc_config::{
8 ApplyKind, Layer, LayerValue, RefusalCode, ReviewedTuple, Schema, ValidationContext,
9};
10use subc_protocol::config::ConfigView;
11
12use super::{capture, review, GateError, Result};
13
14#[derive(Clone, Debug)]
17pub struct ProjectLayerSchema {
18 schema: Schema,
19 user_only_sections: BTreeSet<String>,
20 user_only_patterns: Vec<CredentialPattern>,
21}
22
23#[derive(Clone, Debug)]
24struct CredentialPattern {
25 pattern: Regex,
26 named: BTreeSet<String>,
27}
28
29pub struct RecordedProjectLayer {
32 input: LayerValue,
33 pub recorded: Value,
34}
35
36impl ProjectLayerSchema {
37 pub fn new(schema: Schema) -> Self {
38 let mut user_only_sections = BTreeSet::new();
39 let mut user_only_patterns = Vec::new();
40 collect_sections(
41 schema.normalized(),
42 &mut user_only_sections,
43 &mut user_only_patterns,
44 );
45 Self {
46 schema,
47 user_only_sections,
48 user_only_patterns,
49 }
50 }
51
52 pub fn schema(&self) -> &Schema {
53 &self.schema
54 }
55
56 pub fn record_layer(
59 &self,
60 layer: Layer,
61 bytes: &[u8],
62 module: &str,
63 ) -> Result<RecordedProjectLayer> {
64 if !matches!(layer, Layer::Workspace | Layer::Project) {
65 return Err(GateError::new(
66 "layer_forbidden",
67 "expected a workspace or project layer",
68 ));
69 }
70 let value = capture::parse_layer(bytes)?;
71 capture::refuse_expansions(&value, module, "").map_err(|error| {
72 GateError::new(&error.code, "configuration expansions are not supported")
74 })?;
75 let recorded = self
76 .schema
77 .record(&value)
78 .map_err(|_| GateError::new("value_invalid", "configuration could not be recorded"))?;
79 self.check_credentials(&value)?;
80 Ok(RecordedProjectLayer {
81 input: LayerValue::new(layer, value),
82 recorded,
83 })
84 }
85
86 pub fn review_tuple(
88 &self,
89 module: &str,
90 project: &str,
91 user: Option<Value>,
92 layers: &[RecordedProjectLayer],
93 base: Option<(&Schema, &ConfigView)>,
94 ) -> Result<ReviewedTuple> {
95 let mut inputs: Vec<_> = user
96 .into_iter()
97 .map(|value| LayerValue::new(Layer::User, value))
98 .collect();
99 for layer in layers {
100 self.check_credentials(&layer.input.value)
101 .map_err(|error| error.at_settings_layer(layer.input.layer))?;
102 inputs.push(layer.input.clone());
103 }
104 let reviewed = self
105 .schema
106 .review_tuple_attributed(
107 &inputs,
108 &ValidationContext::new(module, Some(project.into())),
109 )
110 .map_err(|attributed| {
111 let refusal = attributed.refusal;
112 let file_layer = match (refusal.code, attributed.layer) {
113 (RefusalCode::LayerForbidden, Some(Layer::Workspace)) => Some("workspace"),
114 (RefusalCode::LayerForbidden, Some(Layer::Project)) => Some("project"),
115 _ => None,
116 };
117 let detail = if let Some(layer) = file_layer.filter(|_| !refusal.path.is_empty()) {
118 format!("{} can't be set in {layer} files", refusal.path)
119 } else if let Some(layer) = file_layer {
120 let reason = match self.schema.normalized()["x-ck-layers"]
121 .as_array()
122 .map(Vec::as_slice)
123 {
124 Some([only]) if only == "user" => "its settings are user-only",
125 _ => "its schema does not allow that layer",
126 };
127 format!("{module} takes no settings from {layer} files ({reason})")
128 } else {
129 let setting = if refusal.path.is_empty() {
130 "configuration"
131 } else {
132 &refusal.path
133 };
134 format!(
135 "{setting} is not valid here ({})",
136 capture::refusal_code(refusal.code)
137 )
138 };
139 let error = GateError::new(capture::refusal_code(refusal.code), detail);
140 match attributed.layer {
141 Some(layer) => error.at_settings_layer(layer),
142 None => error,
143 }
144 })?;
145 refuse_project_apply_kinds(base, &self.schema, &reviewed)?;
146 Ok(reviewed)
147 }
148
149 fn check_credentials(&self, value: &Value) -> Result<()> {
150 if let Some(section) = self
151 .user_only_sections
152 .iter()
153 .find(|section| value.get(section.as_str()).is_some())
154 {
155 return Err(GateError::new(
156 "credential_layer_unsupported",
157 format!("{section} can be set only in the user settings file"),
158 ));
159 }
160 if value.as_object().is_some_and(|fields| {
161 fields.keys().any(|key| {
162 self.user_only_patterns
163 .iter()
164 .any(|section| !section.named.contains(key) && section.pattern.is_match(key))
165 })
166 }) {
167 return Err(GateError::new(
168 "credential_layer_unsupported",
169 "credentials can be set only in the user settings file",
170 ));
171 }
172 Ok(())
173 }
174}
175
176fn properties<'a>(schema: &'a Value, kind: &str) -> impl Iterator<Item = (&'a String, &'a Value)> {
177 schema
178 .get(kind)
179 .and_then(Value::as_object)
180 .into_iter()
181 .flatten()
182}
183
184fn branches(schema: &Value) -> impl Iterator<Item = &Value> {
185 schema
186 .get("oneOf")
187 .and_then(Value::as_array)
188 .into_iter()
189 .flatten()
190}
191
192fn collect_sections(
193 schema: &Value,
194 names: &mut BTreeSet<String>,
195 patterns: &mut Vec<CredentialPattern>,
196) {
197 for branch in branches(schema) {
198 collect_sections(branch, names, patterns);
199 }
200 names.extend(
201 properties(schema, "properties")
202 .filter(|(_, field)| contains_credential(field))
203 .map(|(name, _)| name.clone()),
204 );
205 for (pattern, field) in properties(schema, "patternProperties") {
206 if contains_credential(field) {
207 if let Ok(pattern) = Regex::new(pattern) {
210 patterns.push(CredentialPattern {
211 pattern,
212 named: properties(schema, "properties")
213 .map(|(name, _)| name.clone())
214 .collect(),
215 });
216 }
217 }
218 }
219}
220
221fn contains_credential(schema: &Value) -> bool {
222 schema.get("x-ck-kind").and_then(Value::as_str) == Some("credential_ref")
223 || ["properties", "patternProperties"]
224 .iter()
225 .any(|kind| properties(schema, kind).any(|(_, child)| contains_credential(child)))
226 || schema.get("items").is_some_and(contains_credential)
227 || branches(schema).any(contains_credential)
228}
229
230pub fn refuse_project_apply_kinds(
233 base: Option<(&Schema, &ConfigView)>,
234 candidate_schema: &Schema,
235 candidate: &ReviewedTuple,
236) -> Result<()> {
237 let check = |schema: &Schema, effective: &Value, sources: &BTreeMap<String, Layer>| {
238 for path in review::leaf_paths(schema, effective) {
239 let Some(layer @ (Layer::Workspace | Layer::Project)) = review::source(sources, &path)
240 else {
241 continue;
242 };
243 if matches!(
244 review::apply_for_project(schema.normalized(), effective, &path)?,
245 ApplyKind::NextSupervision | ApplyKind::RouteRebind
246 ) {
247 return Err(GateError::new(
248 "project_apply_kind_unsupported",
249 format!("{path} can't be set in a project or workspace file, because changing it restarts the module or reconnects its routes"),
250 )
251 .at_settings_layer(layer));
252 }
253 }
254 Ok(())
255 };
256 if let Some((schema, view)) = base {
257 check(schema, &view.effective, &view.sources)?;
258 }
259 check(candidate_schema, &candidate.effective, &candidate.sources)
260}
261
262#[cfg(test)]
263mod tests;