Skip to main content

schedr_master/
params.rs

1//! A DAG's run parameters (decisions 133, 135, 138): the check of its schema when the DAG is
2//! validated, and of a run's values before the run exists.
3//!
4//! The master runs no user code: it checks values against the JSON Schema the runner wrote
5//! (with the `jsonschema` crate), and refuses at validation a schema asking for a check that
6//! crate doesn't make, so what passes here never falls short of the schema. Pydantic's own
7//! validators run only when a task decodes the values.
8
9use jsonschema::error::{TypeKind, ValidationErrorKind};
10use jsonschema::{Draft, Validator};
11use schedr_config::masked::{mask_text, names_secret_in_words};
12use schedr_model::Params;
13use schedr_model::params::{MAX_PARAMS_BYTES, duration_micros, to_stored};
14use serde_json::{Map, Value};
15
16#[cfg(test)]
17mod tests;
18
19/// Keywords the validator checks (JSON Schema 2020-12, and `definitions` of the drafts
20/// Pydantic once wrote).
21const CHECKED: &[&str] = &[
22    "type",
23    "enum",
24    "const",
25    "multipleOf",
26    "maximum",
27    "exclusiveMaximum",
28    "minimum",
29    "exclusiveMinimum",
30    "maxLength",
31    "minLength",
32    "pattern",
33    "maxItems",
34    "minItems",
35    "uniqueItems",
36    "maxContains",
37    "minContains",
38    "maxProperties",
39    "minProperties",
40    "required",
41    "dependentRequired",
42    "allOf",
43    "anyOf",
44    "oneOf",
45    "not",
46    "if",
47    "then",
48    "else",
49    "dependentSchemas",
50    "prefixItems",
51    "items",
52    "contains",
53    "properties",
54    "patternProperties",
55    "additionalProperties",
56    "propertyNames",
57    "unevaluatedItems",
58    "unevaluatedProperties",
59    "format",
60    "$ref",
61    "$defs",
62    "definitions",
63];
64
65/// Keywords that only describe (nothing to check): `discriminator` is Pydantic's hint for a
66/// union its `oneOf` already checks.
67const ANNOTATIONS: &[&str] = &[
68    "$schema",
69    "$comment",
70    "title",
71    "description",
72    "default",
73    "examples",
74    "deprecated",
75    "readOnly",
76    "writeOnly",
77    "discriminator",
78];
79
80/// The formats the validator checks (without its `idna` feature: no `idn-*`).
81const FORMATS: &[&str] = &[
82    "date",
83    "date-time",
84    "time",
85    "duration",
86    "email",
87    "hostname",
88    "ipv4",
89    "ipv6",
90    "uri",
91    "uri-reference",
92    "iri",
93    "iri-reference",
94    "uri-template",
95    "uuid",
96    "json-pointer",
97    "relative-json-pointer",
98    "regex",
99];
100
101/// Keywords whose value is one schema.
102const ONE_SCHEMA: &[&str] = &[
103    "not",
104    "if",
105    "then",
106    "else",
107    "items",
108    "contains",
109    "additionalProperties",
110    "propertyNames",
111    "unevaluatedItems",
112    "unevaluatedProperties",
113];
114
115/// Keywords whose value is a list of schemas.
116const SCHEMA_LIST: &[&str] = &["allOf", "anyOf", "oneOf", "prefixItems"];
117
118/// Keywords whose value maps names to schemas.
119const SCHEMA_MAP: &[&str] = &[
120    "properties",
121    "patternProperties",
122    "dependentSchemas",
123    "$defs",
124    "definitions",
125];
126
127/// What is wrong with a DAG's `params`, for the DAG's validation; empty when nothing is.
128/// `scheduled`: the DAG has a schedule, so every field needs a default.
129#[must_use]
130pub fn problems(params: &Params, scheduled: bool) -> Vec<String> {
131    let mut problems = Vec::new();
132    if !params.schema.is_object() {
133        return vec!["params: the schema isn't an object".to_owned()];
134    }
135    keyword_problems(&params.schema, "", &mut problems);
136    if !problems.is_empty() {
137        return problems;
138    }
139    if !matches!(
140        params.ty,
141        schedr_model::TypeDesc::Dataclass { .. } | schedr_model::TypeDesc::Model { .. }
142    ) {
143        problems.push("params: must be a dataclass or a Pydantic model".to_owned());
144    }
145    if scheduled
146        && let Some(missing) = required(&params.schema)
147            .into_iter()
148            .find(|name| !params.defaults.contains_key(*name))
149    {
150        problems.push(format!(
151            "params: `{missing}` has no default, but the DAG has a schedule (its runs use the \
152             defaults)"
153        ));
154    }
155    if let Err(why) = defaults_checked(params) {
156        problems.push(format!("params: the defaults: {why}"));
157    }
158    problems
159}
160
161/// The fields the schema requires.
162fn required(schema: &Value) -> Vec<&str> {
163    fields_schema(schema)
164        .get("required")
165        .and_then(Value::as_array)
166        .map(|names| names.iter().filter_map(Value::as_str).collect())
167        .unwrap_or_default()
168}
169
170fn defaults_checked(params: &Params) -> Result<(), String> {
171    validator(&params.schema)?;
172    let size = Value::Object(params.defaults.clone()).to_string().len();
173    if size > MAX_PARAMS_BYTES {
174        return Err(over_limit(size));
175    }
176    // Each default alone, against its field's schema (the others may be required and without
177    // one), with the definitions its `$ref`s name.
178    for (name, value) in &params.defaults {
179        let property = properties(&params.schema)
180            .and_then(|p| p.get(name))
181            .ok_or_else(|| format!("`{name}` isn't a field"))?;
182        let mut one = Map::new();
183        for defs in ["$defs", "definitions"] {
184            if let Some(found) = params.schema.get(defs) {
185                one.insert(defs.to_owned(), found.clone());
186            }
187        }
188        one.insert("properties".to_owned(), json_object(name, property.clone()));
189        check(
190            &validator(&Value::Object(one))?,
191            &json_object(name, value.clone()),
192        )?;
193    }
194    Ok(())
195}
196
197fn json_object(name: &str, value: Value) -> Value {
198    let mut map = Map::new();
199    map.insert(name.to_owned(), value);
200    Value::Object(map)
201}
202
203/// A run's parameters, as stored (decision 138): the DAG's defaults with `given` over them,
204/// checked against its schema.
205///
206/// # Errors
207///
208/// Why they are refused, to show: parameters for a DAG that takes none, an unknown field,
209/// values that don't fit the schema, or over [`MAX_PARAMS_BYTES`].
210pub fn run_params(
211    params: Option<&Params>,
212    given: Option<&Map<String, Value>>,
213) -> Result<Value, String> {
214    let given = given.filter(|g| !g.is_empty());
215    let Some(params) = params else {
216        return match given {
217            Some(_) => Err("the DAG takes no parameters (it declares no `params=`)".to_owned()),
218            None => Ok(Value::Object(Map::new())),
219        };
220    };
221    let mut values = params.defaults.clone();
222    if let Some(given) = given {
223        let known = properties(&params.schema);
224        for (name, value) in given {
225            if !known.is_some_and(|k| k.contains_key(name)) {
226                let names = known
227                    .map(|k| {
228                        k.keys()
229                            .map(|n| format!("`{n}`"))
230                            .collect::<Vec<_>>()
231                            .join(", ")
232                    })
233                    .unwrap_or_default();
234                // The name is the trigger's, as typed: masked as a text.
235                return Err(format!(
236                    "unknown parameter `{}` (the DAG takes {names})",
237                    mask_text(name)
238                ));
239            }
240            values.insert(name.clone(), value.clone());
241        }
242    }
243    let values = Value::Object(values);
244    let size = values.to_string().len();
245    if size > MAX_PARAMS_BYTES {
246        return Err(over_limit(size));
247    }
248    check(&validator(&params.schema)?, &values)?;
249    // Its reason never quotes the value; under a secret name, it doesn't give one either.
250    to_stored(&values, &params.ty).map_err(|misfit| {
251        if misfit.fields().any(names_secret_in_words) {
252            format!(
253                "`{}`: doesn't fit its type (the value isn't shown)",
254                mask_text(&misfit.at())
255            )
256        } else {
257            // Names in it (a key, an unknown field) are the trigger's, as typed.
258            mask_text(&misfit.to_string())
259        }
260    })
261}
262
263/// The object schema whose `properties` are the parameters: the root, or what its `$ref`
264/// names (Pydantic's form for a model that refers to itself).
265fn fields_schema(schema: &Value) -> &Value {
266    schema
267        .get("$ref")
268        .and_then(Value::as_str)
269        .and_then(|r| r.strip_prefix('#'))
270        .and_then(|pointer| schema.pointer(pointer))
271        .unwrap_or(schema)
272}
273
274/// The parameters' schemas, by name.
275fn properties(schema: &Value) -> Option<&Map<String, Value>> {
276    fields_schema(schema)
277        .get("properties")
278        .and_then(Value::as_object)
279}
280
281fn over_limit(size: usize) -> String {
282    format!(
283        "the parameters are {size} bytes as JSON, over the limit of {} KiB",
284        MAX_PARAMS_BYTES / 1024
285    )
286}
287
288fn validator(schema: &Value) -> Result<Validator, String> {
289    jsonschema::options()
290        .with_draft(Draft::Draft202012)
291        .should_validate_formats(true)
292        // ISO 8601, fractions of a second included (`PT0.5S`, Pydantic's form; RFC 3339's
293        // `duration`, the crate's, has none), not in years or months (decision 141).
294        .with_format("duration", is_duration)
295        .build(schema)
296        .map_err(|e| format!("the schema is invalid: {e}"))
297}
298
299/// Every reason `values` don't fit, each with where (`limits/1: ...`). A reason never quotes
300/// a value nor the schema's values (decision 134): it names the keyword that failed, a
301/// missing or unknown field, the expected type or the format; names are masked as texts, and
302/// under a field named by a secret word not even the keyword is given.
303fn check(validator: &Validator, values: &Value) -> Result<(), String> {
304    let reasons: Vec<String> = validator
305        .iter_errors(values)
306        .map(|e| {
307            let path = pointer_steps(&e.instance_path().to_string());
308            let at = path
309                .iter()
310                .map(|step| mask_text(step))
311                .collect::<Vec<_>>()
312                .join("/");
313            let reason = if path.iter().any(|step| names_secret_in_words(step)) {
314                "doesn't fit its schema (the value isn't shown)".to_owned()
315            } else {
316                reason(e.kind())
317            };
318            if at.is_empty() {
319                reason
320            } else {
321                format!("`{at}`: {reason}")
322            }
323        })
324        .collect();
325    if reasons.is_empty() {
326        Ok(())
327    } else {
328        Err(reasons.join("; "))
329    }
330}
331
332/// Why a value doesn't fit, from what failed only: nothing of the value, nor a value the
333/// schema holds (a `const`, an `enum`, a `not`'s schema).
334fn reason(kind: &ValidationErrorKind) -> String {
335    let names = |names: &[String]| {
336        names
337            .iter()
338            .map(|n| format!("`{}`", mask_text(n)))
339            .collect::<Vec<_>>()
340            .join(", ")
341    };
342    match kind {
343        ValidationErrorKind::Required { property } => match property.as_str() {
344            Some(name) => format!("`{}` is required", mask_text(name)),
345            None => "a required field is missing".to_owned(),
346        },
347        ValidationErrorKind::Type {
348            kind: TypeKind::Single(ty),
349        } => format!("not of type `{ty}`"),
350        ValidationErrorKind::Type { .. } => "not of any of its types".to_owned(),
351        ValidationErrorKind::Format { format } => format!("not of the format `{format}`"),
352        ValidationErrorKind::AdditionalProperties { unexpected }
353        | ValidationErrorKind::UnevaluatedProperties { unexpected } => {
354            format!("unknown fields {}", names(unexpected))
355        }
356        other => format!("doesn't fit the schema's `{}`", other.keyword()),
357    }
358}
359
360/// A JSON pointer's steps as the names they are (`api~1key` is `api/key`).
361fn pointer_steps(pointer: &str) -> Vec<String> {
362    pointer
363        .split('/')
364        .skip(1)
365        .map(|step| step.replace("~1", "/").replace("~0", "~"))
366        .collect()
367}
368
369/// Every keyword of `schema` (at `at`, a JSON pointer) the validator doesn't check, or a format
370/// it doesn't know, or a `$ref` it would have to fetch.
371fn keyword_problems(schema: &Value, at: &str, problems: &mut Vec<String>) {
372    let Value::Object(object) = schema else {
373        if !schema.is_boolean() {
374            problems.push(format!(
375                "params: the schema at `{}` isn't a schema",
376                shown(at)
377            ));
378        }
379        return;
380    };
381    for (keyword, value) in object {
382        let here = format!("{at}/{keyword}");
383        if !CHECKED.contains(&keyword.as_str()) && !ANNOTATIONS.contains(&keyword.as_str()) {
384            problems.push(format!(
385                "params: the schema's keyword `{keyword}` (at `{}`) isn't one the master checks; \
386                 remove it, or check it in the task",
387                shown(at)
388            ));
389            continue;
390        }
391        match keyword.as_str() {
392            "format" => {
393                if let Some(format) = value.as_str()
394                    && !FORMATS.contains(&format)
395                {
396                    problems.push(format!(
397                        "params: the format `{format}` (at `{}`) isn't one the master checks \
398                         ({}); use another type, or check it in the task",
399                        shown(at),
400                        FORMATS.join(", ")
401                    ));
402                }
403            }
404            "$ref" => {
405                if !value.as_str().is_some_and(|r| r.starts_with('#')) {
406                    problems.push(format!(
407                        "params: `$ref` {value} (at `{}`) isn't within the schema; the master \
408                         fetches nothing",
409                        shown(at)
410                    ));
411                }
412            }
413            "$schema" => {
414                if value.as_str().is_some_and(|s| !s.contains("2020-12")) {
415                    problems.push(format!(
416                        "params: `$schema` {value}: the master checks JSON Schema 2020-12"
417                    ));
418                }
419            }
420            k if ONE_SCHEMA.contains(&k) => keyword_problems(value, &here, problems),
421            k if SCHEMA_LIST.contains(&k) => {
422                for (i, item) in value.as_array().into_iter().flatten().enumerate() {
423                    keyword_problems(item, &format!("{here}/{i}"), problems);
424                }
425            }
426            k if SCHEMA_MAP.contains(&k) => {
427                for (name, item) in value.as_object().into_iter().flatten() {
428                    keyword_problems(item, &format!("{here}/{name}"), problems);
429                }
430            }
431            _ => {}
432        }
433    }
434}
435
436/// The rule a dataclass's duration is stored by (decision 139): ISO 8601, not in years or
437/// months.
438fn is_duration(text: &str) -> bool {
439    duration_micros(text).is_ok()
440}
441
442fn shown(at: &str) -> &str {
443    if at.is_empty() { "/" } else { at }
444}