Repository navigation
Cost Estimation and Sandboxing
When evaluating expressions authored by end users (webhook filters, policy rules, query predicates), you should defend against both compile-time complexity bombs (deep nested comprehensions) and runtime resource exhaustion.
Celly.Json pairs JSON Schema size bounds with Celly's built-in static cost estimator (CelEnv.EstimateCost) and runtime EvalLimits.
JSON Schema already lets you declare bounds on inputs:
-
minLength/maxLengthfor strings -
minItems/maxItemsfor arrays (includingitemsbounds for comprehension iterators) -
minProperties/maxPropertiesfor objects
JsonSchemaTypeProvider.CostEstimator automatically translates those bounds into a Celly ICostEstimator:
const string schema = """
{
"type": "object",
"properties": {
"name": { "type": "string", "minLength": 1, "maxLength": 64 },
"roles": {
"type": "array",
"minItems": 0,
"maxItems": 10,
"items": { "type": "string", "maxLength": 32 }
}
}
}
""";
var provider = JsonSchemaTypeProvider.FromJson(schema);
CelEnv env = JsonSchemaEnv.Create(schema);
var parsed = env.Parse("roles.exists(r, r == 'admin') && name.startsWith('A')");
var check = env.Check(parsed.Ast!);
if (check.HasErrors)
{
throw new InvalidOperationException(string.Join("; ", check.Issues));
}
// Compute a bounded worst-case cost BEFORE ever running the expression
CostEstimate cost = env.EstimateCost(parsed.Ast!, provider.CostEstimator);
if (cost.IsUnbounded || cost.Max > 1_000)
{
throw new InvalidOperationException($"Expression exceeds cost budget: {cost}");
}If you created your environment with JsonSchemaEnv.CreateForVariable("req", schema), scope the estimator with .ForVariable("req"):
JsonSchemaCostEstimator estimator = provider.CostEstimator.ForVariable("req");
CostEstimate cost = env.EstimateCost(parsed.Ast!, estimator);Every EvalJson*, FilterJsonArray, and FilterJsonLines overload accepts an optional EvalLimits parameter from Celly to enforce runtime execution caps (such as maximum recursion depth or comprehension iterations):
var limits = new EvalLimits
{
MaxComprehensionIterations = 1_000,
};
bool allowed = program.EvalJsonBool(doc, limits: limits);Combining JSON Schema static type checking + JsonSchemaCostEstimator + runtime EvalLimits gives you defense-in-depth for untrusted rules.
Celly.Json — High-performance System.Text.Json adapter for Celly (.NET 10, NativeAOT-ready, MIT License).