use std::collections::{BTreeMap, BTreeSet};
use regex::Regex;
use serde_json::Value;
use subc_config::{
ApplyKind, Layer, LayerValue, RefusalCode, ReviewedTuple, Schema, ValidationContext,
};
use subc_protocol::config::ConfigView;
use super::{capture, review, GateError, Result};
#[derive(Clone, Debug)]
pub struct ProjectLayerSchema {
schema: Schema,
user_only_sections: BTreeSet<String>,
user_only_patterns: Vec<CredentialPattern>,
}
#[derive(Clone, Debug)]
struct CredentialPattern {
pattern: Regex,
named: BTreeSet<String>,
}
pub struct RecordedProjectLayer {
input: LayerValue,
pub recorded: Value,
}
impl ProjectLayerSchema {
pub fn new(schema: Schema) -> Self {
let mut user_only_sections = BTreeSet::new();
let mut user_only_patterns = Vec::new();
collect_sections(
schema.normalized(),
&mut user_only_sections,
&mut user_only_patterns,
);
Self {
schema,
user_only_sections,
user_only_patterns,
}
}
pub fn schema(&self) -> &Schema {
&self.schema
}
pub fn record_layer(
&self,
layer: Layer,
bytes: &[u8],
module: &str,
) -> Result<RecordedProjectLayer> {
if !matches!(layer, Layer::Workspace | Layer::Project) {
return Err(GateError::new(
"layer_forbidden",
"expected a workspace or project layer",
));
}
let value = capture::parse_layer(bytes)?;
capture::refuse_expansions(&value, module, "").map_err(|error| {
GateError::new(&error.code, "configuration expansions are not supported")
})?;
let recorded = self
.schema
.record(&value)
.map_err(|_| GateError::new("value_invalid", "configuration could not be recorded"))?;
self.check_credentials(&value)?;
Ok(RecordedProjectLayer {
input: LayerValue::new(layer, value),
recorded,
})
}
pub fn review_tuple(
&self,
module: &str,
project: &str,
user: Option<Value>,
layers: &[RecordedProjectLayer],
base: Option<(&Schema, &ConfigView)>,
) -> Result<ReviewedTuple> {
let mut inputs: Vec<_> = user
.into_iter()
.map(|value| LayerValue::new(Layer::User, value))
.collect();
for layer in layers {
self.check_credentials(&layer.input.value)
.map_err(|error| error.at_settings_layer(layer.input.layer))?;
inputs.push(layer.input.clone());
}
let reviewed = self
.schema
.review_tuple_attributed(
&inputs,
&ValidationContext::new(module, Some(project.into())),
)
.map_err(|attributed| {
let refusal = attributed.refusal;
let file_layer = match (refusal.code, attributed.layer) {
(RefusalCode::LayerForbidden, Some(Layer::Workspace)) => Some("workspace"),
(RefusalCode::LayerForbidden, Some(Layer::Project)) => Some("project"),
_ => None,
};
let detail = if let Some(layer) = file_layer.filter(|_| !refusal.path.is_empty()) {
format!("{} can't be set in {layer} files", refusal.path)
} else if let Some(layer) = file_layer {
let reason = match self.schema.normalized()["x-ck-layers"]
.as_array()
.map(Vec::as_slice)
{
Some([only]) if only == "user" => "its settings are user-only",
_ => "its schema does not allow that layer",
};
format!("{module} takes no settings from {layer} files ({reason})")
} else {
let setting = if refusal.path.is_empty() {
"configuration"
} else {
&refusal.path
};
format!(
"{setting} is not valid here ({})",
capture::refusal_code(refusal.code)
)
};
let error = GateError::new(capture::refusal_code(refusal.code), detail);
match attributed.layer {
Some(layer) => error.at_settings_layer(layer),
None => error,
}
})?;
refuse_project_apply_kinds(base, &self.schema, &reviewed)?;
Ok(reviewed)
}
fn check_credentials(&self, value: &Value) -> Result<()> {
if let Some(section) = self
.user_only_sections
.iter()
.find(|section| value.get(section.as_str()).is_some())
{
return Err(GateError::new(
"credential_layer_unsupported",
format!("{section} can be set only in the user settings file"),
));
}
if value.as_object().is_some_and(|fields| {
fields.keys().any(|key| {
self.user_only_patterns
.iter()
.any(|section| !section.named.contains(key) && section.pattern.is_match(key))
})
}) {
return Err(GateError::new(
"credential_layer_unsupported",
"credentials can be set only in the user settings file",
));
}
Ok(())
}
}
fn properties<'a>(schema: &'a Value, kind: &str) -> impl Iterator<Item = (&'a String, &'a Value)> {
schema
.get(kind)
.and_then(Value::as_object)
.into_iter()
.flatten()
}
fn branches(schema: &Value) -> impl Iterator<Item = &Value> {
schema
.get("oneOf")
.and_then(Value::as_array)
.into_iter()
.flatten()
}
fn collect_sections(
schema: &Value,
names: &mut BTreeSet<String>,
patterns: &mut Vec<CredentialPattern>,
) {
for branch in branches(schema) {
collect_sections(branch, names, patterns);
}
names.extend(
properties(schema, "properties")
.filter(|(_, field)| contains_credential(field))
.map(|(name, _)| name.clone()),
);
for (pattern, field) in properties(schema, "patternProperties") {
if contains_credential(field) {
if let Ok(pattern) = Regex::new(pattern) {
patterns.push(CredentialPattern {
pattern,
named: properties(schema, "properties")
.map(|(name, _)| name.clone())
.collect(),
});
}
}
}
}
fn contains_credential(schema: &Value) -> bool {
schema.get("x-ck-kind").and_then(Value::as_str) == Some("credential_ref")
|| ["properties", "patternProperties"]
.iter()
.any(|kind| properties(schema, kind).any(|(_, child)| contains_credential(child)))
|| schema.get("items").is_some_and(contains_credential)
|| branches(schema).any(contains_credential)
}
pub fn refuse_project_apply_kinds(
base: Option<(&Schema, &ConfigView)>,
candidate_schema: &Schema,
candidate: &ReviewedTuple,
) -> Result<()> {
let check = |schema: &Schema, effective: &Value, sources: &BTreeMap<String, Layer>| {
for path in review::leaf_paths(schema, effective) {
let Some(layer @ (Layer::Workspace | Layer::Project)) = review::source(sources, &path)
else {
continue;
};
if matches!(
review::apply_for_project(schema.normalized(), effective, &path)?,
ApplyKind::NextSupervision | ApplyKind::RouteRebind
) {
return Err(GateError::new(
"project_apply_kind_unsupported",
format!("{path} can't be set in a project or workspace file, because changing it restarts the module or reconnects its routes"),
)
.at_settings_layer(layer));
}
}
Ok(())
};
if let Some((schema, view)) = base {
check(schema, &view.effective, &view.sources)?;
}
check(candidate_schema, &candidate.effective, &candidate.sources)
}
#[cfg(test)]
mod tests;