diff --git a/changelog.d/602-strict-integer.md b/changelog.d/602-strict-integer.md new file mode 100644 index 00000000..ee0643e7 --- /dev/null +++ b/changelog.d/602-strict-integer.md @@ -0,0 +1,3 @@ +### Breaking + +- `cloudfall config validate` now refuses a whole-number float such as `8100.0` in any integer field, naming the field's path like any other schema error; before, it passed, and the command that read the value (`cloudfall domains apply` for a Domain's `spec.proxy.upstream.port`) crashed with `HANDLER_CRASHED`. One field worked with it: a Component's `spec.deployment.retainReleases: 2.0` validated and read as 2, and is now refused like the rest. Before upgrading, write those values as plain integers (`8100`, not `8100.0`; `retainReleases: 2`, not `2.0`); `cloudfall config validate` on the new release names each one (#602) diff --git a/sdk/src/cloudfall/domain.py b/sdk/src/cloudfall/domain.py index c2b1488e..bca68bb1 100644 --- a/sdk/src/cloudfall/domain.py +++ b/sdk/src/cloudfall/domain.py @@ -752,15 +752,9 @@ def __post_init__(self) -> None: @classmethod def from_boundary(cls, value: object) -> RetainReleases: - """Coerce an optional boundary value; absent (None) means 5. - - JSON Schema's ``integer`` accepts a number with no fraction, so a - validated ``2.0`` reads as 2; ``2.5`` is refused. - """ + """Coerce an optional boundary value; absent (None) means 5.""" if value is None: return cls(_RETAIN_RELEASES_DEFAULT) - if isinstance(value, float) and value.is_integer(): - value = int(value) if isinstance(value, bool) or not isinstance(value, int): message = f"retain releases must be an integer, got {type(value).__name__}" raise TypeError(message) diff --git a/sdk/src/cloudfall/validation.py b/sdk/src/cloudfall/validation.py index f2df80ee..e8af8a88 100644 --- a/sdk/src/cloudfall/validation.py +++ b/sdk/src/cloudfall/validation.py @@ -16,8 +16,9 @@ import yaml from cryptography import x509 -from jsonschema import Draft202012Validator, FormatChecker +from jsonschema import Draft202012Validator, FormatChecker, TypeChecker from jsonschema.exceptions import SchemaError, ValidationError +from jsonschema.validators import extend from referencing import Registry, Resource from cloudfall.clickhouse import MAX_REPLICAS as CLICKHOUSE_MAX_REPLICAS @@ -261,6 +262,26 @@ def as_dict(self) -> dict[str, object]: } +def _is_strict_integer(_checker: TypeChecker, instance: object) -> bool: + """Accept a Python ``int`` only: no ``bool``, no whole-number float.""" + return isinstance(instance, int) and not isinstance(instance, bool) + + +# The stock 2020-12 ``integer`` accepts ``8100.0``, which the value objects +# refuse with a TypeError in the command that reads it (#602). The extended +# class keeps the 2020-12 keywords, metaschema and interface; jsonschema's +# ``extend`` is untyped, hence the casts. +_StrictValidator = cast( + "type[Draft202012Validator]", + cast("Callable[..., object]", extend)( + Draft202012Validator, + type_checker=Draft202012Validator.TYPE_CHECKER.redefine( + "integer", _is_strict_integer + ), + ), +) + + class SchemaCatalog: """Validated v1 schemas and their reference registry.""" @@ -289,7 +310,7 @@ def __init__(self, schema_directory: Path) -> None: message=f"{path}: {error.message}", ) raise ConfigValidationError(issue) from error - named_validators[path.name] = Draft202012Validator( + named_validators[path.name] = _StrictValidator( schema, registry=registry, format_checker=FormatChecker(), diff --git a/sdk/tests/test_retain_releases.py b/sdk/tests/test_retain_releases.py index 7eee5f0a..89816563 100644 --- a/sdk/tests/test_retain_releases.py +++ b/sdk/tests/test_retain_releases.py @@ -54,8 +54,17 @@ def test_config_validate_accepts_a_count_of_at_least_two( @pytest.mark.parametrize( "retain", - [1, 0, -3, 2.5, 1.0, "5", True], - ids=["1", "0", "negative", "float", "integral-float-1", "string", "boolean"], + [1, 0, -3, 2.5, 1.0, 2.0, "5", True], + ids=[ + "1", + "0", + "negative", + "float", + "integral-float-1", + "integral-float-2", + "string", + "boolean", + ], ) def test_config_validate_refuses_a_count_below_two_or_not_an_integer( tmp_path: Path, capsys: pytest.CaptureFixture[str], retain: object @@ -66,13 +75,11 @@ def test_config_validate_refuses_a_count_below_two_or_not_an_integer( assert payload["error"]["context"]["code"] == "schema_validation_failed" -@pytest.mark.parametrize( - ("retain", "expected"), [(None, 5), (2, 2), (9, 9), (2.0, 2), (5.0, 5)] -) +@pytest.mark.parametrize(("retain", "expected"), [(None, 5), (2, 2), (9, 9)]) def test_the_inventory_carries_the_count_five_when_absent( - tmp_path: Path, retain: float | None, expected: int + tmp_path: Path, retain: int | None, expected: int ) -> None: - """``2.0`` is an integer to JSON Schema, so it validates and reads as 2.""" + """A declared count reads as itself; an absent one reads as 5.""" inventory = PlatformInventory.from_state( validate_config(_project(tmp_path, retain), SCHEMAS) ) @@ -83,7 +90,7 @@ def test_the_inventory_carries_the_count_five_when_absent( assert (type(carried), carried) == (int, expected) -@pytest.mark.parametrize("value", [1, 0, True, 1.0, 2.5, "5"]) +@pytest.mark.parametrize("value", [1, 0, True, 1.0, 2.0, 2.5, "5"]) def test_the_value_object_refuses_what_the_schema_refuses(value: object) -> None: with pytest.raises((ValueError, TypeError)): RetainReleases.from_boundary(value) diff --git a/sdk/tests/test_strict_integer.py b/sdk/tests/test_strict_integer.py new file mode 100644 index 00000000..38b5663b --- /dev/null +++ b/sdk/tests/test_strict_integer.py @@ -0,0 +1,84 @@ +"""An integer field refuses a whole-number float at `config validate` (#602).""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest +from cloudfall.cli import main +from examples_project import copy_examples + +ROOT = Path(__file__).parents[2] +SCHEMAS = ROOT / "config" / "schemas" / "v1" + +_UPSTREAM = " upstream:\n address: 127.0.0.1\n port: 8100\n" + + +def _project(tmp_path: Path, upstream: str) -> Path: + """Copy the examples and replace their Domain's upstream block.""" + project = tmp_path / "config" + copy_examples(project) + path = project / "domains" / "crm-site.yaml" + text = path.read_text(encoding="utf-8") + assert _UPSTREAM in text + path.write_text(text.replace(_UPSTREAM, upstream), encoding="utf-8") + return project + + +def _validate( + project: Path, capsys: pytest.CaptureFixture[str] +) -> tuple[int, dict[str, Any]]: + exit_code = main( + [ + "config", + "validate", + "--project", + str(project), + "--schemas", + str(SCHEMAS), + ] + ) + return exit_code, json.loads(capsys.readouterr().out) + + +def _port(value: str) -> str: + return f" upstream:\n address: 127.0.0.1\n port: {value}\n" + + +def _body_limit(value: str) -> str: + return f"{_UPSTREAM} maxRequestBodyMegabytes: {value}\n" + + +@pytest.mark.parametrize( + ("upstream", "field"), + [ + (_port("8100.0"), "spec.proxy.upstream.port"), + (_port("true"), "spec.proxy.upstream.port"), + (_body_limit("55.0"), "spec.proxy.maxRequestBodyMegabytes"), + ], + ids=["port-float", "port-bool", "body-limit-float"], +) +def test_a_float_or_bool_in_an_integer_field_is_refused_with_its_path( + tmp_path: Path, capsys: pytest.CaptureFixture[str], upstream: str, field: str +) -> None: + exit_code, payload = _validate(_project(tmp_path, upstream), capsys) + + assert exit_code == 80 + assert payload["error"]["code"] == "CONFIG_INVALID" + context = payload["error"]["context"] + assert context["code"] == "schema_validation_failed" + assert context["field"] == field + + +@pytest.mark.parametrize( + "upstream", [_port("8100"), _body_limit("55")], ids=["port", "body-limit"] +) +def test_a_plain_integer_still_passes( + tmp_path: Path, capsys: pytest.CaptureFixture[str], upstream: str +) -> None: + exit_code, payload = _validate(_project(tmp_path, upstream), capsys) + + assert exit_code == 0 + assert payload["data"]["status"] == "ok"