use std::borrow::Cow;
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use tilo_lock::MutexRecover as _;
mod carried;
mod refused;
pub(crate) use carried::without_named;
pub const ARGUMENTS_JSON_PREFIX: &str = "\u{1e}tilo-args:";
pub type Str = Cow<'static, str>;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ParamType {
Text,
Integer,
Number,
Boolean,
Object,
Array,
Resource,
DateTime,
Secret,
}
#[must_use]
pub fn param_type_of(schema: &serde_json::Value) -> ParamType {
fn of(schema: &serde_json::Value) -> Option<ParamType> {
let kind = match schema.get("type") {
Some(serde_json::Value::Array(kinds)) => kinds
.iter()
.filter_map(serde_json::Value::as_str)
.find(|kind| *kind != "null"),
Some(kind) => kind.as_str(),
None => None,
};
if let Some(kind) = kind {
return Some(match kind {
"string" => ParamType::Text,
"integer" => ParamType::Integer,
"number" => ParamType::Number,
"boolean" => ParamType::Boolean,
"array" => ParamType::Array,
_ => ParamType::Object,
});
}
if let Some(values) = schema.get("enum").and_then(serde_json::Value::as_array) {
return values
.iter()
.all(serde_json::Value::is_string)
.then_some(ParamType::Text);
}
let alternatives = schema
.get("oneOf")
.or_else(|| schema.get("anyOf"))
.and_then(serde_json::Value::as_array)?;
let mut kinds = alternatives
.iter()
.filter(|alternative| alternative.get("type") != Some(&serde_json::json!("null")))
.map(of);
let first = kinds.next()??;
kinds.all(|kind| kind == Some(first)).then_some(first)
}
of(schema).unwrap_or(ParamType::Object)
}
impl ParamType {
pub fn label(self) -> &'static str {
match self {
ParamType::Text => "text",
ParamType::Integer => "integer",
ParamType::Number => "number",
ParamType::Boolean => "boolean",
ParamType::Object => "object",
ParamType::Array => "array",
ParamType::Resource => "resource",
ParamType::DateTime => "datetime",
ParamType::Secret => "secret",
}
}
}
pub const RESOURCE_KIND_ANNOTATION: &str = "resource_kind";
pub const RESOURCE_KINDS_ANNOTATION: &str = "resource_kinds";
pub const CHOICE_LABELS_ANNOTATION: &str = "choice_labels";
pub const PEOPLE_ANNOTATION: &str = "people";
pub const PLACE_ANNOTATION: &str = "place";
pub const CONTENT_ANNOTATION: &str = "content";
pub const PICK_ANNOTATION: &str = "pick";
pub const SHAPED_BY_ANNOTATION: &str = "shaped_by";
#[must_use]
pub fn shaped_by_schema<V: Into<String>>(
schema: serde_json::Value,
argument: &str,
shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
) -> serde_json::Value {
let mut schema = match schema {
serde_json::Value::Object(schema) => schema,
_ => serde_json::Map::new(),
};
schema.insert(
SHAPED_BY_ANNOTATION.into(),
shapes_decided_by(argument, shapes),
);
serde_json::Value::Object(schema)
}
fn shapes_decided_by<V: Into<String>>(
argument: &str,
shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
) -> serde_json::Value {
let shapes: serde_json::Map<String, serde_json::Value> = shapes
.into_iter()
.map(|(value, schema)| (value.into(), schema))
.collect();
serde_json::json!({"argument": argument, "shapes": shapes})
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Pick {
Grantee,
Node,
Grant,
Resource { kind: String },
}
impl Pick {
const TAGGED: [Self; 3] = [Self::Grantee, Self::Node, Self::Grant];
const RESOURCE_TAG: &str = "resource";
const fn tag(&self) -> &'static str {
match self {
Self::Grantee => "subject",
Self::Node => "node",
Self::Grant => "grant",
Self::Resource { .. } => Self::RESOURCE_TAG,
}
}
}
#[must_use]
pub fn resource_reference_schema() -> serde_json::Value {
let text = || serde_json::json!({ "type": "string", "minLength": 1 });
serde_json::json!({
"type": "object",
"properties": {
"app": text(),
"record": text(),
"kind": text(),
"id": text(),
"label": { "type": "string" },
},
"required": ["app", "kind", "id", "label"],
})
}
#[must_use]
pub fn picked_resource_schema(kind: &str) -> serde_json::Value {
let mut schema = resource_reference_schema();
if let serde_json::Value::Object(fields) = &mut schema {
fields.insert(PICK_ANNOTATION.into(), Pick::RESOURCE_TAG.into());
fields.insert(RESOURCE_KIND_ANNOTATION.into(), kind.into());
}
schema
}
#[must_use]
pub fn picked_address_schema(kind: &str) -> serde_json::Value {
let mut schema = serde_json::json!({ "type": "string" });
if let serde_json::Value::Object(fields) = &mut schema {
fields.insert(RESOURCE_KIND_ANNOTATION.into(), kind.into());
}
schema
}
#[must_use]
pub fn place_schema() -> serde_json::Value {
let offset = || serde_json::json!({ "type": "integer", "minimum": 0 });
serde_json::json!({
"type": "object",
PLACE_ANNOTATION: true,
"properties": {
"item": { "type": "string", "minLength": 1 },
"at": offset(),
"start": offset(),
"end": offset(),
},
"required": ["item"],
"additionalProperties": false,
})
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActionParam {
pub name: Str,
pub ty: ParamType,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub required: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub entry: bool,
pub description: Str,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub choices: Vec<Str>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub schema: Option<std::sync::Arc<serde_json::Value>>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub nullable: bool,
}
impl ActionParam {
pub const fn required(name: &'static str, ty: ParamType, description: &'static str) -> Self {
Self {
name: Cow::Borrowed(name),
ty,
required: true,
entry: false,
description: Cow::Borrowed(description),
choices: Vec::new(),
schema: None,
nullable: false,
}
}
pub const fn optional(name: &'static str, ty: ParamType, description: &'static str) -> Self {
Self {
name: Cow::Borrowed(name),
ty,
required: false,
entry: false,
description: Cow::Borrowed(description),
choices: Vec::new(),
schema: None,
nullable: false,
}
}
pub fn required_owned(
name: impl Into<Str>,
ty: ParamType,
description: impl Into<Str>,
) -> Self {
Self {
name: name.into(),
ty,
required: true,
entry: false,
description: description.into(),
choices: Vec::new(),
schema: None,
nullable: false,
}
}
pub fn optional_owned(
name: impl Into<Str>,
ty: ParamType,
description: impl Into<Str>,
) -> Self {
Self {
name: name.into(),
ty,
required: false,
entry: false,
description: description.into(),
choices: Vec::new(),
schema: None,
nullable: false,
}
}
#[must_use]
pub fn taking_entry(mut self) -> Self {
self.entry = true;
self
}
#[must_use]
pub fn with_choices<S: Into<Str>>(mut self, choices: impl IntoIterator<Item = S>) -> Self {
self.choices = choices.into_iter().map(Into::into).collect();
self
}
#[must_use]
pub fn with_schema(mut self, schema: serde_json::Value) -> Self {
self.schema = Some(std::sync::Arc::new(schema));
self
}
#[must_use]
pub fn titled(mut self, title: impl Into<String>) -> Self {
let mut schema = match self.schema.as_deref() {
Some(serde_json::Value::Object(schema)) => schema.clone(),
_ => serde_json::Map::new(),
};
schema.insert("title".to_owned(), serde_json::Value::String(title.into()));
self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
self
}
#[must_use]
pub fn described(mut self, title: impl Into<String>) -> Self {
let title = title.into();
self.description = title.clone().into();
self.titled(title)
}
#[must_use]
pub fn with_default(mut self, value: serde_json::Value) -> Self {
let mut schema = match self.schema.as_deref() {
Some(serde_json::Value::Object(schema)) => schema.clone(),
_ => serde_json::Map::new(),
};
schema.insert("default".to_owned(), value);
self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
self
}
#[must_use]
pub fn with_shared_schema(mut self, schema: std::sync::Arc<serde_json::Value>) -> Self {
self.schema = Some(schema);
self
}
#[must_use]
pub fn taking_resource_kinds<I, S>(self, kinds: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
let kinds = kinds
.into_iter()
.map(|kind| serde_json::Value::String(kind.into()))
.collect();
self.annotate(RESOURCE_KINDS_ANNOTATION, serde_json::Value::Array(kinds))
}
#[must_use]
pub fn resource_kinds(&self) -> Vec<&str> {
self.schema
.as_deref()
.and_then(|schema| schema.get(RESOURCE_KINDS_ANNOTATION))
.and_then(serde_json::Value::as_array)
.map(|kinds| kinds.iter().filter_map(serde_json::Value::as_str).collect())
.unwrap_or_default()
}
#[must_use]
pub fn of_resource_kind(mut self, kind: impl Into<String>) -> Self {
let mut schema = match self.schema.take() {
Some(schema) => match std::sync::Arc::unwrap_or_clone(schema) {
serde_json::Value::Object(schema) => schema,
_ => serde_json::Map::new(),
},
_ => serde_json::Map::new(),
};
schema.insert(
RESOURCE_KIND_ANNOTATION.into(),
serde_json::Value::String(kind.into()),
);
self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
self
}
#[must_use]
pub fn with_labelled_choices<V: Into<Str>, L: Into<String>>(
mut self,
choices: impl IntoIterator<Item = (V, L)>,
) -> Self {
let mut labels = serde_json::Map::new();
self.choices = choices
.into_iter()
.map(|(value, label)| {
let value: Str = value.into();
labels.insert(value.to_string(), serde_json::Value::String(label.into()));
value
})
.collect();
self.annotate(CHOICE_LABELS_ANNOTATION, serde_json::Value::Object(labels))
}
#[must_use]
pub fn choosing_people<S: Into<String>>(self, people: impl IntoIterator<Item = S>) -> Self {
let people = people
.into_iter()
.map(|person| serde_json::Value::String(person.into()))
.collect();
self.annotate(PEOPLE_ANNOTATION, serde_json::Value::Array(people))
}
#[must_use]
pub fn picking(self, pick: Pick) -> Self {
match pick {
Pick::Resource { kind } => self.with_schema(picked_resource_schema(&kind)),
tagged => self.annotate(
PICK_ANNOTATION,
serde_json::Value::String(tagged.tag().into()),
),
}
}
#[must_use]
pub fn pick(&self) -> Option<Pick> {
let schema = self.schema.as_ref()?;
let tag = schema.get(PICK_ANNOTATION)?.as_str()?;
if tag == Pick::RESOURCE_TAG {
let kind = schema.get(RESOURCE_KIND_ANNOTATION)?.as_str()?;
return Some(Pick::Resource { kind: kind.into() });
}
Pick::TAGGED.into_iter().find(|pick| pick.tag() == tag)
}
#[must_use]
pub fn choice_label(&self, choice: &str) -> Option<&str> {
self.schema
.as_ref()?
.get(CHOICE_LABELS_ANNOTATION)?
.get(choice)?
.as_str()
}
#[must_use]
pub fn shaped_by<V: Into<String>>(
self,
argument: &str,
shapes: impl IntoIterator<Item = (V, serde_json::Value)>,
) -> Self {
self.annotate(SHAPED_BY_ANNOTATION, shapes_decided_by(argument, shapes))
}
#[must_use]
pub fn shapes_by(&self) -> Option<(&str, &serde_json::Map<String, serde_json::Value>)> {
let declared = self.schema.as_deref()?.get(SHAPED_BY_ANNOTATION)?;
Some((
declared.get("argument")?.as_str()?,
declared.get("shapes")?.as_object()?,
))
}
fn annotate(mut self, key: &str, value: serde_json::Value) -> Self {
let mut schema = match self.schema.take() {
Some(schema) => match std::sync::Arc::unwrap_or_clone(schema) {
serde_json::Value::Object(schema) => schema,
_ => serde_json::Map::new(),
},
_ => serde_json::Map::new(),
};
schema.insert(key.into(), value);
self.schema = Some(std::sync::Arc::new(serde_json::Value::Object(schema)));
self
}
#[must_use]
pub fn resource_kind(&self) -> Option<&str> {
if self.ty != ParamType::Resource {
return None;
}
self.schema
.as_ref()?
.get(RESOURCE_KIND_ANNOTATION)?
.as_str()
.filter(|kind| !kind.is_empty())
}
#[must_use]
pub fn as_place(mut self) -> Self {
self.ty = ParamType::Object;
self.schema = Some(std::sync::Arc::new(place_schema()));
self
}
#[must_use]
pub fn as_place_in(mut self, field: &str) -> Self {
let mut schema = place_schema();
if let Some(object) = schema.as_object_mut() {
object.insert(
PLACE_ANNOTATION.into(),
serde_json::Value::String(field.into()),
);
}
self.ty = ParamType::Object;
self.schema = Some(std::sync::Arc::new(schema));
self
}
#[must_use]
pub fn as_content(mut self) -> Self {
self.ty = ParamType::Text;
self.schema = Some(std::sync::Arc::new(serde_json::json!({
"type": "string",
CONTENT_ANNOTATION: true,
})));
self
}
#[must_use]
pub fn as_content_list(mut self) -> Self {
self.ty = ParamType::Array;
self.schema = Some(std::sync::Arc::new(serde_json::json!({
"type": "array",
"items": { "type": "string", CONTENT_ANNOTATION: true },
})));
self
}
#[must_use]
pub fn is_content_list(&self) -> bool {
self.ty == ParamType::Array
&& self
.schema
.as_ref()
.and_then(|schema| schema.get("items"))
.and_then(|items| items.get(CONTENT_ANNOTATION))
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
}
#[must_use]
pub fn is_content(&self) -> bool {
self.ty == ParamType::Text
&& self
.schema
.as_ref()
.and_then(|schema| schema.get(CONTENT_ANNOTATION))
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
}
#[must_use]
pub fn is_place(&self) -> bool {
self.ty == ParamType::Object
&& self
.schema
.as_ref()
.and_then(|schema| schema.get(PLACE_ANNOTATION))
.is_some_and(|place| place.as_bool() == Some(true) || place.is_string())
}
#[must_use]
pub fn place_field(&self) -> Option<&str> {
self.schema
.as_ref()?
.get(PLACE_ANNOTATION)?
.as_str()
.filter(|field| !field.is_empty())
}
#[must_use]
pub fn nullable(mut self) -> Self {
self.nullable = true;
self
}
#[must_use]
pub fn declared_shape(&self) -> Option<String> {
refused::declared_shape(self)
}
pub fn validate_declaration(&self) -> Vec<String> {
let mut errors = Vec::new();
if self.name.trim().is_empty() {
errors.push("parameter name must be non-empty".into());
}
if self.description.trim().is_empty() {
errors.push("parameter description must be non-empty".into());
}
if self.ty == ParamType::Secret && !self.choices.is_empty() {
errors.push("secret parameters must not publish possible values".into());
}
for choice in &self.choices {
let valid = match self.ty {
ParamType::Text => true,
ParamType::Integer => choice.parse::<i128>().is_ok(),
ParamType::Number => choice.parse::<f64>().is_ok(),
ParamType::Boolean => matches!(choice.as_ref(), "true" | "false"),
ParamType::Object => {
serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(choice)
.is_ok()
}
ParamType::Array => serde_json::from_str::<Vec<serde_json::Value>>(choice).is_ok(),
ParamType::Resource => {
!choice.trim().is_empty()
&& !choice.contains(crate::KEY_SEP)
&& choice.contains(':')
}
ParamType::DateTime => looks_like_rfc3339(choice),
ParamType::Secret => false,
};
if !valid {
errors.push(format!(
"choice `{choice}` does not have declared type {}",
self.ty.label()
));
}
}
if let Some(schema) = &self.schema
&& let Err(reason) = validate_shared_schema_definition(schema)
{
errors.push(format!("invalid schema: {reason}"));
}
errors
}
}
const VALID_SCHEMA_LIMIT: usize = 64;
thread_local! {
static VALID_SCHEMAS: std::cell::RefCell<Vec<std::sync::Weak<serde_json::Value>>> =
const { std::cell::RefCell::new(Vec::new()) };
}
fn validate_shared_schema_definition(
schema: &std::sync::Arc<serde_json::Value>,
) -> Result<(), String> {
let known = VALID_SCHEMAS.with(|schemas| {
schemas
.borrow()
.iter()
.any(|validated| std::ptr::eq(validated.as_ptr(), std::sync::Arc::as_ptr(schema)))
});
if known {
return Ok(());
}
validate_schema_definition(schema)?;
VALID_SCHEMAS.with(|schemas| {
let mut schemas = schemas.borrow_mut();
schemas.retain(|schema| schema.strong_count() != 0);
if schemas.len() == VALID_SCHEMA_LIMIT {
schemas.remove(0);
}
schemas.push(std::sync::Arc::downgrade(schema));
});
Ok(())
}
#[derive(Clone, PartialEq)]
pub enum ArgValue {
Text(String),
Integer(i128),
Number(f64),
Boolean(bool),
Object(serde_json::Map<String, serde_json::Value>),
Array(Vec<serde_json::Value>),
Resource(String),
DateTime(String),
Secret(String),
Null,
}
impl std::fmt::Debug for ArgValue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Text(value) => f.debug_tuple("Text").field(value).finish(),
Self::Integer(value) => f.debug_tuple("Integer").field(value).finish(),
Self::Number(value) => f.debug_tuple("Number").field(value).finish(),
Self::Boolean(value) => f.debug_tuple("Boolean").field(value).finish(),
Self::Object(value) => f.debug_tuple("Object").field(value).finish(),
Self::Array(value) => f.debug_tuple("Array").field(value).finish(),
Self::Resource(value) => f.debug_tuple("Resource").field(value).finish(),
Self::DateTime(value) => f.debug_tuple("DateTime").field(value).finish(),
Self::Secret(_) => f.debug_tuple("Secret").field(&"[REDACTED]").finish(),
Self::Null => f.write_str("Null"),
}
}
}
impl ArgValue {
pub fn ty(&self) -> ParamType {
match self {
ArgValue::Text(_) | ArgValue::Null => ParamType::Text,
ArgValue::Integer(_) => ParamType::Integer,
ArgValue::Number(_) => ParamType::Number,
ArgValue::Boolean(_) => ParamType::Boolean,
ArgValue::Object(_) => ParamType::Object,
ArgValue::Array(_) => ParamType::Array,
ArgValue::Resource(_) => ParamType::Resource,
ArgValue::DateTime(_) => ParamType::DateTime,
ArgValue::Secret(_) => ParamType::Secret,
}
}
pub fn satisfies(&self, want: ParamType) -> bool {
self.ty() == want || (want == ParamType::Number && self.ty() == ParamType::Integer)
}
pub fn from_json(value: &serde_json::Value) -> Option<Self> {
match value {
serde_json::Value::String(s) => Some(ArgValue::Text(s.clone())),
serde_json::Value::Bool(b) => Some(ArgValue::Boolean(*b)),
serde_json::Value::Number(n) => match (n.as_i64(), n.as_u64()) {
(Some(i), _) => Some(ArgValue::Integer(i128::from(i))),
(None, Some(i)) => Some(ArgValue::Integer(i128::from(i))),
(None, None) => n.as_f64().map(ArgValue::Number),
},
serde_json::Value::Object(value) => Some(ArgValue::Object(value.clone())),
serde_json::Value::Array(value) => Some(ArgValue::Array(value.clone())),
serde_json::Value::Null => Some(ArgValue::Null),
}
}
pub fn to_json(&self) -> serde_json::Value {
match self {
ArgValue::Text(s) => serde_json::Value::String(s.clone()),
ArgValue::Integer(i) => i64::try_from(*i).map_or_else(
|_| u64::try_from(*i).map_or(serde_json::Value::Null, serde_json::Value::from),
serde_json::Value::from,
),
ArgValue::Number(f) => serde_json::Number::from_f64(*f)
.map_or(serde_json::Value::Null, serde_json::Value::Number),
ArgValue::Boolean(b) => serde_json::Value::Bool(*b),
ArgValue::Object(value) => serde_json::Value::Object(value.clone()),
ArgValue::Array(value) => serde_json::Value::Array(value.clone()),
ArgValue::Resource(value) | ArgValue::DateTime(value) | ArgValue::Secret(value) => {
serde_json::Value::String(value.clone())
}
ArgValue::Null => serde_json::Value::Null,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ArgViolation {
Minimum { bound: serde_json::Value },
Maximum { bound: serde_json::Value },
}
impl std::fmt::Display for ArgViolation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let (side, bound) = match self {
Self::Minimum { bound } => ("least", bound),
Self::Maximum { bound } => ("most", bound),
};
write!(f, "must be at {side} {bound}")
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ArgError {
Missing {
name: String,
takes: String,
},
OutOfRange {
name: String,
violation: ArgViolation,
},
Unknown {
name: String,
takes: String,
},
WrongType {
name: String,
expected: ParamType,
got: ParamType,
shape: String,
},
NotAllowed {
name: String,
given: &'static str,
allowed: Vec<String>,
},
Unrepresentable {
name: String,
},
Constraint {
name: String,
reason: String,
},
}
impl std::fmt::Display for ArgError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ArgError::Missing { name, takes } => write!(
f,
"required argument `{name}` was not supplied: it must be {takes}"
),
ArgError::Unknown { name, takes } => write!(
f,
"`{name}` is not a parameter of this action; its arguments are {takes}"
),
ArgError::WrongType {
name,
expected,
got,
shape,
} => write!(
f,
"argument `{name}` was given {} and must be {}: {shape}",
refused::kind(*got),
refused::kind(*expected)
),
ArgError::NotAllowed {
name,
given,
allowed,
} => write!(
f,
"argument `{name}` must be one of {}; it was given {given} that is none of them",
allowed.join(", ")
),
ArgError::Unrepresentable { name } => {
write!(f, "argument `{name}` has an unsupported JSON value")
}
ArgError::Constraint { name, reason } => {
write!(f, "argument `{name}` {reason}")
}
ArgError::OutOfRange { name, violation } => {
write!(f, "argument `{name}` {violation}")
}
}
}
}
impl std::error::Error for ArgError {}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ActionArgs {
values: BTreeMap<String, ArgValue>,
from: Option<MadeFrom>,
}
pub const FROM_ARGUMENT: &str = "$from";
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct MadeFrom {
pub resource: String,
pub kind: String,
}
impl MadeFrom {
#[must_use]
pub fn from_json(value: &serde_json::Value) -> Option<Self> {
let object = value.as_object()?;
Some(Self {
resource: object.get("ref")?.as_str()?.to_owned(),
kind: object.get("ty")?.as_str()?.to_owned(),
})
}
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({"ref": self.resource, "ty": self.kind})
}
#[must_use]
pub fn app(&self) -> Option<&str> {
let (app, kind) = self.kind.strip_prefix("tl.")?.rsplit_once('.')?;
(!app.is_empty() && !kind.is_empty()).then_some(app)
}
}
pub const MADE: &str = "$made";
#[must_use]
pub fn made_marker(member: usize, item: usize) -> String {
format!("{MADE}:{member}:{item}")
}
#[must_use]
pub fn made_reference(value: &serde_json::Value) -> Option<(usize, usize)> {
let reference = value.get(MADE)?;
let number = |key: &str| {
reference
.get(key)
.and_then(serde_json::Value::as_u64)
.and_then(|number| usize::try_from(number).ok())
};
Some((number("member")?, number("item")?))
}
#[must_use]
pub fn made_of_marker(text: &str) -> Option<(usize, usize)> {
let rest = text.strip_prefix(MADE)?.strip_prefix(':')?;
let (member, item) = rest.split_once(':')?;
Some((member.parse().ok()?, item.parse().ok()?))
}
impl ActionArgs {
pub fn none() -> Self {
Self::default()
}
#[must_use]
pub fn from(&self) -> Option<&MadeFrom> {
self.from.as_ref()
}
#[must_use]
pub fn with_from(mut self, from: Option<MadeFrom>) -> Self {
self.from = from;
self
}
pub fn bind(
params: &[ActionParam],
supplied: impl IntoIterator<Item = (String, ArgValue)>,
) -> Result<Self, ArgError> {
let mut values: BTreeMap<String, ArgValue> = BTreeMap::new();
for (name, value) in supplied {
let Some(param) = params.iter().find(|p| p.name.as_ref() == name.as_str()) else {
return Err(refused::unknown(name, params));
};
if matches!(value, ArgValue::Null) && !param.nullable && !param.required {
continue;
}
if matches!(value, ArgValue::Null) && !param.nullable {
return Err(refused::null(param));
}
if !matches!(value, ArgValue::Null)
&& !value.satisfies(param.ty)
&& !schema_alternative_of(param, &value)
{
return Err(refused::wrong_type(param, &value));
}
match &value {
ArgValue::Number(number) if !number.is_finite() => {
return Err(ArgError::Constraint {
name,
reason: "must be a finite number".into(),
});
}
ArgValue::Resource(address)
if address.trim().is_empty()
|| address.contains(crate::KEY_SEP)
|| !address.contains(':') =>
{
return Err(ArgError::Constraint {
name,
reason: "must be a stable resource address (`kind:id`)".into(),
});
}
ArgValue::DateTime(value) if !looks_like_rfc3339(value) => {
return Err(ArgError::Constraint {
name,
reason: "must be an RFC 3339 date-time with a timezone".into(),
});
}
_ => {}
}
if let Some(schema) = ¶m.schema {
validate_shared_schema_definition(schema).map_err(|reason| {
ArgError::Constraint {
name: name.clone(),
reason,
}
})?;
check_schema_value(&value.to_json(), schema).map_err(|refusal| match refusal {
SchemaRefusal::Bound(violation) => ArgError::OutOfRange {
name: name.clone(),
violation,
},
SchemaRefusal::Other(reason) => ArgError::Constraint {
name: name.clone(),
reason,
},
})?;
}
if !param.choices.is_empty() {
let got = match &value {
ArgValue::Text(s)
| ArgValue::Resource(s)
| ArgValue::DateTime(s)
| ArgValue::Secret(s) => s.clone(),
other => other.to_json().to_string(),
};
if !param.choices.iter().any(|c| c.as_ref() == got.as_str()) {
return Err(refused::not_a_choice(param, &value));
}
}
values.insert(name, value);
}
for param in params.iter().filter(|p| p.required) {
if !values.contains_key(param.name.as_ref()) {
return Err(refused::missing(param));
}
}
hold_to_decided_shapes(params, &values)?;
Ok(Self { values, from: None })
}
pub fn bind_json(
params: &[ActionParam],
supplied: &serde_json::Map<String, serde_json::Value>,
) -> Result<Self, ArgError> {
let mut pairs = Vec::with_capacity(supplied.len());
for (name, value) in supplied {
if name == FROM_ARGUMENT {
continue;
}
let Some(param) = params.iter().find(|param| param.name.as_ref() == name) else {
return Err(refused::unknown(name.clone(), params));
};
let value = match (param.ty, value) {
(ParamType::Resource, serde_json::Value::String(value)) => {
Some(ArgValue::Resource(value.clone()))
}
(ParamType::Text | ParamType::Resource, value)
if made_reference(value).is_some() =>
{
made_reference(value)
.map(|(member, item)| ArgValue::Text(made_marker(member, item)))
}
(ParamType::DateTime, serde_json::Value::String(value)) => {
Some(ArgValue::DateTime(value.clone()))
}
(ParamType::Secret, serde_json::Value::String(value)) => {
Some(ArgValue::Secret(value.clone()))
}
_ => ArgValue::from_json(value),
};
let Some(v) = value else {
return Err(ArgError::Unrepresentable { name: name.clone() });
};
pairs.push((name.clone(), v));
}
let from = supplied.get(FROM_ARGUMENT).and_then(MadeFrom::from_json);
Self::bind(params, pairs).map(|args| args.with_from(from))
}
pub fn text(&self, name: &str) -> Option<&str> {
match self.values.get(name) {
Some(
ArgValue::Text(s)
| ArgValue::Resource(s)
| ArgValue::DateTime(s)
| ArgValue::Secret(s),
) => Some(s.as_str()),
_ => None,
}
}
pub fn integer(&self, name: &str) -> Option<i64> {
match self.values.get(name) {
Some(ArgValue::Integer(i)) => i64::try_from(*i).ok(),
_ => None,
}
}
pub fn whole(&self, name: &str) -> Option<u64> {
match self.values.get(name) {
Some(ArgValue::Integer(i)) => u64::try_from(*i).ok(),
_ => None,
}
}
pub fn array(&self, name: &str) -> Option<&[serde_json::Value]> {
match self.values.get(name) {
Some(ArgValue::Array(values)) => Some(values),
_ => None,
}
}
#[allow(
clippy::cast_precision_loss,
reason = "Number parameters deliberately widen integer JSON values to f64"
)]
pub fn number(&self, name: &str) -> Option<f64> {
match self.values.get(name) {
Some(ArgValue::Number(f)) => Some(*f),
Some(ArgValue::Integer(i)) => Some(*i as f64),
_ => None,
}
}
pub fn boolean(&self, name: &str) -> Option<bool> {
match self.values.get(name) {
Some(ArgValue::Boolean(b)) => Some(*b),
_ => None,
}
}
pub fn get(&self, name: &str) -> Option<&ArgValue> {
self.values.get(name)
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
pub fn to_json(&self) -> serde_json::Map<String, serde_json::Value> {
self.values
.iter()
.map(|(k, v)| (k.clone(), v.to_json()))
.collect()
}
}
fn looks_like_rfc3339(value: &str) -> bool {
let bytes = value.as_bytes();
let at = |index: usize| bytes.get(index).copied();
let digits = |start: usize, count: usize| -> Option<u32> {
bytes
.get(start..start.checked_add(count)?)?
.iter()
.try_fold(0_u32, |sum, digit| {
let digit = char::from(*digit).to_digit(10)?;
sum.checked_mul(10)?.checked_add(digit)
})
};
let (Some(year), Some(month), Some(day), Some(hour), Some(minute), Some(second)) = (
digits(0, 4),
digits(5, 2),
digits(8, 2),
digits(11, 2),
digits(14, 2),
digits(17, 2),
) else {
return false;
};
let leap = (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400);
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => return false,
};
let separated = at(4) == Some(b'-')
&& at(7) == Some(b'-')
&& matches!(at(10), Some(b'T' | b't' | b' '))
&& at(13) == Some(b':')
&& at(16) == Some(b':');
if !separated || !(1..=days).contains(&day) || hour > 23 || minute > 59 || second > 60 {
return false;
}
let mut zone = 19;
if at(zone) == Some(b'.') {
let fraction = bytes
.iter()
.skip(20)
.take_while(|digit| digit.is_ascii_digit())
.count();
if fraction == 0 {
return false;
}
zone = fraction.saturating_add(20);
}
let rest = bytes.get(zone..).unwrap_or_default();
match rest {
[b'Z' | b'z'] => true,
[b'+' | b'-', _, _, b':', _, _] => {
digits(zone.saturating_add(1), 2).is_some_and(|hours| hours <= 23)
&& digits(zone.saturating_add(4), 2).is_some_and(|minutes| minutes <= 59)
}
_ => false,
}
}
const COMPILED_PATTERNS: usize = 64;
fn schema_pattern(pattern: &str) -> Result<regex_lite::Regex, regex_lite::Error> {
static COMPILED: std::sync::LazyLock<
std::sync::Mutex<std::collections::HashMap<String, regex_lite::Regex>>,
> = std::sync::LazyLock::new(std::sync::Mutex::default);
let mut compiled = COMPILED.lock_recover();
if let Some(expression) = compiled.get(pattern) {
return Ok(expression.clone());
}
let expression = regex_lite::Regex::new(pattern)?;
if compiled.len() >= COMPILED_PATTERNS {
compiled.clear();
}
compiled.insert(pattern.to_owned(), expression.clone());
drop(compiled);
Ok(expression)
}
fn validate_string_schema(
text: &str,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
let length = u64::try_from(text.chars().count()).unwrap_or(u64::MAX);
if let Some(minimum) = schema.get("minLength").and_then(serde_json::Value::as_u64)
&& length < minimum
{
return Err(format!("must contain at least {minimum} characters"));
}
if let Some(maximum) = schema.get("maxLength").and_then(serde_json::Value::as_u64)
&& length > maximum
{
return Err(format!("must contain at most {maximum} characters"));
}
if let Some(pattern) = schema.get("pattern") {
let pattern = pattern
.as_str()
.ok_or_else(|| "has a non-string schema pattern".to_string())?;
let expression = schema_pattern(pattern)
.map_err(|error| format!("has an invalid schema pattern: {error}"))?;
if !expression.is_match(text) {
return Err(format!("must match pattern `{pattern}`"));
}
}
if let Some(format) = schema.get("format") {
let format = format
.as_str()
.ok_or_else(|| "has a non-string schema format".to_string())?;
let valid = match format {
"date-time" => looks_like_rfc3339(text),
"date" => text.len() == 10 && looks_like_rfc3339(&format!("{text}T00:00:00Z")),
"uuid" => uuid::Uuid::parse_str(text).is_ok(),
"uri" => text.split_once(':').is_some_and(|(scheme, rest)| {
!scheme.is_empty()
&& !rest.is_empty()
&& scheme
.chars()
.next()
.is_some_and(|ch| ch.is_ascii_alphabetic())
&& scheme
.chars()
.skip(1)
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '+' | '-' | '.'))
&& !text.chars().any(char::is_whitespace)
}),
_ => return Err(format!("uses unsupported schema format `{format}`")),
};
if !valid {
return Err(refused::off_format(format, schema));
}
}
Ok(())
}
fn validate_object_schema(
object: &serde_json::Map<String, serde_json::Value>,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(required) = schema.get("required").and_then(serde_json::Value::as_array) {
for key in required.iter().filter_map(serde_json::Value::as_str) {
if !object.contains_key(key) {
return Err(refused::lacks(key, schema));
}
}
}
if let Some(properties) = schema
.get("properties")
.and_then(serde_json::Value::as_object)
{
for (key, property_schema) in properties {
if let Some(property) = object.get(key) {
validate_schema_value(property, property_schema)
.map_err(|reason| format!("property `{key}` {reason}"))?;
}
}
}
let listed = |key: &str| {
schema
.get("properties")
.and_then(serde_json::Value::as_object)
.is_some_and(|properties| properties.contains_key(key))
};
match schema.get("additionalProperties") {
Some(serde_json::Value::Bool(false)) => {
if let Some(key) = object.keys().find(|key| !listed(key.as_str())) {
return Err(refused::takes_no(key, schema));
}
}
Some(of_its_own @ serde_json::Value::Object(_)) => {
for (key, value) in object {
if !listed(key.as_str()) {
validate_schema_value(value, of_its_own)
.map_err(|reason| format!("property <key> {reason}"))?;
}
}
}
_ => {}
}
Ok(())
}
pub(crate) fn validate_schema(
value: &serde_json::Value,
schema: &serde_json::Value,
) -> Result<(), String> {
check_schema(value, schema).map_err(|refusal| refusal.to_string())
}
enum SchemaRefusal {
Bound(ArgViolation),
Other(String),
}
impl From<String> for SchemaRefusal {
fn from(reason: String) -> Self {
Self::Other(reason)
}
}
impl From<ArgViolation> for SchemaRefusal {
fn from(violation: ArgViolation) -> Self {
Self::Bound(violation)
}
}
impl std::fmt::Display for SchemaRefusal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bound(violation) => violation.fmt(f),
Self::Other(reason) => f.write_str(reason),
}
}
}
fn hold_to_decided_shapes(
params: &[ActionParam],
values: &BTreeMap<String, ArgValue>,
) -> Result<(), ArgError> {
for param in params {
let Some((argument, shapes)) = param.shapes_by() else {
continue;
};
let Some(ArgValue::Text(decides)) = values.get(argument) else {
continue;
};
let Some(shape) = shapes.get(decides.as_str()) else {
continue;
};
let name = param.name.to_string();
if let Some(own) = ¶m.schema {
validate_shared_schema_definition(own).map_err(|reason| ArgError::Constraint {
name: name.clone(),
reason,
})?;
}
let Some(given) = values.get(param.name.as_ref()).map(ArgValue::to_json) else {
if check_schema_value(&serde_json::Value::Null, shape).is_ok() {
continue;
}
return Err(refused::missing_shaped(param, shape));
};
check_schema_value(&given, shape).map_err(|refusal| match refusal {
SchemaRefusal::Bound(violation) => ArgError::OutOfRange {
name: name.clone(),
violation,
},
SchemaRefusal::Other(reason) => ArgError::Constraint {
name: name.clone(),
reason,
},
})?;
}
Ok(())
}
fn check_schema(
value: &serde_json::Value,
schema: &serde_json::Value,
) -> Result<(), SchemaRefusal> {
validate_schema_definition(schema)?;
check_schema_value(value, schema)
}
fn validate_schema_value(
value: &serde_json::Value,
schema: &serde_json::Value,
) -> Result<(), String> {
check_schema_value(value, schema).map_err(|refusal| refusal.to_string())
}
fn schema_alternative_of(param: &ActionParam, value: &ArgValue) -> bool {
let json_type = match value.to_json() {
serde_json::Value::String(_) => "string",
serde_json::Value::Number(number) if number.is_i64() || number.is_u64() => "integer",
serde_json::Value::Number(_) => "number",
serde_json::Value::Bool(_) => "boolean",
serde_json::Value::Object(_) => "object",
serde_json::Value::Array(_) => "array",
serde_json::Value::Null => return false,
};
param
.schema
.as_deref()
.is_some_and(|schema| has_alternative(schema, json_type))
}
fn has_alternative(schema: &serde_json::Value, json_type: &str) -> bool {
schema
.get("oneOf")
.and_then(serde_json::Value::as_array)
.is_some_and(|alternatives| {
alternatives.iter().any(|alternative| {
alternative.get("type").and_then(serde_json::Value::as_str) == Some(json_type)
|| has_alternative(alternative, json_type)
})
})
}
fn check_schema_value(
value: &serde_json::Value,
schema: &serde_json::Value,
) -> Result<(), SchemaRefusal> {
let Some(schema) = schema.as_object() else {
return Err(SchemaRefusal::Other(
"has a schema that is not an object".into(),
));
};
if let Some(alternatives) = schema.get("oneOf").and_then(serde_json::Value::as_array) {
validate_one_of(value, alternatives)?;
}
validate_schema_type(value, schema)?;
validate_schema_equality(value, schema)?;
validate_schema_number(value, schema)?;
validate_schema_string(value, schema)?;
validate_schema_array(value, schema)?;
validate_schema_object(value, schema)?;
Ok(())
}
fn validate_one_of(
value: &serde_json::Value,
alternatives: &[serde_json::Value],
) -> Result<(), String> {
let mut failures = Vec::new();
let mut matched = 0_usize;
for alternative in alternatives {
match validate_schema_value(value, alternative) {
Ok(()) => matched = matched.saturating_add(1),
Err(reason) => failures.push((alternative, reason)),
}
}
match matched {
1 => return Ok(()),
0 => {}
_ => return Err("matches more than one `oneOf` alternative".into()),
}
let meant: Vec<_> = failures
.iter()
.filter(|(alternative, _)| selects(value, alternative))
.collect();
if let [(alternative, reason)] = meant.as_slice() {
return Err(match alternative_name(alternative) {
Some(name) => format!("as `{name}`: {reason}"),
None => reason.clone(),
});
}
let names: Option<Vec<String>> = alternatives.iter().map(alternative_name).collect();
Err(match names {
Some(names) if !names.is_empty() => format!("must be one of: {}", names.join(", ")),
_ => refused::no_alternative(alternatives),
})
}
fn selects(value: &serde_json::Value, alternative: &serde_json::Value) -> bool {
let Some(schema) = alternative.as_object() else {
return false;
};
if let Some(expected) = schema.get("const") {
return value == expected;
}
let Some(object) = value.as_object() else {
return false;
};
let tags: Vec<(&String, &serde_json::Value)> = schema
.get("properties")
.and_then(serde_json::Value::as_object)
.into_iter()
.flatten()
.filter(|(_, property)| property.get("const").is_some() || property.get("enum").is_some())
.collect();
if !tags.is_empty() {
return tags.iter().all(|(key, property)| {
object.get(key.as_str()).is_some_and(|given| {
property.get("const") == Some(given)
|| property
.get("enum")
.and_then(serde_json::Value::as_array)
.is_some_and(|names| names.contains(given))
})
});
}
let required = schema
.get("required")
.and_then(serde_json::Value::as_array)
.map_or(&[][..], Vec::as_slice);
!required.is_empty()
&& required
.iter()
.filter_map(serde_json::Value::as_str)
.all(|key| object.contains_key(key))
}
fn alternative_name(alternative: &serde_json::Value) -> Option<String> {
let schema = alternative.as_object()?;
if let Some(title) = schema.get("title").and_then(serde_json::Value::as_str) {
return Some(title.to_owned());
}
if let Some(constant) = schema.get("const") {
return Some(
constant
.as_str()
.map_or_else(|| constant.to_string(), str::to_owned),
);
}
let required = schema.get("required")?.as_array()?;
let first = required.first()?.as_str()?;
if let Some(constant) = schema
.get("properties")
.and_then(|properties| properties.get(first))
.and_then(|property| property.get("const"))
.and_then(serde_json::Value::as_str)
{
return Some(constant.to_owned());
}
(required.len() == 1).then(|| first.to_owned())
}
fn validate_schema_type(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(expected) = schema.get("type") {
let matches_type = |name: &str| match name {
"null" => value.is_null(),
"boolean" => value.is_boolean(),
"object" => value.is_object(),
"array" => value.is_array(),
"number" => value.is_number(),
"integer" => value
.as_number()
.is_some_and(|number| number.as_i64().is_some() || number.as_u64().is_some()),
"string" => value.is_string(),
_ => false,
};
let valid = expected.as_str().is_some_and(matches_type)
|| expected.as_array().is_some_and(|types| {
!types.is_empty()
&& types.iter().all(serde_json::Value::is_string)
&& types
.iter()
.filter_map(serde_json::Value::as_str)
.any(matches_type)
});
if !valid {
return Err(refused::wrong_kind(value, schema));
}
}
Ok(())
}
fn validate_schema_equality(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(values) = schema.get("enum").and_then(serde_json::Value::as_array)
&& !values.contains(value)
{
return Err(refused::none_of(values));
}
if let Some(expected) = schema.get("const")
&& value != expected
{
return Err(format!("must be {expected}"));
}
Ok(())
}
fn validate_schema_number(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), ArgViolation> {
if let Some(minimum) = schema
.get("minimum")
.filter(|minimum| past(value, minimum, Side::Below))
{
return Err(ArgViolation::Minimum {
bound: minimum.clone(),
});
}
if let Some(maximum) = schema
.get("maximum")
.filter(|maximum| past(value, maximum, Side::Above))
{
return Err(ArgViolation::Maximum {
bound: maximum.clone(),
});
}
Ok(())
}
#[derive(Clone, Copy)]
enum Side {
Below,
Above,
}
fn past(value: &serde_json::Value, bound: &serde_json::Value, side: Side) -> bool {
if let (Some(value), Some(bound)) = (whole(value), whole(bound)) {
return match side {
Side::Below => value < bound,
Side::Above => value > bound,
};
}
let (Some(value), Some(bound)) = (value.as_f64(), bound.as_f64()) else {
return false;
};
match side {
Side::Below => value < bound,
Side::Above => value > bound,
}
}
fn whole(value: &serde_json::Value) -> Option<i128> {
value
.as_i64()
.map(i128::from)
.or_else(|| value.as_u64().map(i128::from))
}
fn validate_schema_string(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(text) = value.as_str() {
validate_string_schema(text, schema)?;
}
Ok(())
}
fn validate_schema_array(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(items) = value.as_array() {
let length = u64::try_from(items.len()).unwrap_or(u64::MAX);
if let Some(minimum) = schema.get("minItems").and_then(serde_json::Value::as_u64)
&& length < minimum
{
return Err(format!("must contain at least {minimum} items"));
}
if let Some(maximum) = schema.get("maxItems").and_then(serde_json::Value::as_u64)
&& length > maximum
{
return Err(format!("must contain at most {maximum} items"));
}
if schema
.get("uniqueItems")
.and_then(serde_json::Value::as_bool)
.unwrap_or(false)
&& items
.iter()
.enumerate()
.any(|(index, item)| items.get(..index).is_some_and(|prior| prior.contains(item)))
{
return Err("must contain unique items".into());
}
let prefix = schema
.get("prefixItems")
.and_then(serde_json::Value::as_array)
.map_or(&[][..], Vec::as_slice);
for (index, (item, item_schema)) in items.iter().zip(prefix).enumerate() {
validate_schema_value(item, item_schema)
.map_err(|reason| format!("item {index} {reason}"))?;
}
if let Some(item_schema) = schema.get("items") {
for (index, item) in items.iter().enumerate().skip(prefix.len()) {
validate_schema_value(item, item_schema)
.map_err(|reason| format!("item {index} {reason}"))?;
}
}
}
Ok(())
}
fn validate_schema_object(
value: &serde_json::Value,
schema: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(object) = value.as_object() {
validate_object_schema(object, schema)?;
}
Ok(())
}
pub fn validate_json_schema(
value: &serde_json::Value,
schema: &serde_json::Value,
) -> Result<(), String> {
validate_schema(value, schema)
}
const SCHEMA_ASSERTIONS: &[&str] = &[
"type",
"enum",
"const",
"minimum",
"maximum",
"minLength",
"maxLength",
"pattern",
"format",
"minItems",
"maxItems",
"uniqueItems",
"items",
"prefixItems",
"required",
"properties",
"additionalProperties",
"oneOf",
];
const SCHEMA_ANNOTATIONS: &[&str] = &[
"$schema",
"$id",
"$comment",
"title",
"description",
"default",
"examples",
"deprecated",
"readOnly",
"writeOnly",
RESOURCE_KIND_ANNOTATION,
RESOURCE_KINDS_ANNOTATION,
PLACE_ANNOTATION,
CONTENT_ANNOTATION,
CHOICE_LABELS_ANNOTATION,
PEOPLE_ANNOTATION,
PICK_ANNOTATION,
SHAPED_BY_ANNOTATION,
];
pub(crate) fn validate_schema_definition(schema: &serde_json::Value) -> Result<(), String> {
let object = schema
.as_object()
.ok_or_else(|| "schema must be an object".to_string())?;
for keyword in object.keys() {
if !SCHEMA_ASSERTIONS.contains(&keyword.as_str())
&& !SCHEMA_ANNOTATIONS.contains(&keyword.as_str())
{
return Err(format!(
"schema uses unsupported keyword `{keyword}`; Tilo rejects unknown keywords instead of silently weakening a contract"
));
}
}
validate_schema_definition_type(object)?;
validate_schema_definition_strings(object)?;
validate_schema_definition_collections(object)?;
validate_schema_definition_shaped(object)?;
validate_schema_definition_numbers(object)
}
fn validate_schema_definition_type(
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(types) = object.get("type") {
let supported = |name: &str| {
matches!(
name,
"null" | "boolean" | "object" | "array" | "number" | "integer" | "string"
)
};
let valid = types.as_str().is_some_and(supported)
|| types.as_array().is_some_and(|types| {
!types.is_empty()
&& types
.iter()
.all(|value| value.as_str().is_some_and(supported))
});
if !valid {
return Err("schema has an unsupported `type`".into());
}
}
Ok(())
}
fn validate_schema_definition_strings(
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(pattern) = object.get("pattern") {
let pattern = pattern
.as_str()
.ok_or_else(|| "schema `pattern` must be a string".to_string())?;
schema_pattern(pattern)
.map_err(|error| format!("schema has an invalid pattern: {error}"))?;
}
if let Some(format) = object.get("format") {
let format = format
.as_str()
.ok_or_else(|| "schema `format` must be a string".to_string())?;
if !matches!(format, "date" | "date-time" | "uuid" | "uri") {
return Err(format!("schema uses unsupported format `{format}`"));
}
}
Ok(())
}
fn validate_schema_definition_collections(
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
if let Some(required) = object.get("required")
&& !required
.as_array()
.is_some_and(|values| values.iter().all(serde_json::Value::is_string))
{
return Err("schema `required` must be an array of strings".into());
}
if object.get("enum").is_some_and(|values| !values.is_array()) {
return Err("schema `enum` must be an array".into());
}
match object.get("additionalProperties") {
None | Some(serde_json::Value::Bool(_)) => {}
Some(of_its_own @ serde_json::Value::Object(_)) => {
validate_schema_definition(of_its_own)
.map_err(|reason| format!("additionalProperties {reason}"))?;
}
Some(_) => {
return Err("schema `additionalProperties` must be a boolean or a schema".into());
}
}
if object
.get("uniqueItems")
.is_some_and(|value| !value.is_boolean())
{
return Err("schema `uniqueItems` must be a boolean".into());
}
if let Some(properties) = object.get("properties") {
let properties = properties
.as_object()
.ok_or_else(|| "schema `properties` must be an object".to_string())?;
for (name, child) in properties {
validate_schema_definition(child)
.map_err(|reason| format!("property `{name}` {reason}"))?;
}
}
if let Some(items) = object.get("items") {
validate_schema_definition(items).map_err(|reason| format!("items {reason}"))?;
}
if let Some(prefix) = object.get("prefixItems") {
let prefix = prefix
.as_array()
.ok_or_else(|| "schema `prefixItems` must be an array".to_string())?;
for (index, item) in prefix.iter().enumerate() {
validate_schema_definition(item)
.map_err(|reason| format!("prefixItems {index} {reason}"))?;
}
}
if let Some(alternatives) = object.get("oneOf") {
let alternatives = alternatives
.as_array()
.filter(|alternatives| !alternatives.is_empty())
.ok_or_else(|| "schema `oneOf` must be a non-empty array".to_string())?;
for (index, alternative) in alternatives.iter().enumerate() {
validate_schema_definition(alternative)
.map_err(|reason| format!("oneOf alternative {index} {reason}"))?;
}
}
Ok(())
}
fn validate_schema_definition_shaped(
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
let Some(declared) = object.get(SHAPED_BY_ANNOTATION) else {
return Ok(());
};
let argument = declared
.get("argument")
.and_then(serde_json::Value::as_str)
.filter(|argument| !argument.trim().is_empty());
let shapes = declared
.get("shapes")
.and_then(serde_json::Value::as_object);
let (Some(_), Some(shapes)) = (argument, shapes) else {
return Err(format!(
"schema `{SHAPED_BY_ANNOTATION}` must name an `argument` and the `shapes` its values decide"
));
};
for (value, shape) in shapes {
validate_schema_definition(shape)
.map_err(|reason| format!("`{SHAPED_BY_ANNOTATION}` shape `{value}` {reason}"))?;
}
Ok(())
}
fn validate_schema_definition_numbers(
object: &serde_json::Map<String, serde_json::Value>,
) -> Result<(), String> {
for keyword in ["minimum", "maximum"] {
if object.get(keyword).is_some_and(|value| !value.is_number()) {
return Err(format!("schema `{keyword}` must be a number"));
}
}
for keyword in ["minLength", "maxLength", "minItems", "maxItems"] {
if object
.get(keyword)
.is_some_and(|value| value.as_u64().is_none())
{
return Err(format!("schema `{keyword}` must be a non-negative integer"));
}
}
Ok(())
}
#[cfg(test)]
mod declaration_reuse_tests {
use std::sync::Arc;
use std::time::Instant;
use serde_json::json;
use super::{ActionArgs, ActionParam, ParamType};
tilo_test_env::scenario! {
fn a_shared_declaration_is_validated_once_per_schema;
phase shared_schema_edits_and_descriptor_changes_are_still_refused;
{
let original = ActionParam::required("body", ParamType::Text, "Body")
.with_schema(json!({"type": "string", "minLength": 3}));
assert!(original.validate_declaration().is_empty());
assert!(
ActionArgs::bind_json(
std::slice::from_ref(&original),
json!({"body": "a"}).as_object().unwrap()
)
.is_err()
);
let mut edited = original.clone();
assert!(edited.validate_declaration().is_empty());
Arc::make_mut(edited.schema.as_mut().unwrap())["minLength"] = json!(-1);
assert!(edited.validate_declaration()[0].contains("non-negative integer"));
assert!(original.validate_declaration().is_empty());
let mut renamed = original.clone();
renamed.name = " ".into();
assert_eq!(
renamed.validate_declaration(),
["parameter name must be non-empty"]
);
let mut secret = original;
secret.ty = ParamType::Secret;
secret.choices.push("private".into());
assert!(secret.validate_declaration()[0].contains("must not publish possible values"));
}
phase last_owner_schema_mutation_dissociates_prior_validation;
{
let mut parameter = ActionParam::required("body", ParamType::Text, "Body")
.with_schema(json!({"type": "string"}));
assert!(parameter.validate_declaration().is_empty());
Arc::make_mut(parameter.schema.as_mut().unwrap())["type"] = json!("unsupported");
assert_eq!(
parameter.validate_declaration(),
["invalid schema: schema has an unsupported `type`"]
);
Arc::make_mut(parameter.schema.as_mut().unwrap())["type"] = json!("string");
assert!(parameter.validate_declaration().is_empty());
}
phase retired_generations_are_released_and_new_invalid_schemas_are_refused;
{
for _ in 0..128 {
let schema = Arc::new(json!({"type": "string"}));
let retired = Arc::downgrade(&schema);
let parameter =
ActionParam::required("body", ParamType::Text, "Body").with_shared_schema(schema);
assert!(parameter.validate_declaration().is_empty());
drop(parameter);
assert!(retired.upgrade().is_none());
let invalid = ActionParam::required("body", ParamType::Text, "Body")
.with_schema(json!({"pattern": "["}));
assert!(invalid.validate_declaration()[0].contains("invalid pattern"));
}
}
phase shared_declaration_observes_recursive_publication_work;
{
let properties: serde_json::Map<String, serde_json::Value> = (0..128)
.map(|index| {
(
format!("field{index}"),
json!({"type": "array", "items": {"type": "object", "properties": {
"text": {"type": "string", "minLength": 1},
"count": {"type": "integer", "minimum": 0}
}, "additionalProperties": false}}),
)
})
.collect();
let parameter = ActionParam::required("request", ParamType::Object, "Request")
.with_shared_schema(Arc::new(
json!({"type": "object", "properties": properties}),
));
let start = Instant::now();
for _ in 0..1000 {
assert!(
std::hint::black_box(¶meter)
.validate_declaration()
.is_empty()
);
}
eprintln!(
"ACTION_SCHEMA_DECLARATION_OBSERVATION iterations=1000 fields=128 elapsed_ns={} includes_gpu_or_display=false",
start.elapsed().as_nanos()
);
}
}
#[test]
fn an_integer_argument_carries_a_whole_id() {
let id = u64::MAX - 7;
let params = [ActionParam::required("row", ParamType::Integer, "Row")];
let bound = ActionArgs::bind_json(¶ms, json!({"row": id}).as_object().unwrap())
.expect("an integer argument takes the whole id");
assert_eq!(bound.to_json()["row"], json!(id), "it reads back exactly");
assert_eq!(
bound.whole("row"),
Some(id),
"and a caller reads the whole id"
);
assert_eq!(bound.integer("row"), None, "which is no i64");
let negative = ActionArgs::bind_json(¶ms, json!({"row": -48}).as_object().unwrap())
.expect("a negative integer binds too");
assert_eq!(negative.to_json()["row"], json!(-48));
}
#[test]
fn an_integers_choices_are_as_wide_as_its_values() {
for id in [u64::MAX - 7, 4_294_967_296, 7] {
let param = ActionParam::required("place", ParamType::Integer, "Place")
.with_choices([id.to_string()]);
assert!(
param.validate_declaration().is_empty(),
"`{id}` declares as a choice: {:?}",
param.validate_declaration()
);
let bound = ActionArgs::bind_json(
std::slice::from_ref(¶m),
json!({"place": id}).as_object().unwrap(),
)
.expect("the id binds as its own choice");
assert_eq!(
bound.to_json()["place"],
json!(id),
"exactly what was given"
);
let other = ActionArgs::bind_json(
std::slice::from_ref(¶m),
json!({"place": id - 1}).as_object().unwrap(),
);
assert!(
other.is_err_and(|error| matches!(error, super::ArgError::NotAllowed { .. })),
"an id not in the list is refused"
);
}
}
#[test]
fn a_bounds_refusal_names_the_whole_number() {
let id = u64::MAX - 7;
let param = ActionParam::required("place", ParamType::Integer, "Place")
.with_schema(json!({"type": "integer", "maximum": id}));
let refused = ActionArgs::bind_json(
std::slice::from_ref(¶m),
json!({"place": id + 1}).as_object().unwrap(),
)
.expect_err("beyond the bound");
assert_eq!(
refused.to_string(),
format!("argument `place` must be at most {id}")
);
}
}
#[cfg(test)]
mod rich_schema_tests {
use super::*;
use serde_json::json;
tilo_test_env::scenario! {
fn parameters_bind_and_validate_by_their_schema;
phase action_parameters_are_typed_validated_and_round_trip;
{
structured_arguments_are_typed_and_recursively_validated();
resource_datetime_secret_and_nullable_values_round_trip();
malformed_schema_is_rejected_before_it_describes_values();
unique_array_items_are_published_and_enforced();
}
phase null_leaves_an_optional_argument_out_and_is_no_required_ones_value;
{
let params = vec![
ActionParam::required("media", ParamType::Text, "media"),
ActionParam::optional("fade_in", ParamType::Number, "fade in"),
ActionParam::optional("parent", ParamType::Text, "parent").nullable(),
];
let supplied = json!({"media": "shot-a.mp4", "fade_in": null, "parent": null});
let bound = ActionArgs::bind_json(¶ms, supplied.as_object().unwrap()).unwrap();
assert_eq!(
bound.to_json(),
*json!({"media": "shot-a.mp4", "parent": null})
.as_object()
.unwrap()
);
assert_eq!(bound.number("fade_in"), None);
let missing = json!({"media": null});
assert_eq!(
ActionArgs::bind_json(¶ms, missing.as_object().unwrap())
.unwrap_err()
.to_string(),
"argument `media` was given null and must be text: \"<text>\""
);
}
phase shared_schema_preserves_wire_binding_and_copy_on_write;
{
use crate::{ActionSpec, EncodedAction, ExecutionLocus};
use std::sync::Arc;
let schema = serde_json::json!({"type": "integer", "minimum": 1});
let original =
ActionParam::required("count", ParamType::Integer, "Count").with_schema(schema.clone());
let clone = original.clone();
assert!(Arc::ptr_eq(
original.schema.as_ref().unwrap(),
clone.schema.as_ref().unwrap()
));
let expected = serde_json::json!({
"name":"count", "ty":"integer", "required":true,
"description":"Count", "schema":schema
});
assert_eq!(serde_json::to_value(&clone).unwrap(), expected);
let decoded: ActionParam = serde_json::from_value(expected).unwrap();
assert_eq!(decoded, original);
let spec = ActionSpec::typed(
"count",
"Count",
"Count",
ExecutionLocus::ClientLocal,
vec![clone],
|args| EncodedAction {
type_id: "test.count".into(),
payload: serde_json::to_vec(&args.to_json()).unwrap(),
},
);
let valid = serde_json::json!({"count":2});
let encoded = spec.build_json(valid.as_object().unwrap()).unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&encoded.payload).unwrap(),
valid
);
assert!(
spec.build_json(serde_json::json!({"count":0}).as_object().unwrap())
.is_err()
);
assert_eq!(spec.build_text("2"), Some(encoded));
assert_eq!(
spec.build_text("0").unwrap().type_id,
crate::resource::INVALID_ARGUMENTS_TYPE
);
let mut edited = original.clone();
Arc::make_mut(edited.schema.as_mut().unwrap())["minimum"] = serde_json::json!(3);
assert_eq!(original.schema.as_ref().unwrap()["minimum"], 1);
assert!(ActionArgs::bind_json(&[edited], valid.as_object().unwrap()).is_err());
assert!(spec.build_json(valid.as_object().unwrap()).is_ok());
let resource = ActionParam::required("target", ParamType::Resource, "Target")
.with_schema(serde_json::json!({"type":"string"}));
let annotated = resource.clone().of_resource_kind("test.page");
assert_eq!(resource.resource_kind(), None);
assert_eq!(annotated.resource_kind(), Some("test.page"));
assert_eq!(
resource
.schema
.as_ref()
.unwrap()
.get(RESOURCE_KIND_ANNOTATION),
None
);
}
phase a_picked_resource_is_a_reference_of_its_kind;
{
let note =
ActionParam::required("note", ParamType::Object, "The note").picking(Pick::Resource {
kind: "notes.notebook.pages".into(),
});
assert!(
note.validate_declaration().is_empty(),
"{:?}",
note.validate_declaration()
);
assert_eq!(
note.pick(),
Some(Pick::Resource {
kind: "notes.notebook.pages".into()
})
);
let params = [note];
let reference = serde_json::json!({ "note": {
"app": "so.tilo.notes",
"kind": "notes.notebook.pages",
"id": "notes.notebook/pages/p1",
"label": "Plan",
}});
assert!(ActionArgs::bind_json(¶ms, reference.as_object().unwrap()).is_ok());
let typed_id = serde_json::json!({ "note": { "id": "notes.notebook/pages/p1" } });
assert!(
ActionArgs::bind_json(¶ms, typed_id.as_object().unwrap()).is_err(),
"a reference names its app and kind"
);
let subject = ActionParam::required("who", ParamType::Object, "Who").picking(Pick::Grantee);
assert_eq!(subject.pick(), Some(Pick::Grantee));
}
phase a_parameter_with_labelled_choices_of_people_binds_its_values;
{
let param = ActionParam::required("id", ParamType::Text, "The identity")
.with_labelled_choices([("ada", "Ada"), ("bob", "Bob")])
.choosing_people(["ada", "bob"]);
assert!(param.validate_declaration().is_empty());
let params = [param];
assert!(ActionArgs::bind(¶ms, [("id".into(), ArgValue::Text("ada".into()))]).is_ok());
assert!(
ActionArgs::bind(¶ms, [("id".into(), ArgValue::Text("eve".into()))]).is_err(),
"only the values offered"
);
}
phase prefix_items_check_the_leading_items_and_items_the_rest;
{
let schema = json!({
"type": "array",
"prefixItems": [{"const": "a"}, {"type": "string"}],
"items": {"type": "integer"},
});
assert!(validate_schema_definition(&schema).is_ok());
assert!(validate_schema(&json!(["a", "x", 1, 2]), &schema).is_ok());
assert!(validate_schema(&json!(["b", "x"]), &schema).is_err());
assert!(validate_schema(&json!(["a", 1]), &schema).is_err());
assert!(validate_schema(&json!(["a", "x", "y"]), &schema).is_err());
assert!(validate_schema_definition(&json!({"prefixItems": {}})).is_err());
}
phase a_maximum_violation_carries_its_bound;
{
let params = vec![
ActionParam::required("pageSize", ParamType::Integer, "Items")
.with_schema(json!({"type": "integer", "minimum": 1, "maximum": 64})),
ActionParam::optional("scale", ParamType::Number, "Zoom")
.with_schema(json!({"type": "number", "minimum": 0.5})),
ActionParam::optional("box", ParamType::Object, "Bounds").with_schema(json!({
"type": "object",
"properties": {"width": {"type": "integer", "maximum": 10}}
})),
];
let bind = |arguments: serde_json::Value| {
ActionArgs::bind_json(¶ms, arguments.as_object().unwrap())
};
let refused = bind(json!({"pageSize": 200})).unwrap_err();
assert_eq!(
refused,
ArgError::OutOfRange {
name: "pageSize".into(),
violation: ArgViolation::Maximum { bound: json!(64) },
}
);
assert_eq!(
refused.to_string(),
"argument `pageSize` must be at most 64"
);
let api = crate::ApiError::from(refused);
assert_eq!(api.code(), "invalid_arguments");
assert_eq!(api.to_string(), "argument `pageSize` must be at most 64");
assert_eq!(
api.failure_details(),
Some(json!({"param": "pageSize", "violation": {"kind": "maximum", "bound": 64}}))
);
let refused = bind(json!({"pageSize": 1, "scale": 0.25})).unwrap_err();
assert_eq!(
refused,
ArgError::OutOfRange {
name: "scale".into(),
violation: ArgViolation::Minimum { bound: json!(0.5) },
}
);
assert_eq!(refused.to_string(), "argument `scale` must be at least 0.5");
let nested = bind(json!({"pageSize": 1, "box": {"width": 11}})).unwrap_err();
assert!(matches!(nested, ArgError::Constraint { .. }), "{nested:?}");
assert_eq!(crate::ApiError::from(nested).failure_details(), None);
assert!(bind(json!({"pageSize": 64, "scale": 0.5})).is_ok());
}
phase a_refusal_names_the_alternative_an_enumerated_tag_selects;
{
let schema = json!({"oneOf": [
{"type": "object", "required": ["action"], "properties": {
"action": {"enum": ["draw", "paint"]}, "args": {"type": "object"}
}, "additionalProperties": false},
{"type": "object", "required": ["action", "args"], "properties": {
"action": {"const": "apply"}, "args": {"type": "object", "required": ["action"]}
}, "additionalProperties": false},
]});
assert!(validate_schema(&json!({"action": "draw", "args": {}}), &schema).is_ok());
let refused = validate_schema(&json!({"action": "apply", "args": {}}), &schema);
assert_eq!(
refused,
Err("as `apply`: property `args` must contain property `action`".into())
);
let refused = validate_schema(&json!({"action": "paint", "args": 3}), &schema).unwrap_err();
assert!(refused.contains("property `args`"), "{refused}");
}
}
fn structured_arguments_are_typed_and_recursively_validated() {
let params = vec![
ActionParam::required("request", ParamType::Object, "request").with_schema(json!({
"required": ["items"],
"additionalProperties": false,
"properties": {
"items": {"minItems": 1, "items": {"minimum": 1}}
}
})),
];
let good = json!({"request": {"items": [1, 2]}})
.as_object()
.cloned()
.unwrap();
assert!(ActionArgs::bind_json(¶ms, &good).is_ok());
let bad = json!({"request": {"items": [0], "surprise": true}})
.as_object()
.cloned()
.unwrap();
assert!(matches!(
ActionArgs::bind_json(¶ms, &bad),
Err(ArgError::Constraint { .. })
));
assert!(
validate_schema(
&json!("#A0b1C2"),
&json!({
"type": "string",
"pattern": "^#[0-9A-Fa-f]{6}$"
})
)
.is_ok()
);
assert!(validate_schema(&json!(42), &json!({"type": "string"})).is_err());
assert!(
validate_schema(
&json!("red"),
&json!({
"type": "string",
"pattern": "^#[0-9A-Fa-f]{6}$"
})
)
.is_err()
);
}
fn resource_datetime_secret_and_nullable_values_round_trip() {
let params = vec![
ActionParam::required("resource", ParamType::Resource, "target"),
ActionParam::required("at", ParamType::DateTime, "time"),
ActionParam::required("token", ParamType::Secret, "credential"),
ActionParam::optional("metadata", ParamType::Object, "metadata").nullable(),
];
let supplied = json!({
"resource": "files.entry:abc",
"at": "2026-09-01T00:00:00Z",
"token": "not-for-logs",
"metadata": null
})
.as_object()
.cloned()
.unwrap();
let bound = ActionArgs::bind_json(¶ms, &supplied).unwrap();
assert_eq!(bound.text("resource"), Some("files.entry:abc"));
assert_eq!(bound.to_json(), supplied);
for moment in [
"2028-02-29t23:59:60.123456789z",
"2026-09-01 08:30:00-07:00",
"2026-12-31T23:59:59.5+14:00",
] {
assert!(looks_like_rfc3339(moment), "{moment} is RFC 3339");
}
for not_a_moment in [
"2026-02-29T00:00:00Z",
"2026-09-01T24:00:00Z",
"2026-09-01T00:00:00.Z",
"2026-09-01T00:00:00+0100",
"2026-09-01T00:00:00+01:00x",
"2026-09-01T00:00Z",
] {
assert!(!looks_like_rfc3339(not_a_moment), "{not_a_moment} is not");
}
for invalid in [
json!({"resource": "label only", "at": "2026-09-01T00:00:00Z", "token": "x"}),
json!({"resource": "files.entry:abc", "at": "tomorrow", "token": "x"}),
json!({"resource": "files.entry:abc", "at": "2026-09-01T00:00:00", "token": "x"}),
json!({"resource": "files.entry:abc", "at": "2026-02-31T00:00:00Z", "token": "x"}),
] {
assert!(matches!(
ActionArgs::bind_json(¶ms, invalid.as_object().unwrap()),
Err(ArgError::Constraint { .. })
));
}
}
fn malformed_schema_is_rejected_before_it_describes_values() {
assert!(validate_schema_definition(&json!({"pattern":"["})).is_err());
assert!(validate_schema_definition(&json!({"format":"tilo-maybe"})).is_err());
let day = json!({"type": "string", "format": "date"});
assert!(validate_schema_definition(&day).is_ok());
assert!(validate_schema(&json!("2026-10-29"), &day).is_ok());
for not_a_day in ["2026-02-30", "2026-1-5", "2026-10-29T10:00:00Z", "tomorrow"] {
assert!(
validate_schema(&json!(not_a_day), &day).is_err(),
"{not_a_day}"
);
}
assert!(validate_schema_definition(&json!({"oneOf": []})).is_err());
let one_of = json!({
"oneOf": [
{"const": "Workspace"},
{"type": "object", "required": ["App"], "properties": {
"App": {"type": "string"}
}, "additionalProperties": false}
]
});
assert!(validate_schema_definition(&one_of).is_ok());
assert!(validate_json_schema(&json!("Workspace"), &one_of).is_ok());
assert!(validate_json_schema(&json!({"App": "so.tilo.notes"}), &one_of).is_ok());
assert!(validate_json_schema(&json!({"App": "notes", "extra": true}), &one_of).is_err());
assert!(
validate_schema_definition(&json!({
"properties": {"nested": {"type":"mystery"}}
}))
.is_err()
);
assert!(validate_schema_definition(&json!({"minProperties": 1})).is_err());
assert!(validate_schema_definition(&json!({"additionalProperties": 1})).is_err());
assert!(
validate_schema_definition(&json!({"additionalProperties": {"type": "mystery"}}))
.is_err()
);
assert!(
validate_schema_definition(&json!({"additionalProperties": {"type": "integer"}}))
.is_ok()
);
assert!(validate_schema_definition(&json!({"title": "accepted annotation"})).is_ok());
}
fn unique_array_items_are_published_and_enforced() {
let schema = json!({
"type": "array",
"uniqueItems": true,
"items": {"type": "string"}
});
assert!(validate_schema_definition(&schema).is_ok());
assert!(
validate_json_schema(&json!(["photos.photo:a", "photos.photo:b"]), &schema).is_ok()
);
assert!(
validate_json_schema(&json!(["photos.photo:a", "photos.photo:a"]), &schema).is_err()
);
assert!(validate_schema_definition(&json!({"uniqueItems": "yes"})).is_err());
}
}
#[cfg(test)]
mod schema_vocabulary_pin_tests {
use super::{SCHEMA_ANNOTATIONS, SCHEMA_ASSERTIONS};
const PINNED: &str = "\
type
enum
const
minimum
maximum
minLength
maxLength
pattern
format
minItems
maxItems
uniqueItems
items
prefixItems
required
properties
additionalProperties
oneOf
---
$schema
$id
$comment
title
description
default
examples
deprecated
readOnly
writeOnly
resource_kind
resource_kinds
place
content
choice_labels
people
pick
shaped_by";
tilo_test_env::scenario! {
fn the_schema_vocabulary_is_pinned;
phase the_vocabulary_is_the_one_pinned_elsewhere;
{
let listed: Vec<&str> = SCHEMA_ASSERTIONS
.iter()
.chain(std::iter::once(&"---"))
.chain(SCHEMA_ANNOTATIONS)
.copied()
.collect();
assert_eq!(PINNED, listed.join("\n"));
}
phase every_keyword_is_listed_once;
{
let mut all: Vec<&str> = SCHEMA_ASSERTIONS
.iter()
.chain(SCHEMA_ANNOTATIONS)
.copied()
.collect();
let listed = all.len();
all.sort_unstable();
all.dedup();
assert_eq!(all.len(), listed, "a keyword is listed twice");
}
}
}