Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions tools/migrate-apim/ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ A data-driven contract is only as good as the checking of it. Two claims used to
| Every rule field has a reader | Each field is one that some site able to select the rule declares it `reads` |
| Several rules about one subject add up | Two rules a site could apply to one subject name no different `capabilityId` or `target` — a subject has one of each, and combining would take one and never build the other — and the proposal their combination makes is one of the options it offers. Two rules looking alike to the site that selects them used to be the error; under first-match the second was dead data, and now it is ordinary |
| `where` stays three forms wide | Every predicate is equals, one of, or `{"nonEmpty": bool}` |
| Every `partialWhen` condition does something | Each condition a rule demotes on is one `plan._PARTIAL_WHEN` pairs with a predicate, and that set and the one `$defs.partialWhen` allows are equal in both directions. The schema said what was legal and the planner said what did anything, with nothing between them: a condition added to both the schema and a rule, with the predicate forgotten, validated and never fired, so the element kept the stronger verdict the rule existed to take away — and no test could catch it, because an inert rule has no behaviour to pin |

Three severities. **Errors** fail the command. **Warnings** — a field no site reads, a version that cannot be compared — are advisory, and `--strict` promotes them; `--strict` passes on the committed data, which is the only state in which it is worth having, since a mode that cannot pass is a mode nobody runs. **Suggestions** are never fatal, not even under `--strict`, and are counted apart from the tally so a clean compile still reads as clean.

Expand Down
10 changes: 9 additions & 1 deletion tools/migrate-apim/migrate_apim/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,15 @@ def _plan(args: argparse.Namespace) -> int:
print(f"error: existing plan at {args.output} is not valid JSON: {exc}", file=sys.stderr)
return 1

document = build_plan(inventory, capabilities, previous=previous, target=args.target)
try:
document = build_plan(inventory, capabilities, previous=previous, target=args.target)
except CapabilityError as exc:
# The planner refuses rules it cannot execute -- a `partialWhen`
# condition it does not implement is the one case today. Reported like
# every other capability-data failure in this command rather than as a
# traceback, because `--rules` is how a file that never compiled gets here.
print(f"error: {exc}", file=sys.stderr)
return 1
if not (document.get("target") or {}).get("resourceId"):
# Said here rather than discovered at preflight: every phase needs it,
# and the id is not something to guess at the point of writing.
Expand Down
73 changes: 73 additions & 0 deletions tools/migrate-apim/migrate_apim/compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,11 +538,83 @@ def check_policy_vocabulary(rules: dict[str, Any], out: Compilation) -> None:
)


def check_partial_when_conditions(rules: dict[str, Any], rules_schema: dict[str, Any],
out: Compilation) -> None:
"""Every `partialWhen` condition has to be one the planner implements.

`partialWhen` was the one part of the rules vocabulary with two independent
declarations and no join between them. The schema's `$defs.partialWhen`
decides which condition names are *legal*; `plan._PARTIAL_WHEN` decides
which ones *do* anything. `capability._POLICY_FIELDS` names `partialWhen`
among the fields a site reads, which is enough for `rule-field-unread` --
the field is read, and the condition names inside it were examined by
nothing.

So a condition added to the schema and written on a rule, with the predicate
forgotten, passed every gate and never fired: the element kept the stronger
verdict while the rule existed to say the mapping was lossy. Nothing could
catch it in a test either, because an inert rule has no behaviour to pin --
renaming the one condition that existed failed two tests, adding one that
never existed failed none. It is decidable here instead, offline, from
committed data.

Both directions against the schema, because each is a different mistake.
A key the schema allows and nothing implements is the inert rule waiting to
be written, and catching it as the schema is edited is cheaper than catching
it as the rule is. A condition implemented and not allowed is the opposite
failure: the rule that would use it is rejected for naming something that
works.
"""
implemented = set(_plan.PARTIAL_WHEN_CONDITIONS)
declared = set(
((rules_schema.get("$defs") or {}).get("partialWhen") or {}).get("properties") or {}
)
written = sum(
len(rule.get("partialWhen") or {})
for section in _SELECTED_SECTIONS for rule in rules.get(section) or []
)
out.cover(
f"{len(implemented)} partialWhen conditions the planner implements: the same set "
f"rules.schema.json allows, and each of the {written} a rule demotes on"
)

