Skip to content

Commit a78528d

Browse files
fix(api): fail closed on mistyped values and small negative doubles
Defaulting replaces a value whose type the schema does not allow with the schema's default, so `{"resources": "invalid"}` reached the declaration as an empty object and a guarded read reserved its fallback. The evaluator now checks every value against the kind's structural schema before defaulting it and refuses a mismatch. A double result was rounded up to millis before its sign was checked, so a negative figure smaller than a milli became zero. It is now refused before the conversion. Assisted-by: LLM Signed-off-by: Mattia Eleuteri <[email protected]>
1 parent 19a97e1 commit a78528d

2 files changed

Lines changed: 138 additions & 2 deletions

File tree

‎pkg/reservation/evaluator.go‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,11 @@ func (e *Evaluator) Evaluate(values map[string]any, env Environment) (ResourceLi
186186
}
187187

188188
defaulted := normalizeNumbers(values).(map[string]any)
189+
// Defaulting replaces a value of the wrong type with the schema's
190+
// default, which would turn a malformed spec into a smaller one.
191+
if err := checkTypes(defaulted, e.schema, ""); err != nil {
192+
return nil, err
193+
}
189194
if err := defaulting.Apply(&defaulted, e.schema); err != nil {
190195
return nil, fmt.Errorf("default values: %w", err)
191196
}
@@ -302,6 +307,11 @@ func toQuantity(v ref.Val) (resource.Quantity, error) {
302307
if math.IsNaN(f) || math.IsInf(f, 0) {
303308
return resource.Quantity{}, fmt.Errorf("not a finite number: %v", f)
304309
}
310+
// Rounding up would carry a negative figure smaller than a milli to
311+
// zero, past the sign check.
312+
if f < 0 {
313+
return resource.Quantity{}, fmt.Errorf("negative reservation %v", f)
314+
}
305315
return *resource.NewMilliQuantity(int64(math.Ceil(f*1000)), resource.DecimalSI), nil
306316
case types.String:
307317
q, err := resource.ParseQuantity(string(t))
@@ -314,6 +324,78 @@ func toQuantity(v ref.Val) (resource.Quantity, error) {
314324
}
315325
}
316326

327+
// checkTypes refuses a value whose JSON type the schema does not allow. It
328+
// runs on normalized values: an integer is an int64, any other number a
329+
// float64. A null is left to defaulting, which treats it as absent.
330+
func checkTypes(v any, s *structuralschema.Structural, path string) error {
331+
if s == nil || v == nil {
332+
return nil
333+
}
334+
if s.XIntOrString {
335+
switch v.(type) {
336+
case int64, string:
337+
return nil
338+
}
339+
return typeError(path, "an integer or a string", v)
340+
}
341+
switch s.Type {
342+
case "object":
343+
m, ok := v.(map[string]any)
344+
if !ok {
345+
return typeError(path, "an object", v)
346+
}
347+
for k, vv := range m {
348+
ps, known := s.Properties[k]
349+
switch {
350+
case known:
351+
if err := checkTypes(vv, &ps, path+"."+k); err != nil {
352+
return err
353+
}
354+
case s.AdditionalProperties != nil && s.AdditionalProperties.Structural != nil:
355+
if err := checkTypes(vv, s.AdditionalProperties.Structural, path+"."+k); err != nil {
356+
return err
357+
}
358+
}
359+
}
360+
case "array":
361+
sl, ok := v.([]any)
362+
if !ok {
363+
return typeError(path, "an array", v)
364+
}
365+
for i, vv := range sl {
366+
if err := checkTypes(vv, s.Items, fmt.Sprintf("%s[%d]", path, i)); err != nil {
367+
return err
368+
}
369+
}
370+
case "string":
371+
if _, ok := v.(string); !ok {
372+
return typeError(path, "a string", v)
373+
}
374+
case "integer":
375+
if _, ok := v.(int64); !ok {
376+
return typeError(path, "an integer", v)
377+
}
378+
case "number":
379+
switch v.(type) {
380+
case int64, float64:
381+
default:
382+
return typeError(path, "a number", v)
383+
}
384+
case "boolean":
385+
if _, ok := v.(bool); !ok {
386+
return typeError(path, "a boolean", v)
387+
}
388+
}
389+
return nil
390+
}
391+
392+
func typeError(path, want string, got any) error {
393+
if path == "" {
394+
path = "."
395+
}
396+
return fmt.Errorf("values%s: expected %s, got %T", path, want, got)
397+
}
398+
317399
// normalizeNumbers returns a copy of v in which every JSON number is an int64
318400
// when it is integral and a float64 otherwise. Without it every number in a
319401
// stored spec reaches CEL as a double, and replicas * quantity(...) would not

