diff --git a/.github/workflows/openapi-contract.yml b/.github/workflows/openapi-contract.yml index a11bb081..df41792e 100644 --- a/.github/workflows/openapi-contract.yml +++ b/.github/workflows/openapi-contract.yml @@ -36,6 +36,14 @@ jobs: python examples/openapi_contract/generate_schemas.py \ --output-dir "$RUNNER_TEMP/openapi-contract-schemas" + - name: Upload generated OpenAPI schemas for review + uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 + with: + name: versioned-openapi-contract-schemas + path: ${{ runner.temp }}/openapi-contract-schemas/ + if-no-files-found: error + retention-days: 7 + - name: Install pinned oasdiff run: | archive="$RUNNER_TEMP/oasdiff_1.38.0_linux_amd64.tar.gz" @@ -58,17 +66,10 @@ jobs: - name: Compare candidate schemas with committed version baselines run: | - oasdiff breaking --fail-on ERR \ + oasdiff breaking --fail-on WARN \ examples/openapi_contract/schemas/v1/openapi.yaml \ "$RUNNER_TEMP/openapi-contract-schemas/v1/openapi.yaml" - oasdiff breaking --fail-on ERR \ + oasdiff breaking --fail-on WARN \ examples/openapi_contract/schemas/v2/openapi.yaml \ "$RUNNER_TEMP/openapi-contract-schemas/v2/openapi.yaml" - - name: Upload generated OpenAPI schemas for review - uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6 - with: - name: versioned-openapi-contract-schemas - path: ${{ runner.temp }}/openapi-contract-schemas/ - if-no-files-found: error - retention-days: 7 diff --git a/docs/design/versioned-openapi-contract.md b/docs/design/versioned-openapi-contract.md index bf0de776..042a11ae 100644 --- a/docs/design/versioned-openapi-contract.md +++ b/docs/design/versioned-openapi-contract.md @@ -50,7 +50,7 @@ The CI sequence is: 2. Generate one schema for each supported API version. 3. Validate schemas and fail on unresolved introspection warnings. 4. Compare each candidate only with the matching released version baseline. -5. Run oasdiff breaking and fail on breaking changes to a stable contract. +5. Run oasdiff breaking with `--fail-on WARN`; both definite breaking changes (`ERR`) and potential breaking changes (`WARN`) block the contract gate. Review and justify any exception with a narrowly scoped severity override. 6. Review additive changes and update migration/release notes deliberately. A new API version starts with its own baseline. A breaking change to an existing diff --git a/examples/openapi_contract/README.md b/examples/openapi_contract/README.md index 60cc099c..1c6d4d17 100644 --- a/examples/openapi_contract/README.md +++ b/examples/openapi_contract/README.md @@ -17,8 +17,9 @@ python -m pip install -e ".[dev]" python -m pip install -r examples/openapi_contract/requirements.txt ~~~ -The example pins drf-spectacular 0.30.0. Its upstream project recommends -pinning the generator and reviewing schema diffs when upgrading. +The consumer example pins Django 5.2.19 (the current 5.2 LTS patch), +Django REST framework 3.18.3, and drf-spectacular 0.30.0. Upgrade these +versions deliberately and review regenerated schemas before changing the pins. ## Verify diff --git a/examples/openapi_contract/requirements.txt b/examples/openapi_contract/requirements.txt index 1d6c0bb2..0846ac09 100644 --- a/examples/openapi_contract/requirements.txt +++ b/examples/openapi_contract/requirements.txt @@ -1,3 +1,3 @@ -Django>=5.2,<5.3 -djangorestframework>=3.18,<3.19 +Django==5.2.19 +djangorestframework==3.18.3 drf-spectacular==0.30.0 diff --git a/examples/openapi_contract/verify_oasdiff.py b/examples/openapi_contract/verify_oasdiff.py index 946d84e8..a81296de 100644 --- a/examples/openapi_contract/verify_oasdiff.py +++ b/examples/openapi_contract/verify_oasdiff.py @@ -1,4 +1,4 @@ -"""Exercise oasdiff with a safe additive change and a deliberate breaking change.""" +"""Verify oasdiff's compatibility policy against focused OpenAPI fixtures.""" from __future__ import annotations @@ -6,10 +6,310 @@ import subprocess import tempfile from pathlib import Path +from typing import Any import yaml +def _document( + openapi: str, property_schema: dict[str, Any], direction: str +) -> dict[str, Any]: + payload = { + "type": "object", + "properties": {"value": property_schema}, + } + response_payload = ( + payload + if direction == "response" + else {"type": "object", "properties": {"value": {"type": "string"}}} + ) + operation: dict[str, Any] = { + "responses": { + "200": { + "description": "OK", + "content": {"application/json": {"schema": response_payload}}, + } + } + } + if direction == "request": + operation["requestBody"] = { + "required": True, + "content": {"application/json": {"schema": payload}}, + } + return { + "openapi": openapi, + "info": {"title": "Nullability fixture", "version": "1.0.0"}, + "paths": {"/test/": {"post": operation}}, + "components": { + "schemas": { + "Scalar": {"type": "string"}, + } + }, + } + + +def _write(document: dict[str, Any], path: Path) -> None: + path.write_text(yaml.safe_dump(document, sort_keys=False), encoding="utf-8") + + +def _run( + binary: Path, + base: Path, + revision: Path, + *, + flatten_allof: bool = False, + severity_levels: Path | None = None, +) -> subprocess.CompletedProcess[str]: + command = [str(binary), "breaking", "--fail-on", "WARN"] + if flatten_allof: + command.append("--flatten-allof") + if severity_levels is not None: + command.extend(["--severity-levels", str(severity_levels)]) + command.extend([str(base), str(revision)]) + return subprocess.run(command, text=True, capture_output=True, check=False) + + +def _assert_case( + binary: Path, + root: Path, + name: str, + *, + openapi: str, + before: dict[str, Any], + after: dict[str, Any], + direction: str, + expected_exit: int, + expected_check: str | None = None, + flatten_allof: bool = False, +) -> None: + case_dir = root / name + case_dir.mkdir() + base_path = case_dir / "base.yaml" + revision_path = case_dir / "revision.yaml" + _write(_document(openapi, before, direction), base_path) + _write(_document(openapi, after, direction), revision_path) + + result = _run( + binary, + base_path, + revision_path, + flatten_allof=flatten_allof, + ) + output = result.stdout + result.stderr + if result.returncode != expected_exit: + raise SystemExit( + f"{name}: expected exit {expected_exit}, got {result.returncode}:\n{output}" + ) + if expected_check is not None and expected_check not in output: + raise SystemExit( + f"{name}: expected check {expected_check!r} in oasdiff output:\n{output}" + ) + + +def _nullable_31() -> dict[str, Any]: + return {"type": ["string", "null"]} + + +def _nonnull_31() -> dict[str, Any]: + return {"type": "string"} + + +def _nullable_oneof() -> dict[str, Any]: + return {"oneOf": [{"type": "string"}, {"type": "null"}]} + + +def _nullable_anyof() -> dict[str, Any]: + return {"anyOf": [{"type": "string"}, {"type": "null"}]} + + +def _nullable_allof_30() -> dict[str, Any]: + return { + "nullable": True, + "allOf": [{"$ref": "#/components/schemas/Scalar"}], + } + + +def _nonnull_allof_30() -> dict[str, Any]: + return {"allOf": [{"$ref": "#/components/schemas/Scalar"}]} + + +def verify_nullability(binary: Path, root: Path) -> None: + # OpenAPI 3.0 nullable:true -> non-nullable. + _assert_case( + binary, + root, + "oas30-request-became-nonnullable", + openapi="3.0.3", + before={"type": "string", "nullable": True}, + after={"type": "string"}, + direction="request", + expected_exit=1, + expected_check="request-property-became-not-nullable", + ) + _assert_case( + binary, + root, + "oas30-response-became-nonnullable", + openapi="3.0.3", + before={"type": "string", "nullable": True}, + after={"type": "string"}, + direction="response", + expected_exit=0, + ) + + # OpenAPI 3.1 type unions: narrowing requests is breaking; narrowing + # responses is not. Widening responses is breaking; widening requests is not. + _assert_case( + binary, + root, + "oas31-request-became-nonnullable", + openapi="3.1.0", + before=_nullable_31(), + after=_nonnull_31(), + direction="request", + expected_exit=1, + expected_check="request-property-became-not-nullable", + ) + _assert_case( + binary, + root, + "oas31-response-became-nonnullable", + openapi="3.1.0", + before=_nullable_31(), + after=_nonnull_31(), + direction="response", + expected_exit=0, + ) + _assert_case( + binary, + root, + "oas31-request-became-nullable", + openapi="3.1.0", + before=_nonnull_31(), + after=_nullable_31(), + direction="request", + expected_exit=0, + ) + _assert_case( + binary, + root, + "oas31-response-became-nullable", + openapi="3.1.0", + before=_nonnull_31(), + after=_nullable_31(), + direction="response", + expected_exit=1, + expected_check="response-property-became-nullable", + ) + + # Composition forms. The pure oneOf wrapper is intentionally kept to + # oasdiff's documented two-branch recognition contract. + composition_cases = ( + ( + "oneof", + _nullable_oneof(), + "request-property-became-not-nullable", + "response-property-became-nullable", + ), + ( + "anyof", + _nullable_anyof(), + "request-property-list-of-types-narrowed", + "response-property-list-of-types-widened", + ), + ) + for name, nullable, request_check, response_check in composition_cases: + _assert_case( + binary, + root, + f"{name}-request-became-nonnullable", + openapi="3.1.0", + before=nullable, + after=_nonnull_31(), + direction="request", + expected_exit=1, + expected_check=request_check, + ) + _assert_case( + binary, + root, + f"{name}-response-became-nullable", + openapi="3.1.0", + before=_nonnull_31(), + after=nullable, + direction="response", + expected_exit=1, + expected_check=response_check, + ) + + # Keep nullable allOf/$ref detection separate from flattening tests. + # The pinned v1.38.0 binary is checked directly for this transition; + # separate constraints below exercise --flatten-allof semantics. + _assert_case( + binary, + root, + "allof-request-became-nonnullable", + openapi="3.0.3", + before=_nullable_allof_30(), + after=_nonnull_allof_30(), + direction="request", + expected_exit=1, + expected_check="request-property-became-not-nullable", + ) + _assert_case( + binary, + root, + "allof-flatten-request-min-length-increased", + openapi="3.0.3", + before={"allOf": [{"type": "string"}, {"minLength": 3}]}, + after={"allOf": [{"type": "string"}, {"minLength": 5}]}, + direction="request", + expected_exit=1, + expected_check="request-property-min-length-increased", + flatten_allof=True, + ) + _assert_case( + binary, + root, + "allof-flatten-response-min-length-decreased", + openapi="3.0.3", + before={"allOf": [{"type": "string"}, {"minLength": 5}]}, + after={"allOf": [{"type": "string"}, {"minLength": 3}]}, + direction="response", + expected_exit=1, + expected_check="response-property-min-length-decreased", + flatten_allof=True, + ) + + +def verify_warn_policy(binary: Path, root: Path) -> None: + # A request becoming nullable is normally INFO. Promote that known rule + # to WARN in a fixture to prove that --fail-on WARN actually blocks WARN + # findings, rather than merely documenting the intended policy. + case_dir = root / "warn-policy" + case_dir.mkdir() + base_path = case_dir / "base.yaml" + revision_path = case_dir / "revision.yaml" + severity_path = case_dir / "severity-levels.txt" + _write(_document("3.1.0", _nonnull_31(), "request"), base_path) + _write(_document("3.1.0", _nullable_31(), "request"), revision_path) + severity_path.write_text( + "request-property-became-nullable warn\n", encoding="utf-8" + ) + + result = _run( + binary, + base_path, + revision_path, + severity_levels=severity_path, + ) + output = result.stdout + result.stderr + if result.returncode != 1 or "request-property-became-nullable" not in output: + raise SystemExit( + "WARN policy fixture did not fail as required by --fail-on WARN:\n" + output + ) + + def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--oasdiff", type=Path, default=Path("oasdiff")) @@ -21,8 +321,6 @@ def main() -> None: with tempfile.TemporaryDirectory(prefix="oasdiff-contract-") as directory: root = Path(directory) - additive_path = root / "additive.yaml" - breaking_path = root / "breaking.yaml" additive = yaml.safe_load(yaml.safe_dump(base, sort_keys=False)) product = additive["components"]["schemas"]["ProductV1"] @@ -30,29 +328,15 @@ def main() -> None: "type": "string", "description": "An additive optional response field.", } - additive_path.write_text( - yaml.safe_dump(additive, sort_keys=False), encoding="utf-8" - ) + additive_path = root / "additive.yaml" + _write(additive, additive_path) breaking = yaml.safe_load(yaml.safe_dump(base, sort_keys=False)) del breaking["paths"]["/api/v1/products/"] - breaking_path.write_text( - yaml.safe_dump(breaking, sort_keys=False), encoding="utf-8" - ) + breaking_path = root / "breaking.yaml" + _write(breaking, breaking_path) - additive_result = subprocess.run( - [ - str(args.oasdiff), - "breaking", - "--fail-on", - "ERR", - str(base_path), - str(additive_path), - ], - text=True, - capture_output=True, - check=False, - ) + additive_result = _run(args.oasdiff, base_path, additive_path) if additive_result.returncode != 0: raise SystemExit( "oasdiff rejected an additive optional response field:\n" @@ -60,19 +344,7 @@ def main() -> None: + additive_result.stderr ) - breaking_result = subprocess.run( - [ - str(args.oasdiff), - "breaking", - "--fail-on", - "ERR", - str(base_path), - str(breaking_path), - ], - text=True, - capture_output=True, - check=False, - ) + breaking_result = _run(args.oasdiff, base_path, breaking_path) if breaking_result.returncode != 1: raise SystemExit( "oasdiff did not reject a deliberately removed operation " @@ -81,8 +353,13 @@ def main() -> None: + breaking_result.stderr ) - print("oasdiff accepted an additive optional response field.") - print("oasdiff rejected a deliberately removed API operation.") + verify_nullability(args.oasdiff, root) + verify_warn_policy(args.oasdiff, root) + + print("oasdiff accepted an additive optional response field.") + print("oasdiff rejected a deliberately removed API operation.") + print("oasdiff nullability direction and composition fixtures passed.") + print("oasdiff WARN findings are enforced by the CI failure policy.") if __name__ == "__main__":