for section in _SELECTED_SECTIONS:
for rule in rules.get(section) or []:
for name in sorted(set(rule.get("partialWhen") or {}) - implemented):
out.error(
"partial-when-implemented",
f"{section} {_rule_label(rule)}: demotes on {name!r}, which "
f"`plan._apply_partial_when` does not implement, so the condition never "
f"holds and the element keeps the stronger verdict this rule exists to "
f"take away. Implemented: {sorted(implemented)}.",
)

for name in sorted(declared - implemented):
out.error(
"partial-when-implemented",
f"rules.schema.json allows partialWhen {name!r}, which "
f"`plan._apply_partial_when` does not implement. A rule naming it would validate "
f"and never fire. Give `plan._PARTIAL_WHEN` the predicate, or drop the key.",
)
for name in sorted(implemented - declared):
out.error(
"partial-when-declared",
f"`plan._apply_partial_when` implements partialWhen {name!r}, which "
f"rules.schema.json does not allow, so a rule naming a condition that works is "
f"rejected for its shape. Add it to $defs.partialWhen.properties.",
)


def _inventory_schema() -> dict[str, Any]:
path = Path(__file__).resolve().parent.parent / "schemas" / "inventory.schema.json"
return json.loads(path.read_text(encoding="utf-8"))


def _rules_schema() -> dict[str, Any]:
path = Path(__file__).resolve().parent.parent / "schemas" / "rules.schema.json"
return json.loads(path.read_text(encoding="utf-8"))


def check_subjects_have_rules(rules: dict[str, Any], out: Compilation) -> None:
"""Every path a site selects on has at least one rule answering it.

Expand Down Expand Up @@ -1009,6 +1081,7 @@ def compile_contract(
check_rules(catalog, rules, out)
check_where_operators(rules, out)
check_policy_vocabulary(rules, out)
check_partial_when_conditions(rules, _rules_schema(), out)
check_fragment_dispositions(rules, out)
check_subjects_have_rules(rules, out)
check_paths_are_fields(rules, _inventory_schema(), out)
Expand Down
77 changes: 60 additions & 17 deletions tools/migrate-apim/migrate_apim/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@
import hashlib
import ipaddress
import json
from typing import Any
from typing import Any, Callable

from . import ids
from . import policy as policy_mod
from .capability import CapabilityMap
from .capability import CapabilityError, CapabilityMap
from .detect import MCP_PATTERNS, PROJECTED_CONTRACTS, dialect_target, projected_contracts
from . import dispatch
from .dispatch import selector
Expand Down Expand Up @@ -3322,6 +3322,48 @@ def _name_of(document: dict[str, Any]) -> str | None:
return (document.get("scope") or {}).get("name")


def _is_expression(value: Any) -> bool:
"""Whether an attribute holds APIM's `@(...)` rather than a literal."""
return isinstance(value, str) and value.lstrip().startswith("@")


# Every condition `partialWhen` can name, each beside the test it runs. The
# mapping *is* the declaration: a condition exists exactly when it has an entry
# here, so there is no list to keep in step with the code -- the same reason
# `dispatch.Selector` both performs a match and states what the match looks at.
#
# It has to be stated at all because this vocabulary had two declarations and no
# join between them: `$defs.partialWhen` in rules.schema.json said what was
# *legal*, this function said what *did* anything, and nothing compared the two.
# Closing the schema to a named set only answered one direction. The other --
# adding a condition to the schema and to a rule and forgetting the predicate --
# compiled clean and left the rule inert, so an element kept the stronger
# verdict while the rule existed to say the mapping was lossy. That is a failed
# inference reading as a confident negative, which is the one way this tool must
# not fail. `compile.check_partial_when_conditions` reads this and holds both
# rules.json and the schema to it.
_PARTIAL_WHEN: dict[str, Callable[[Any, dict[str, Any], bool], bool]] = {
# The only condition whose value carries information: it names the attribute
# whose value has to be an expression, rather than asking about the element
# as a whole.
"attributeIsExpression": lambda attribute, element, _conditional: _is_expression(
(element.get("attributes") or {}).get(attribute or "")
),
"hasExpression": lambda _value, element, _conditional: bool(element.get("expressionIds")),
# The caller's branch counts as much as the element's own: a fragment pulled
# in under a `choose` runs conditionally however unconditionally its own body
# reads.
"underConditional": lambda _value, element, conditional: bool(
conditional or policy_mod.under_conditional(element)
),
}