‎pkg/reservation/evaluator_test.go‎

Lines changed: 56 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func shippedSchema(t *testing.T, kind string) *structuralschema.Structural {
100100

101101
func testEnvironment(t *testing.T) Environment {
102102
t.Helper()
103-
env, err := NewStaticEnvironment(shippedInstancetypes(t), InstancetypeOptions{}, map[string]ResourceList{
103+
env, err := NewStaticEnvironment(shippedInstancetypes(t), map[string]ResourceList{
104104
"t1.nano": {"cpu": resource.MustParse("250m"), "memory": resource.MustParse("128Mi"), "ephemeral-storage": resource.MustParse("2Gi")},
105105
"t1.micro": {"cpu": resource.MustParse("500m"), "memory": resource.MustParse("256Mi"), "ephemeral-storage": resource.MustParse("2Gi")},
106106
})
@@ -267,6 +267,60 @@ func TestEvaluateFailsClosed(t *testing.T) {
267267
if _, err := negative.EvaluateJSON(nil, env); err == nil {
268268
t.Error("negative reservation: expected an error")
269269
}
270+
271+
// A negative double too small to survive rounding to millis is still
272+
// negative.
273+
tiny, err := Compile(&Declaration{Resources: map[string]string{"cpu": `-0.0001`}}, nil)
274+
if err != nil {
275+
t.Fatal(err)
276+
}
277+
if _, err := tiny.EvaluateJSON(nil, env); err == nil {
278+
t.Error("small negative reservation: expected an error, not a zero")
279+
}
280+
}
281+
282+
func TestEvaluateRejectsValuesOfTheWrongType(t *testing.T) {
283+
env := testEnvironment(t)
284+
// Defaulting replaces a value whose type does not match the schema with
285+
// the schema's own default, so the type is checked before it runs:
286+
// otherwise this guard would read an erased resources object and
287+
// reserve its fallback.
288+
ev, err := Compile(&Declaration{Resources: map[string]string{
289+
"cpu": `has(values.resources.cpu) ? values.resources.cpu : 1`,
290+
}}, shippedSchema(t, "postgres"))
291+
if err != nil {
292+
t.Fatal(err)
293+
}
294+
for _, raw := range []string{
295+
`{"resources": "invalid"}`,
296+
`{"resources": [1]}`,
297+
`{"resources": true}`,
298+
`{"resources": {"cpu": true}}`,
299+
`{"replicas": 2.5}`,
300+
`{"replicas": "2"}`,
301+
`{"external": "yes"}`,
302+
`{"postgresql": {"sharedPreloadLibraries": "pg_prewarm"}}`,
303+
`{"users": {"app": "admin"}}`,
304+
} {
305+
if got, err := ev.EvaluateJSON([]byte(raw), env); err == nil {
306+
t.Errorf("%s: expected an error, got %v", raw, got)
307+
}
308+
}
309+
for raw, want := range map[string]ResourceList{
310+
`{}`: rl("cpu", "1"),
311+
`{"resources": {}}`: rl("cpu", "1"),
312+
`{"resources": {"cpu": 2}}`: rl("cpu", "2"),
313+
`{"resources": {"cpu": "500m"}}`: rl("cpu", "500m"),
314+
`{"resources": null, "replicas": 3}`: rl("cpu", "1"),
315+
`{"users": {"app": {"replication": true}}}`: rl("cpu", "1"),
316+
} {
317+
got, err := ev.EvaluateJSON([]byte(raw), env)
318+
if err != nil {
319+
t.Errorf("%s: %v", raw, err)
320+
continue
321+
}
322+
assertList(t, raw, got, want)
323+
}
270324
}
271325

272326
func TestCompile(t *testing.T) {
@@ -308,7 +362,7 @@ func TestEvaluateIsConcurrencySafe(t *testing.T) {
308362
catalog := shippedInstancetypes(t)
309363
var wg sync.WaitGroup
310364
for _, it := range []string{"u1.small", "cx1.2xlarge", "o1.large", "u1.medium"} {
311-
want, err := ClassifyInstancetype(findInstancetype(t, catalog, it), InstancetypeOptions{})
365+
want, err := ClassifyInstancetype(findInstancetype(t, catalog, it))
312366
if err != nil {
313367
t.Fatal(err)
314368
}

0 commit comments

Comments
 (0)