PARTIAL_WHEN_CONDITIONS: tuple[str, ...] = tuple(_PARTIAL_WHEN)
"""The conditions the planner implements, derived from the predicates rather
than written down beside them, for `compile` to check the rules and the schema
against."""


def _apply_partial_when(
rule: dict[str, Any], element: dict[str, Any], *, under_conditional: bool = False
) -> dict[str, Any]:
Expand All @@ -3333,27 +3375,28 @@ def _apply_partial_when(
source picked the backend with an expression or inside a ``choose``,
because the pool holds the backends and not the rule that chose among them.

``under_conditional`` is the caller's, not the element's, because a branch
can be at the site that included the element rather than around the element
itself: a fragment pulled in under a ``choose`` runs conditionally however
unconditionally its own body reads.

Any one condition demotes. Requiring all of them would let an element that
trips a single one read as cleanly mapped, which is the reading this exists
to prevent.
to prevent. Only the conditions the rule names are asked, so a rule says
nothing by leaving one out.
"""
condition = rule.get("partialWhen")
if not condition:
return rule
attribute = condition.get("attributeIsExpression")
value = (element.get("attributes") or {}).get(attribute or "")
holds = (
(isinstance(value, str) and value.lstrip().startswith("@"))
or (condition.get("hasExpression") and bool(element.get("expressionIds")))
or (condition.get("underConditional")
and (under_conditional or policy_mod.under_conditional(element)))
)
if not holds:
unknown = sorted(set(condition) - set(_PARTIAL_WHEN))
if unknown:
# Loud rather than ignored. Skipping an unknown condition is precisely
# the inert rule this registry exists to make impossible, and silence
# would put it back one layer down. `compile` catches it offline for the
# bundled rules; `plan --rules` can still be pointed at a file that
# never compiled, and this is what that file gets.
raise CapabilityError(
f"a rule demotes on partialWhen {unknown}, which the planner does not implement, "
f"so the condition never holds and the element keeps the stronger verdict. "
f"It implements {list(_PARTIAL_WHEN)}. Run `migrate-apim compile` on these rules."
)
if not any(_PARTIAL_WHEN[name](value, element, under_conditional)
for name, value in condition.items()):
return rule
return {**rule, "verdict": "partial", **(rule.get("partial") or {})}

Expand Down
2 changes: 1 addition & 1 deletion tools/migrate-apim/schemas/rules.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@
"type": "object",
"additionalProperties": false,
"minProperties": 1,
"description": "What makes this mapping lossy for one element. Any one condition that holds demotes the rule to partial and overlays `partial` on it; requiring all of them would let an element that trips a single condition read as cleanly mapped. Each condition is named by `plan._apply_partial_when`, and a key it does not know would never fire while reading as though it did, so the set is closed here. The booleans take `true` only, for the same reason: there is no condition that holds by an element lacking an expression.",
"description": "What makes this mapping lossy for one element. Any one condition that holds demotes the rule to partial and overlays `partial` on it; requiring all of them would let an element that trips a single condition read as cleanly mapped. These keys are not a list kept here: `plan._PARTIAL_WHEN` pairs each condition with the test it runs, and `compile.check_partial_when_conditions` fails unless this set and that one are the same, in both directions. Closing the set here alone was not enough -- a key added here and written on a rule, with the predicate forgotten, validated and never fired, so the element kept the stronger verdict the rule existed to take away. The booleans take `true` only, for the same reason: there is no condition that holds by an element lacking an expression.",
"properties": {
"attributeIsExpression": {
"type": "string",
Expand Down
88 changes: 87 additions & 1 deletion tools/migrate-apim/tests/test_compile.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,6 +592,92 @@ def test_a_second_terminal_rule_is_no_longer_a_tie(self, compile_with, shipped):
assert "policy-terminal" not in codes(result)


class TestEveryPartialWhenConditionDoesSomething:
"""The vocabulary with two declarations and no join between them.

`$defs.partialWhen` in rules.schema.json said which condition names were
legal; `plan._PARTIAL_WHEN` says which ones do anything. Closing the schema
to a named set answered one direction only. The other -- adding a condition
to the schema and to a rule and forgetting the predicate -- passed every
gate and left the rule inert, so the element kept the stronger verdict while
the rule existed to say the mapping was lossy.

No test could have caught it. *Renaming* the one condition that existed
fails two tests in `test_plan.py`, because they pin its behaviour;
*adding* one that is never implemented has no behaviour to pin, and adding
conditions is how this vocabulary grows.
"""

def _widened(self, name="inUnconditionalSection"):
"""The schema with a condition nothing implements made legal."""
schema = copy.deepcopy(compile._rules_schema())
schema["$defs"]["partialWhen"]["properties"][name] = {
"const": True, "description": "A condition the planner never learned.",
}
return schema

def _demoting_on(self, rules, name):
"""The issue's repro: a native rule given a condition and an overlay."""
edited = copy.deepcopy(rules)
rule = next(r for r in edited["policies"] if r.get("id") == "policies/ip-filter")
rule["partialWhen"] = {name: True}
rule["partial"] = {
"answer": "choose",
"options": ["accept", "retain-in-apim"],
"proposal": "retain-in-apim",
"rationale": "Expression-driven filter.",
}
return edited

def test_a_rule_demoting_on_a_condition_nothing_implements_is_caught(self, shipped):
"""The whole repro, schema and rule together, planner untouched."""
_, rules, _ = shipped
out = compile.Compilation()
compile.check_partial_when_conditions(
self._demoting_on(rules, "inUnconditionalSection"), self._widened(), out)
messages = [d.message for d in out.errors if d.check == "partial-when-implemented"]
# Both halves named: the rule that would never fire, and the schema key
# that let it be written. Either alone leaves the reader guessing.
assert any("ip-filter" in m and "inUnconditionalSection" in m for m in messages)
assert any("rules.schema.json allows" in m for m in messages)

def test_the_rule_alone_is_enough_to_fail_the_shipped_compile(self, compile_with, shipped):
"""Through `compile_contract`, the way CI runs it."""
_, rules, _ = shipped
result = compile_with(rules=self._demoting_on(rules, "inUnconditionalSection"))
assert "partial-when-implemented" in codes(result)

def test_widening_the_schema_alone_is_caught_before_any_rule_uses_it(self, shipped):
"""Cheaper here than one rule later, and the edit that does it is this one."""
_, rules, _ = shipped
out = compile.Compilation()
compile.check_partial_when_conditions(rules, self._widened(), out)
[diagnostic] = [d for d in out.errors if d.check == "partial-when-implemented"]
assert "inUnconditionalSection" in diagnostic.message

def test_a_condition_the_schema_forbids_is_caught_too(self, shipped):
"""The opposite mistake: a condition that works, rejected for its shape."""
_, rules, _ = shipped
narrowed = copy.deepcopy(compile._rules_schema())
narrowed["$defs"]["partialWhen"]["properties"].pop("hasExpression")
out = compile.Compilation()
compile.check_partial_when_conditions(rules, narrowed, out)
[diagnostic] = [d for d in out.errors if d.check == "partial-when-declared"]
assert "hasExpression" in diagnostic.message

def test_the_shipped_schema_and_planner_name_the_same_set(self):
declared = set(compile._rules_schema()["$defs"]["partialWhen"]["properties"])
assert declared == set(plan_mod.PARTIAL_WHEN_CONDITIONS)

def test_the_shipped_rules_demote_on_nothing_inert(self, compile_with):
assert "partial-when-implemented" not in codes(compile_with())
assert "partial-when-declared" not in codes(compile_with())

def test_the_declaration_is_the_predicates_and_not_a_list_beside_them(self):
"""A list written out separately is the second declaration again."""
assert plan_mod.PARTIAL_WHEN_CONDITIONS == tuple(plan_mod._PARTIAL_WHEN)


class TestACleanRunSaysWhatItChecked:
"""A compile that only speaks up on failure leaves the reader of a green
run unable to tell thorough from vacuous -- and this contract shipped a
Expand All @@ -600,7 +686,7 @@ class TestACleanRunSaysWhatItChecked:
def test_every_check_reports_what_it_covered(self, compile_with, shipped):
documented = shipped[0]["cliEvidence"]["documentedVersion"]
covered = compile_with(newest_release=f"cli-v{documented}").covered
assert len(covered) == 13, covered
assert len(covered) == 14, covered

def test_the_counts_are_the_real_ones(self, compile_with, shipped):
catalog, rules, surface = shipped
Expand Down
Loading