From c542135863b2fc213ed67500792848e8dbb1d3f7 Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Fri, 20 Nov 2026 20:37:01 +0000 Subject: [PATCH 1/2] fix(azure_policy): follow-ups to sub-resource array rewrapping Address review comments left open when #958 merged: - Record a plain alias's write only when it succeeds, so a write refused by an array on the way does not hide the arrays there from rewrapping. - Track rewrap targets and writes by the keys as written. Plain aliases whose ARM keys differ only in case write different arrays, and both are rewrapped. Lookups try the exact key first. - Keep a wrapped field's ARM name inside `properties` even when an unwrapped field's short name is the same. - When an array rename supplies a plain alias's value (its ARM key has different casing), read the alias's own ARM value instead of the renamed one, so each wrapper is flattened once, arrays that are sub-resource arrays only under the source name keep their wrappers, and the source name's remaps do not leak into the alias. Then apply the remaps rooted at the alias. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- CHANGELOG.md | 1 + .../azure_policy/aliases/denormalizer/mod.rs | 9 +- .../aliases/denormalizer/sub_resource.rs | 114 +++-- .../aliases/normalizer/alias_resolution.rs | 59 ++- src/languages/azure_policy/aliases/obj_map.rs | 34 +- .../cases/data_plane_sub_resources.yaml | 30 ++ .../cases/normalize_sub_resources.yaml | 447 ++++++++++++++++++ 7 files changed, 633 insertions(+), 61 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f814df88..5569c2a27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- *(azure_policy)* Sub-resource arrays are re-wrapped when a plain alias write is refused or ARM keys differ only in case, wrapped fields stay inside `properties`, and a plain alias whose ARM key has different casing normalizes like a matching key. - *(rvm)* Package values such as `data.pkg` omit undefined rules and include subpackages that have no rules (as `{}`), matching OPA and the interpreter. ## [0.15.0](https://github.com/microsoft/regorus/compare/regorus-v0.14.1...regorus-v0.15.0) - 2026-11-07 diff --git a/src/languages/azure_policy/aliases/denormalizer/mod.rs b/src/languages/azure_policy/aliases/denormalizer/mod.rs index b048fad46..a6299ac7a 100644 --- a/src/languages/azure_policy/aliases/denormalizer/mod.rs +++ b/src/languages/azure_policy/aliases/denormalizer/mod.rs @@ -154,11 +154,12 @@ pub fn denormalize_with_aliases( let arm_path = entry.select_path(api_version); let denorm_val = denormalize_value(val, &casing_map); + // A write refused by a non-object on the way leaves no value. if let Some(props_path) = arm_path.strip_prefix("properties.") { - set_nested_verbatim(&mut properties, props_path, denorm_val); - writes.record_alias(false, props_path, lc_key); - } else { - set_nested_verbatim(&mut result, arm_path, denorm_val); + if set_nested_verbatim(&mut properties, props_path, denorm_val) { + writes.record_alias(false, props_path, lc_key); + } + } else if set_nested_verbatim(&mut result, arm_path, denorm_val) { writes.record_alias(true, arm_path, lc_key); } } diff --git a/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs b/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs index de69d41dc..8f720d5a2 100644 --- a/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs +++ b/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs @@ -18,13 +18,14 @@ use super::helpers::find_key_ci; /// Sub-resource array element envelope fields that remain at the element root. const ELEMENT_ENVELOPE_FIELDS: &[&str] = &["name", "type", "id", "etag"]; -/// The keys leading to a sub-resource array, and the envelope fields of each -/// sub-resource short name that resolves there. -type Target<'a> = (Vec<&'a str>, BTreeMap<&'a str, BTreeSet>); +/// The envelope fields of each sub-resource short name that resolves to one +/// array. +type Target<'a> = BTreeMap<&'a str, BTreeSet>; /// The writes of phases 2a, 2b and 2c, in order. Each records where it wrote -/// (`true` for the ARM root rather than `properties`, then lowercase keys) -/// and the normalized key whose value it wrote. +/// (`true` for the ARM root rather than `properties`, then the keys as +/// written, since keys differing only in case are distinct) and the +/// lowercase normalized key whose value it wrote. #[derive(Debug, Default)] pub struct Writes { aliases: BTreeSet, @@ -35,14 +36,14 @@ impl Writes { /// Record writing the value of normalized key `source` at the dotted /// path `keys`. pub fn record(&mut self, at_root: bool, keys: &str, source: &str) { - let keys = keys.split('.').map(str::to_ascii_lowercase).collect(); + let keys = keys.split('.').map(String::from).collect(); self.log.push((at_root, keys, source.to_ascii_lowercase())); } /// Record writing the value of normalized key `source` at the single, /// possibly dotted, key `key`. pub fn record_key(&mut self, at_root: bool, key: &str, source: &str) { - let keys = alloc::vec![key.to_ascii_lowercase()]; + let keys = alloc::vec![String::from(key)]; self.log.push((at_root, keys, source.to_ascii_lowercase())); } @@ -53,7 +54,7 @@ impl Writes { } /// Whether a write of some other normalized name than `name` (dotted - /// lowercase keys) left the value now at `keys`. + /// keys) left the value now at `keys`. pub fn replaced(&self, at_root: bool, keys: &[String], name: &[String]) -> bool { let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); self.survivor(at_root, &keys) @@ -62,16 +63,18 @@ impl Writes { /// The normalized name of the value now at `keys`: the source of the /// last write at or above `keys`, followed by the keys below it. `None` - /// if nothing was written there. + /// if nothing was written there. Writes to exactly `keys` come first; + /// keys from normalized names match the written keys in any case. fn survivor(&self, at_root: bool, keys: &[&str]) -> Option { - let (_, written, source) = self.log.iter().rev().find(|(root, written, _)| { - *root == at_root - && written.len() <= keys.len() - && written - .iter() - .zip(keys) - .all(|(dest, key)| key.eq_ignore_ascii_case(dest)) - })?; + let last_write = |same: fn(&str, &str) -> bool| { + self.log.iter().rev().find(|(root, written, _)| { + *root == at_root + && written.len() <= keys.len() + && written.iter().zip(keys).all(|(dest, key)| same(dest, key)) + }) + }; + let (_, written, source) = last_write(|dest, key| dest == key) + .or_else(|| last_write(|dest, key| dest.eq_ignore_ascii_case(key)))?; let below = keys.get(written.len()..).unwrap_or_default(); let name: Vec<&str> = core::iter::once(source.as_str()) .chain(below.iter().copied()) @@ -108,25 +111,26 @@ pub fn rewrap_sub_resource_arrays( .collect(); // Several short names can resolve to the same array (two plain aliases - // with one ARM path). Wrap each array once. + // with one ARM path). Wrap each array once. Keys differing only in case + // are different arrays, so group by the keys actually in the output. let mut targets: BTreeMap<(bool, Vec), Target<'_>> = BTreeMap::new(); for sub_array_path in sub_arrays { let envelope_fields = classify_envelope_fields(sub_array_path, &parsed); let (at_root, keys) = written_keys(sub_array_path, entries, api_version, writes, is_data_plane); - let id = keys.iter().map(|key| key.to_ascii_lowercase()).collect(); + let map = if at_root { &*result } else { &*properties }; targets - .entry((at_root, id)) - .or_insert_with(|| (keys, BTreeMap::new())) - .1 + .entry((at_root, output_keys(map, &keys))) + .or_default() .insert(sub_array_path.as_str(), envelope_fields); } // Deepest first, so an outer array is wrapped after the arrays inside it. let mut sorted: Vec<_> = targets.into_iter().collect(); - sorted.sort_by_key(|((_, id), _)| core::cmp::Reverse(id.len())); + sorted.sort_by_key(|((_, keys), _)| core::cmp::Reverse(keys.len())); - for ((at_root, _), (keys, by_name)) in sorted { + for ((at_root, keys), by_name) in sorted { + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); // A later write may have replaced the flattened array with a value // the normalizer left wrapped (another plain alias with the same ARM // path, or one over the array's parent). Wrap only a flattened array. @@ -154,12 +158,54 @@ pub fn rewrap_sub_resource_arrays( } else { &mut *properties }; - if let Some(key) = find_key_ci(map, first) { - if let Some(value) = map.get_mut(key.as_ref()) { - rewrap_at(value, rest, &envelope_fields); + let key = if map.contains_key(*first) { + Some(crate::Rc::from(*first)) + } else { + find_key_ci(map, first) + }; + if let Some(value) = key.and_then(|key| map.get_mut(key.as_ref())) { + rewrap_at(value, rest, &envelope_fields); + } + } +} + +/// The keys in `map` that `keys` lead to: each key as it is in the output +/// (exact match first, else any case), as far as objects go. Keys inside +/// arrays are matched per element and kept as given. +fn output_keys(map: &ObjMap, keys: &[&str]) -> Vec { + let mut out = Vec::with_capacity(keys.len()); + let mut current: Option<&Value> = None; + for (i, key) in keys.iter().enumerate() { + let found = match current { + None => { + let exact = map.get_key_value(*key); + exact + .or_else(|| find_key_ci(map, key).and_then(|k| map.get_key_value(k.as_ref()))) + .map(|(k, v)| (String::from(k.as_ref()), v)) + } + Some(Value::Object(obj)) => find_key_ci_btree(obj, key).and_then(|k| { + let name = String::from(val_str(&k)?); + Some((name, obj.get(&k)?)) + }), + Some(_) => None, + }; + match found { + Some((name, value)) => { + out.push(name); + current = Some(value); + } + None => { + out.extend( + keys.get(i..) + .unwrap_or_default() + .iter() + .map(|k| String::from(*k)), + ); + break; } } } + out } /// Where a sub-resource array sits in the denormalized output: `true` for @@ -278,8 +324,12 @@ fn classify_envelope_fields( } } // A name that is also a wrapped field's ARM name stays wrapped, as it was - // before phase 2d gave fields their ARM names. - envelope.extend(unwrapped.difference(&wrapped).cloned()); + // before phase 2d gave fields their ARM names, whether it came from an + // ARM name or a short name. The standard envelope fields stay. + envelope.extend(unwrapped); + envelope.retain(|field| { + !wrapped.contains(field) || ELEMENT_ENVELOPE_FIELDS.contains(&field.as_str()) + }); envelope } @@ -338,8 +388,12 @@ fn rewrap_at(value: &mut Value, keys: &[&str], envelope_fields: &BTreeSet Option { + let exact = Value::String(crate::Rc::from(key)); + if btree.contains_key(&exact) { + return Some(exact); + } btree .keys() .find(|k| val_str(k).is_some_and(|s| s.eq_ignore_ascii_case(key))) diff --git a/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs b/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs index 4186a5e03..7ab2317d9 100644 --- a/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs +++ b/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs @@ -79,19 +79,37 @@ pub fn apply_alias_entries( if let Some(val) = obj_remove(result, source_lc.as_str()) { // A plain alias the loop above did not resolve (for example, // its ARM key has different casing) gets its value here. - // Flatten it the same way, since the denormalizer re-wraps - // where the alias writes. - let is_plain_alias = entries.get(target_lc.as_str()).is_some_and(|entry| { - !entry.is_wildcard - && !sub_resource_set.contains(target_lc.as_str()) - && !is_root_field_collision(&entry.short_name, &entry.default_path) - }); - let val = if is_plain_alias { - normalize_value(&val, target_lc, Some(sub_resource_set)) - } else { - val + // `val` was flattened for the source name and rewritten by + // the source's remaps, so resolve the alias's own ARM value + // the way the loop above would have. + let resolved = entries + .get(target_lc.as_str()) + .filter(|entry| { + !entry.is_wildcard + && !sub_resource_set.contains(target_lc.as_str()) + && !is_root_field_collision(&entry.short_name, &entry.default_path) + }) + .and_then(|entry| { + let segments = entry.select_path_segments(api_version); + let value = navigate_arm_path_segments_ci(raw, segments)?; + Some(normalize_value( + &value, + &entry.short_name, + Some(sub_resource_set), + )) + }); + let Some(resolved) = resolved else { + obj_insert(result, target_lc, val); + continue; }; - obj_insert(result, target_lc, val); + obj_insert(result, target_lc, resolved); + // The remaps above ran before this value had its alias name. + for remap in &agg.element_remaps { + let root = remap.array_chain.first().and_then(|nav| nav.first()); + if root.is_some_and(|root| root == target_lc) { + apply_element_remap_precomputed(result, remap); + } + } } } } @@ -108,3 +126,20 @@ fn navigate_arm_path_segments(value: &Value, segments: &[Rc]) -> Option]) -> Option { + let mut current = value; + for segment in segments { + let obj = current.as_object().ok()?; + current = match obj.get(&Value::String(Rc::clone(segment))) { + Some(v) => v, + None => obj.iter().find_map(|(k, v)| { + matches!(k, Value::String(s) if s.eq_ignore_ascii_case(segment)).then_some(v) + })?, + }; + } + Some(current.clone()) +} diff --git a/src/languages/azure_policy/aliases/obj_map.rs b/src/languages/azure_policy/aliases/obj_map.rs index 1e87acd19..6f675913c 100644 --- a/src/languages/azure_policy/aliases/obj_map.rs +++ b/src/languages/azure_policy/aliases/obj_map.rs @@ -201,25 +201,25 @@ pub fn set_nested_lowercased(result: &mut ObjMap, path: &str, value: Value) { /// Set a value at a dot-separated path in an [`ObjMap`], creating /// intermediate `Value::Object` nodes as needed. Keys preserve their casing. -pub fn set_nested_verbatim(result: &mut ObjMap, path: &str, value: Value) { +/// Returns `false` if an intermediate value is not an object, in which case +/// nothing is written. +pub fn set_nested_verbatim(result: &mut ObjMap, path: &str, value: Value) -> bool { let segments: Vec<&str> = path.split('.').collect(); - if segments.is_empty() { - return; - } if segments.len() == 1 { if let Some(&seg) = segments.first() { obj_insert(result, seg, value); + return true; } - return; + return false; } - set_nested_inner(result, &segments, value, false); + set_nested_inner(result, &segments, value, false) } /// Core implementation of nested-set. Navigates the first N-1 segments, /// creating intermediate objects, then inserts the value at the last segment. -fn set_nested_inner(obj: &mut ObjMap, segments: &[&str], value: Value, lowercase: bool) { +fn set_nested_inner(obj: &mut ObjMap, segments: &[&str], value: Value, lowercase: bool) -> bool { let Some(&first) = segments.first() else { - return; + return false; }; if segments.len() == 1 { @@ -229,7 +229,7 @@ fn set_nested_inner(obj: &mut ObjMap, segments: &[&str], value: Value, lowercase Rc::from(first) }; obj_insert_rc(obj, key, value); - return; + return true; } let seg: Rc = if lowercase { @@ -246,23 +246,26 @@ fn set_nested_inner(obj: &mut ObjMap, segments: &[&str], value: Value, lowercase // Descend directly into the BTreeMap, avoiding ObjMap round-trip. if let Some(Value::Object(inner_rc)) = obj.get_mut(&*seg) { let inner_btree = Rc::make_mut(inner_rc); - set_nested( + return set_nested( inner_btree, segments.get(1..).unwrap_or_default(), value, lowercase, ); } + false } /// Set a value at a path directly in an `Object`, creating /// intermediate `Value::Object` nodes as needed. /// /// This avoids the `btree_to_obj_map` / `obj_map_to_btree` round-trip that -/// would clone every sibling entry at each nesting level. -pub fn set_nested(obj: &mut Object, segments: &[&str], value: Value, lowercase: bool) { +/// would clone every sibling entry at each nesting level. Returns `false` +/// if an intermediate value is not an object, in which case nothing is +/// written. +pub fn set_nested(obj: &mut Object, segments: &[&str], value: Value, lowercase: bool) -> bool { let Some(&first) = segments.first() else { - return; + return false; }; let key_rc: Rc = if lowercase { @@ -274,7 +277,7 @@ pub fn set_nested(obj: &mut Object, segments: &[&str], value: Value, lowercase: if segments.len() == 1 { obj.insert(key_val, value); - return; + return true; } // Ensure an intermediate object exists. @@ -284,13 +287,14 @@ pub fn set_nested(obj: &mut Object, segments: &[&str], value: Value, lowercase: if let Some(Value::Object(inner_rc)) = obj.get_mut(&key_val) { let inner = Rc::make_mut(inner_rc); - set_nested( + return set_nested( inner, segments.get(1..).unwrap_or_default(), value, lowercase, ); } + false } /// Fields that exist at the ARM resource root (not under `properties`). diff --git a/tests/azure_policy/normalization/cases/data_plane_sub_resources.yaml b/tests/azure_policy/normalization/cases/data_plane_sub_resources.yaml index 5c678b57d..b68b28402 100644 --- a/tests/azure_policy/normalization/cases/data_plane_sub_resources.yaml +++ b/tests/azure_policy/normalization/cases/data_plane_sub_resources.yaml @@ -191,3 +191,33 @@ cases: y: - rawz: 1 round_trip: true + + - note: a refused plain alias write at the resource root does not stop re-wrapping + aliases_json: | + [ + { + "namespace": "Test.Data", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test.Data/widgets/b", "defaultPath": "x.y", "paths": [] }, + { "name": "Test.Data/widgets/x[*].y[*].z", "defaultPath": "x[*].y[*].properties.z", "paths": [] } + ] + } + ] + } + ] + input: + type: "Test.Data/widgets" + x: + - y: + - z: 1 + b: 2 + # `x` is an array, so `b` has nowhere to go and is dropped. + expected_denormalized: + type: "Test.Data/widgets" + x: + - y: + - properties: + z: 1 diff --git a/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml b/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml index 1dec6f180..c11388ca1 100644 --- a/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml +++ b/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml @@ -1308,6 +1308,14 @@ cases: - name: one properties: rawz: 1 + # The array base rename supplies `x`; its elements are flattened and + # remapped like those of a matching key. + expected_normalized: + type: "Test/widgets" + x: + - y: + - name: one + z: 1 round_trip: true # The array base rename supplies `x`, and the key comes back with the # casing of the plain alias's ARM path. @@ -1353,6 +1361,12 @@ cases: - rawState: s properties: z: 1 + expected_normalized: + type: "Test/widgets" + x: + - subnets: + - state: s + z: 1 round_trip: true # The unwrapped `rawState` stays at the element root. The key comes back # with the casing of the plain alias's ARM path. @@ -1364,3 +1378,436 @@ cases: - rawState: s properties: z: 1 + + - note: a plain alias whose write is refused does not stop the arrays under it from being re-wrapped + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/b", "defaultPath": "properties.x.y", "paths": [] }, + { + "name": "Test/widgets/x[*].k", + "defaultPath": "properties.x[*].properties.k", + "paths": [] + }, + { + "name": "Test/widgets/x[*].y[*].z", + "defaultPath": "properties.x[*].properties.y[*].properties.z", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + x: + - y: + - z: 1 + b: 2 + # `x` is an array, so `b` cannot be written under it. The elements of + # `x.y` still get their wrappers back. + expected_denormalized: + type: "Test/widgets" + properties: + x: + - properties: + y: + - properties: + z: 1 + + - note: plain aliases whose ARM keys differ only in case re-wrap both arrays + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/x", "defaultPath": "properties.Items", "paths": [] }, + { "name": "Test/widgets/w", "defaultPath": "properties.items", "paths": [] }, + { + "name": "Test/widgets/x[*].y[*].z", + "defaultPath": "properties.Items[*].y[*].properties.z", + "paths": [] + }, + { + "name": "Test/widgets/w[*].y[*].z", + "defaultPath": "properties.items[*].y[*].properties.z", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + x: + - y: + - name: one + z: 1 + w: + - y: + - name: two + z: 2 + expected_denormalized: + type: "Test/widgets" + properties: + Items: + - y: + - name: one + properties: + z: 1 + items: + - y: + - name: two + properties: + z: 2 + + - note: an unwrapped field whose short name is a wrapped field's ARM name does not unwrap it + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/config", "defaultPath": "properties.config", "paths": [] }, + { + "name": "Test/widgets/config.rules[*].rawstatus", + "defaultPath": "properties.config.rules[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/config.rules[*].other", + "defaultPath": "properties.config.rules[*].properties.rawstatus", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + properties: + config: + rules: + - properties: + rawstatus: 1 + expected_normalized: + type: "Test/widgets" + config: + rules: + - other: 1 + round_trip: true + expected_round_trip: + type: "Test/widgets" + properties: + config: + rules: + - properties: + rawstatus: 1 + + - note: a renaming plain alias with a differently cased ARM key flattens each wrapper once + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/a", "defaultPath": "properties.items", "paths": [] }, + { + "name": "Test/widgets/a[*].y[*].z", + "defaultPath": "properties.items[*].y[*].properties.z", + "paths": [] + }, + { + "name": "Test/widgets/items[*].y[*].k", + "defaultPath": "properties.items[*].y[*].properties.k", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + properties: + Items: + - y: + - name: one + properties: + z: 1 + properties: + keep: true + # `items.y` and `a.y` are both sub-resource arrays. Each element's wrapper + # is consumed once, so the payload's own `properties` stays. + expected_normalized: + type: "Test/widgets" + a: + - y: + - name: one + z: 1 + properties: + keep: true + round_trip: true + expected_round_trip: + type: "Test/widgets" + properties: + items: + - y: + - name: one + properties: + z: 1 + properties: + keep: true + + - note: a renaming plain alias with a differently cased ARM key keeps wrappers flattened only under the source name + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/a", "defaultPath": "properties.items", "paths": [] }, + { "name": "Test/widgets/a[*].y[*].z", "defaultPath": "properties.items[*].y[*].z", "paths": [] }, + { + "name": "Test/widgets/items[*].y[*].k", + "defaultPath": "properties.items[*].y[*].properties.k", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + properties: + Items: + - y: + - z: 1 + properties: + k: 2 + # `a.y` is not a sub-resource array, so its elements keep `properties`, + # as they do when the input key is `items`. + expected_normalized: + type: "Test/widgets" + a: + - y: + - z: 1 + properties: + k: 2 + round_trip: true + expected_round_trip: + type: "Test/widgets" + properties: + items: + - y: + - z: 1 + properties: + k: 2 + + - note: a renaming plain alias with a differently cased ARM key ignores the source name's remaps + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/a", "defaultPath": "properties.items", "paths": [] }, + { "name": "Test/widgets/a[*].d", "defaultPath": "properties.items[*].c", "paths": [] }, + { "name": "Test/widgets/items[*].c", "defaultPath": "properties.items[*].b", "paths": [] } + ] + } + ] + } + ] + input: + type: "Test/widgets" + properties: + Items: + - b: 1 + c: 2 + # `a[*].d` reads ARM `c`, not the `b` that the `items[*].c` remap moved. + expected_normalized: + type: "Test/widgets" + a: + - b: 1 + d: 2 + + - note: a write to a differently cased key does not stop an array from being re-wrapped + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/x", "defaultPath": "properties.Items", "paths": [] }, + { "name": "Test/widgets/z", "defaultPath": "properties.items", "paths": [] }, + { + "name": "Test/widgets/x[*].y[*].k", + "defaultPath": "properties.Items[*].y[*].properties.k", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + x: + - y: + - name: one + k: 1 + z: s + expected_denormalized: + type: "Test/widgets" + properties: + Items: + - y: + - name: one + properties: + k: 1 + items: s + + - note: nested plain aliases whose ARM keys differ only in case re-wrap both arrays + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/x", "defaultPath": "properties.cfg.Items", "paths": [] }, + { "name": "Test/widgets/w", "defaultPath": "properties.cfg.items", "paths": [] }, + { + "name": "Test/widgets/x[*].y[*].z", + "defaultPath": "properties.cfg.Items[*].y[*].properties.z", + "paths": [] + }, + { + "name": "Test/widgets/w[*].y[*].z", + "defaultPath": "properties.cfg.items[*].y[*].properties.z", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + x: + - y: + - name: one + z: 1 + w: + - y: + - name: two + z: 2 + expected_denormalized: + type: "Test/widgets" + properties: + cfg: + Items: + - y: + - name: one + properties: + z: 1 + items: + - y: + - name: two + properties: + z: 2 + + - note: arrays under ARM keys that differ only in case both round-trip + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/x", "defaultPath": "properties.Items", "paths": [] }, + { "name": "Test/widgets/w", "defaultPath": "properties.items", "paths": [] }, + { + "name": "Test/widgets/x[*].y[*].z", + "defaultPath": "properties.Items[*].y[*].properties.z", + "paths": [] + }, + { + "name": "Test/widgets/w[*].y[*].z", + "defaultPath": "properties.items[*].y[*].properties.z", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + properties: + Items: + - y: + - name: one + properties: + z: 1 + items: + - y: + - name: two + properties: + z: 2 + round_trip: true + + - note: a wrapped field whose ARM name is a standard envelope field stays at the element root + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/x[*].label", "defaultPath": "properties.x[*].properties.name", "paths": [] }, + { "name": "Test/widgets/x[*].z", "defaultPath": "properties.x[*].properties.z", "paths": [] } + ] + } + ] + } + ] + input: + type: "Test/widgets" + x: + - name: one + z: 1 + # `name` is ambiguous here; the element's own name wins. + expected_denormalized: + type: "Test/widgets" + properties: + x: + - name: one + properties: + z: 1 From 743da914bfdb67468bce6475909739c49fefa974 Mon Sep 17 00:00:00 2001 From: snehabandla <62899142+snehabandla@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:38:06 +0000 Subject: [PATCH 2/2] azure_policy: address review of sub-resource re-wrapping - Resolve an ancestor write through the output keys, so a reverse remap that differs only in case is not hidden by it. - Restore the casing of short-name keys before matching written keys, so a scalar sibling that differs only in case does not block re-wrapping. - Decide per element whether a field both a wrapped and an unwrapped alias name came from the wrapped one. - Keep the ARM-named key when a mixed-case array is renamed, as for a matching case. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../aliases/denormalizer/helpers.rs | 7 +- .../azure_policy/aliases/denormalizer/mod.rs | 51 ++- .../aliases/denormalizer/sub_resource.rs | 380 +++++++++++++----- .../aliases/normalizer/alias_resolution.rs | 3 + src/languages/azure_policy/aliases/obj_map.rs | 2 +- .../cases/normalize_sub_resources.yaml | 319 +++++++++++++++ 6 files changed, 628 insertions(+), 134 deletions(-) diff --git a/src/languages/azure_policy/aliases/denormalizer/helpers.rs b/src/languages/azure_policy/aliases/denormalizer/helpers.rs index 22c81a357..18b4ef603 100644 --- a/src/languages/azure_policy/aliases/denormalizer/helpers.rs +++ b/src/languages/azure_policy/aliases/denormalizer/helpers.rs @@ -5,9 +5,10 @@ use crate::Rc; -use super::super::obj_map::ObjMap; +use super::super::obj_map::{obj_key_ci, ObjMap}; -/// Find a key in an ObjMap using case-insensitive comparison. +/// Find a key in an ObjMap: `key` itself, else the smallest key that +/// differs only in ASCII case, so the choice does not depend on map order. pub fn find_key_ci(obj: &ObjMap, key: &str) -> Option> { - obj.keys().find(|k| k.eq_ignore_ascii_case(key)).cloned() + obj_key_ci(obj, key) } diff --git a/src/languages/azure_policy/aliases/denormalizer/mod.rs b/src/languages/azure_policy/aliases/denormalizer/mod.rs index a6299ac7a..a17889b5e 100644 --- a/src/languages/azure_policy/aliases/denormalizer/mod.rs +++ b/src/languages/azure_policy/aliases/denormalizer/mod.rs @@ -105,15 +105,15 @@ pub fn denormalize_with_aliases( if key_s.starts_with("_p_") { let restored = restore_casing(lookup_key, &casing_map); - writes.record_key(false, &restored, lookup_key); + writes.record_key(false, &restored, lookup_key, key_s); obj_insert(&mut properties, &restored, denorm_val); } else if is_data_plane { let restored = restore_casing(key_s, &casing_map); - writes.record_key(true, &restored, key_s); + writes.record_key(true, &restored, key_s, key_s); obj_insert(&mut result, &restored, denorm_val); } else { let restored = restore_casing(key_s, &casing_map); - writes.record_key(false, &restored, key_s); + writes.record_key(false, &restored, key_s, key_s); obj_insert(&mut properties, &restored, denorm_val); } } @@ -139,16 +139,13 @@ pub fn denormalize_with_aliases( // Fast-path: direct BTreeMap lookup for lowercase keys, // with case-insensitive fallback for mixed-case external input. let nk_val = Value::String(Rc::from(normalized_key.as_str())); - let val = obj.get(&nk_val).or_else(|| { - obj.iter() - .find(|(k, _)| { - val_str(k).is_some_and(|s| s.eq_ignore_ascii_case(&normalized_key)) - }) - .map(|(_, v)| v) + let found = obj.get(&nk_val).map(|v| (&nk_val, v)).or_else(|| { + obj.iter().find(|(k, _)| { + val_str(k).is_some_and(|s| s.eq_ignore_ascii_case(&normalized_key)) + }) }); - let val = match val { - Some(v) => v, - None => continue, + let Some((read, val)) = found.and_then(|(k, v)| Some((val_str(k)?, v))) else { + continue; }; let arm_path = entry.select_path(api_version); @@ -157,10 +154,10 @@ pub fn denormalize_with_aliases( // A write refused by a non-object on the way leaves no value. if let Some(props_path) = arm_path.strip_prefix("properties.") { if set_nested_verbatim(&mut properties, props_path, denorm_val) { - writes.record_alias(false, props_path, lc_key); + writes.record_alias(false, props_path, lc_key, read); } } else if set_nested_verbatim(&mut result, arm_path, denorm_val) { - writes.record_alias(true, arm_path, lc_key); + writes.record_alias(true, arm_path, lc_key, read); } } @@ -182,7 +179,10 @@ pub fn denormalize_with_aliases( if let Some(val) = properties.remove(key.as_ref()) { obj_insert(&mut properties, arm_base, val); // The normalizer flattened and remapped this value under its ARM name. - writes.record_key(false, arm_base, arm_base); + let read = writes + .read_at(&key) + .unwrap_or_else(|| alloc::string::String::from(&*key)); + writes.record_key(false, arm_base, arm_base, &read); } } } @@ -213,9 +213,15 @@ pub fn denormalize_with_aliases( }); // Another alias's value replaced this one there; it was not // remapped with this alias's names. + // Check the keys the remap will reach, so an older write to an + // exact ancestor does not hide a later write that differs in case. if let (Some(outer), Some(name)) = (array_chain.first(), remap.array_chain.first()) { - if writes.replaced(at_root, outer, name) { + let map = if at_root { &result } else { &properties }; + let outer: alloc::vec::Vec<&str> = + outer.iter().map(|key| key.as_str()).collect(); + let reached = sub_resource::output_keys(map, &outer); + if writes.replaced(at_root, &reached, name) { continue; } } @@ -236,14 +242,19 @@ pub fn denormalize_with_aliases( // Phase 3: Re-wrap sub-resource array elements. if let Some(aliases) = aliases { if !aliases.sub_resource_arrays.is_empty() { + let cx = sub_resource::Context { + entries: &aliases.entries, + api_version, + writes: &writes, + is_data_plane, + casing_map: &casing_map, + normalized: obj, + }; sub_resource::rewrap_sub_resource_arrays( &mut result, &mut properties, &aliases.sub_resource_arrays, - &aliases.entries, - api_version, - &writes, - is_data_plane, + &cx, ); } } diff --git a/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs b/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs index 8f720d5a2..1749caa6c 100644 --- a/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs +++ b/src/languages/azure_policy/aliases/denormalizer/sub_resource.rs @@ -10,102 +10,208 @@ use alloc::vec::Vec; use crate::value::Object; use crate::Value; -use super::super::obj_map::{make_value, new_map, obj_insert, val_str, ObjMap}; +use super::super::obj_map::{make_value, new_map, obj_insert, obj_key_ci, val_str, ObjMap}; use super::super::path; use super::super::types::ResolvedEntry; -use super::helpers::find_key_ci; +use super::casing::restore_casing; /// Sub-resource array element envelope fields that remain at the element root. const ELEMENT_ENVELOPE_FIELDS: &[&str] = &["name", "type", "id", "etag"]; -/// The envelope fields of each sub-resource short name that resolves to one -/// array. -type Target<'a> = BTreeMap<&'a str, BTreeSet>; +/// The fields of a sub-resource array's elements that stay at the element +/// root, from the aliases over the array. +#[derive(Clone, Debug, Default)] +struct Fields { + /// Fields that stay at the element root. + envelope: BTreeSet, + /// Fields that both a wrapped and an unwrapped alias give the same name, + /// with the element-level short-name keys of the wrapped aliases. Such a + /// field came from a wrapped alias, and is wrapped, when the element had + /// one of them. + shared: BTreeMap>>, +} + +impl Fields { + fn extend(&mut self, other: &Self) { + self.envelope.extend(other.envelope.iter().cloned()); + for (field, names) in &other.shared { + self.shared + .entry(field.clone()) + .or_default() + .extend(names.iter().cloned()); + } + } + + /// Whether `field` stays at the root of an element whose normalized + /// value was `input`. + fn at_root(&self, field: &str, input: Option<&Value>) -> bool { + let field = field.to_ascii_lowercase(); + if self.envelope.contains(&field) { + return true; + } + let Some(names) = self.shared.get(&field) else { + return false; + }; + let Some(Value::Object(input)) = input else { + return false; + }; + !names.iter().any(|name| has_keys(input, name)) + } +} + +/// The fields of each sub-resource short name that resolves to one array. +type Target<'a> = BTreeMap<&'a str, Fields>; + +/// The denormalization state that re-wrapping reads. +pub struct Context<'a> { + /// The resource type's resolved aliases, by lowercase short name. + pub entries: &'a BTreeMap, + /// The API version that selects each alias's ARM path. + pub api_version: Option<&'a str>, + /// What phases 2a, 2b and 2c wrote. + pub writes: &'a Writes, + /// Whether phase 2a put non-aliased keys at the ARM root. + pub is_data_plane: bool, + /// The key casing phases 2a and 2b restored. + pub casing_map: &'a BTreeMap, + /// The normalized resource being denormalized. + pub normalized: &'a Object, +} -/// The writes of phases 2a, 2b and 2c, in order. Each records where it wrote -/// (`true` for the ARM root rather than `properties`, then the keys as -/// written, since keys differing only in case are distinct) and the -/// lowercase normalized key whose value it wrote. +/// The writes of phases 2a, 2b and 2c, in order. #[derive(Debug, Default)] pub struct Writes { + /// The lowercase short names of the plain aliases phase 2b wrote. aliases: BTreeSet, - log: Vec<(bool, Vec, String)>, + log: Vec, +} + +/// One value written to the output. +#[derive(Debug)] +struct Write { + /// Whether the write was at the ARM root rather than under `properties`. + at_root: bool, + /// The output keys written, as spelled there: keys differing only in + /// case are distinct. + keys: Vec, + /// The normalized name of the value, lowercase. + source: String, + /// The normalized key the value was read from, as it is spelled there. + read: String, +} + +/// The write that left a value in the output. +pub struct Origin<'a> { + /// The value's normalized name: the write's source, followed by the keys + /// below the write. + pub name: String, + /// The normalized key the write read. + pub read: &'a str, + /// How many output keys the write covered. + pub depth: usize, } impl Writes { - /// Record writing the value of normalized key `source` at the dotted - /// path `keys`. - pub fn record(&mut self, at_root: bool, keys: &str, source: &str) { + /// Record writing the value of normalized key `source`, read from the + /// normalized key `read`, at the dotted path `keys`. + pub fn record(&mut self, at_root: bool, keys: &str, source: &str, read: &str) { let keys = keys.split('.').map(String::from).collect(); - self.log.push((at_root, keys, source.to_ascii_lowercase())); + self.push(at_root, keys, source, read); } - /// Record writing the value of normalized key `source` at the single, - /// possibly dotted, key `key`. - pub fn record_key(&mut self, at_root: bool, key: &str, source: &str) { - let keys = alloc::vec![String::from(key)]; - self.log.push((at_root, keys, source.to_ascii_lowercase())); + /// [`Self::record`] at the single, possibly dotted, key `key`. + pub fn record_key(&mut self, at_root: bool, key: &str, source: &str, read: &str) { + self.push(at_root, alloc::vec![String::from(key)], source, read); } - /// Record phase 2b writing the plain alias `key` at `keys`. - pub fn record_alias(&mut self, at_root: bool, keys: &str, key: &str) { + /// Record phase 2b writing the plain alias `key`, read from the + /// normalized key `read`, at `keys`. + pub fn record_alias(&mut self, at_root: bool, keys: &str, key: &str, read: &str) { self.aliases.insert(String::from(key)); - self.record(at_root, keys, key); + self.record(at_root, keys, key, read); + } + + fn push(&mut self, at_root: bool, keys: Vec, source: &str, read: &str) { + self.log.push(Write { + at_root, + keys, + source: source.to_ascii_lowercase(), + read: String::from(read), + }); + } + + /// The normalized key read by the last write to exactly `key` under + /// `properties`. + pub fn read_at(&self, key: &str) -> Option { + self.log + .iter() + .rev() + .find(|write| { + !write.at_root + && write.keys.len() == 1 + && write.keys.first().is_some_and(|k| k == key) + }) + .map(|write| write.read.clone()) } /// Whether a write of some other normalized name than `name` (dotted /// keys) left the value now at `keys`. pub fn replaced(&self, at_root: bool, keys: &[String], name: &[String]) -> bool { let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); - self.survivor(at_root, &keys) - .is_some_and(|survivor| survivor != name.join(".").to_ascii_lowercase()) + self.origin(at_root, &keys) + .is_some_and(|origin| origin.name != name.join(".").to_ascii_lowercase()) } - /// The normalized name of the value now at `keys`: the source of the - /// last write at or above `keys`, followed by the keys below it. `None` - /// if nothing was written there. Writes to exactly `keys` come first; - /// keys from normalized names match the written keys in any case. - fn survivor(&self, at_root: bool, keys: &[&str]) -> Option { + /// The write that left the value now at `keys`: the last write at or + /// above `keys`. `None` if nothing was written there. Writes to exactly + /// `keys` come first; keys from normalized names match the written keys + /// in any case. + pub fn origin(&self, at_root: bool, keys: &[&str]) -> Option> { let last_write = |same: fn(&str, &str) -> bool| { - self.log.iter().rev().find(|(root, written, _)| { - *root == at_root - && written.len() <= keys.len() - && written.iter().zip(keys).all(|(dest, key)| same(dest, key)) + self.log.iter().rev().find(|write| { + write.at_root == at_root + && write.keys.len() <= keys.len() + && write + .keys + .iter() + .zip(keys) + .all(|(dest, key)| same(dest, key)) }) }; - let (_, written, source) = last_write(|dest, key| dest == key) + let write = last_write(|dest, key| dest == key) .or_else(|| last_write(|dest, key| dest.eq_ignore_ascii_case(key)))?; - let below = keys.get(written.len()..).unwrap_or_default(); - let name: Vec<&str> = core::iter::once(source.as_str()) + let below = keys.get(write.keys.len()..).unwrap_or_default(); + let name: Vec<&str> = core::iter::once(write.source.as_str()) .chain(below.iter().copied()) .collect(); - Some(name.join(".").to_ascii_lowercase()) + Some(Origin { + name: name.join(".").to_ascii_lowercase(), + read: &write.read, + depth: write.keys.len(), + }) } } /// Re-wrap sub-resource array elements by moving non-envelope fields back -/// under each element's `properties` object. `writes` holds what phases 2a -/// and 2b wrote; `is_data_plane` says where phase 2a put non-aliased keys. +/// under each element's `properties` object. pub fn rewrap_sub_resource_arrays( result: &mut ObjMap, properties: &mut ObjMap, sub_arrays: &BTreeSet, - entries: &BTreeMap, - api_version: Option<&str>, - writes: &Writes, - is_data_plane: bool, + cx: &Context<'_>, ) { if sub_arrays.is_empty() { return; } // Parse once per call; only wildcard aliases can address array elements. - let parsed: Vec<(path::Path, path::Path)> = entries + let parsed: Vec<(path::Path, path::Path)> = cx + .entries .values() .filter(|entry| entry.is_wildcard) .filter_map(|entry| { Some(( path::parse(&entry.short_name)?, - path::parse(entry.select_path(api_version))?, + path::parse(entry.select_path(cx.api_version))?, )) }) .collect(); @@ -115,14 +221,14 @@ pub fn rewrap_sub_resource_arrays( // are different arrays, so group by the keys actually in the output. let mut targets: BTreeMap<(bool, Vec), Target<'_>> = BTreeMap::new(); for sub_array_path in sub_arrays { - let envelope_fields = classify_envelope_fields(sub_array_path, &parsed); - let (at_root, keys) = - written_keys(sub_array_path, entries, api_version, writes, is_data_plane); + let fields = classify_envelope_fields(sub_array_path, &parsed); + let (at_root, keys) = written_keys(sub_array_path, cx); + let keys: Vec<&str> = keys.iter().map(String::as_str).collect(); let map = if at_root { &*result } else { &*properties }; targets .entry((at_root, output_keys(map, &keys))) .or_default() - .insert(sub_array_path.as_str(), envelope_fields); + .insert(sub_array_path.as_str(), fields); } // Deepest first, so an outer array is wrapped after the arrays inside it. @@ -134,22 +240,34 @@ pub fn rewrap_sub_resource_arrays( // A later write may have replaced the flattened array with a value // the normalizer left wrapped (another plain alias with the same ARM // path, or one over the array's parent). Wrap only a flattened array. - let survivor = writes.survivor(at_root, &keys); - if survivor + let origin = cx.writes.origin(at_root, &keys); + if origin .as_ref() - .is_some_and(|name| !sub_arrays.contains(name)) + .is_some_and(|origin| !sub_arrays.contains(&origin.name)) { continue; } // Classify by the name whose value is there. Otherwise keep a field // at the element root if any of the names leaves it there. - let envelope_fields = survivor - .as_deref() - .and_then(|name| by_name.get(name)) + let fields = origin + .as_ref() + .and_then(|origin| by_name.get(origin.name.as_str())) .map_or_else( - || by_name.values().flatten().cloned().collect(), - Clone::clone, + || { + let mut all = Fields::default(); + for fields in by_name.values() { + all.extend(fields); + } + all + }, + Fields::clone, ); + // The normalized value the write read, for the fields whose origin + // its elements decide. Below the write, the keys are the same. + let (input, skip) = origin.as_ref().map_or((None, 0), |origin| { + let read = Value::String(crate::Rc::from(origin.read)); + (cx.normalized.get(&read), origin.depth.saturating_sub(1)) + }); let Some((first, rest)) = keys.split_first() else { continue; }; @@ -158,30 +276,23 @@ pub fn rewrap_sub_resource_arrays( } else { &mut *properties }; - let key = if map.contains_key(*first) { - Some(crate::Rc::from(*first)) - } else { - find_key_ci(map, first) - }; - if let Some(value) = key.and_then(|key| map.get_mut(key.as_ref())) { - rewrap_at(value, rest, &envelope_fields); + if let Some(value) = obj_key_ci(map, first).and_then(|key| map.get_mut(key.as_ref())) { + rewrap_at(value, rest, &fields, input, skip); } } } /// The keys in `map` that `keys` lead to: each key as it is in the output -/// (exact match first, else any case), as far as objects go. Keys inside -/// arrays are matched per element and kept as given. -fn output_keys(map: &ObjMap, keys: &[&str]) -> Vec { +/// (exact match first, else the smallest that differs only in case, as +/// element remaps pick), as far as objects go. Keys inside arrays are matched +/// per element and kept as given. +pub fn output_keys(map: &ObjMap, keys: &[&str]) -> Vec { let mut out = Vec::with_capacity(keys.len()); let mut current: Option<&Value> = None; for (i, key) in keys.iter().enumerate() { let found = match current { None => { - let exact = map.get_key_value(*key); - exact - .or_else(|| find_key_ci(map, key).and_then(|k| map.get_key_value(k.as_ref()))) - .map(|(k, v)| (String::from(k.as_ref()), v)) + obj_key_ci(map, key).and_then(|k| Some((String::from(k.as_ref()), map.get(&k)?))) } Some(Value::Object(obj)) => find_key_ci_btree(obj, key).and_then(|k| { let name = String::from(val_str(&k)?); @@ -212,24 +323,26 @@ fn output_keys(map: &ObjMap, keys: &[&str]) -> Vec { /// the ARM root rather than `properties`, plus the keys leading to it. When /// phase 2b wrote a plain alias for the first key, the array is under that /// alias's ARM path (`x` -> `properties.items` puts `x.y` at `items.y`); -/// otherwise phase 2a wrote the key as is. -fn written_keys<'a>( - sub_array_path: &'a str, - entries: &'a BTreeMap, - api_version: Option<&str>, - writes: &Writes, - is_data_plane: bool, -) -> (bool, Vec<&'a str>) { - let keys: Vec<&str> = sub_array_path.split('.').collect(); - let Some((first, rest)) = keys.split_first() else { - return (is_data_plane, keys); +/// otherwise phase 2a wrote the key as is. Keys from the short name get the +/// casing those phases restored, so a sibling that differs only in case is +/// not taken for the array. +fn written_keys(sub_array_path: &str, cx: &Context<'_>) -> (bool, Vec) { + let names: Vec<&str> = sub_array_path.split('.').collect(); + let restore = |part: &[&str]| -> Vec { + part.iter() + .map(|name| restore_casing(name, cx.casing_map)) + .collect() + }; + let Some((first, rest)) = names.split_first() else { + return (cx.is_data_plane, restore(&names)); }; - match alias_location(first, entries, api_version, writes) { - Some((at_root, mut arm)) => { - arm.extend(rest.iter().copied()); - (at_root, arm) + match alias_location(first, cx.entries, cx.api_version, cx.writes) { + Some((at_root, arm)) => { + let mut keys: Vec = arm.into_iter().map(String::from).collect(); + keys.extend(restore(rest)); + (at_root, keys) } - None => (is_data_plane, keys), + None => (cx.is_data_plane, restore(&names)), } } @@ -281,10 +394,7 @@ pub fn redirect_chain( /// Determine which element-level fields are envelope fields for a given /// sub-resource array, from parsed `(short name, ARM path)` pairs. Entries /// whose short name or selected ARM path does not parse are excluded. -fn classify_envelope_fields( - sub_array_path: &str, - parsed: &[(path::Path, path::Path)], -) -> BTreeSet { +fn classify_envelope_fields(sub_array_path: &str, parsed: &[(path::Path, path::Path)]) -> Fields { let mut envelope = BTreeSet::new(); for &f in ELEMENT_ENVELOPE_FIELDS { envelope.insert(f.to_ascii_lowercase()); @@ -294,15 +404,16 @@ fn classify_envelope_fields( // ARM names of the element's root fields, and of the fields under its // `properties` wrapper. let mut unwrapped = BTreeSet::new(); - let mut wrapped = BTreeSet::new(); + let mut wrapped: BTreeMap>> = BTreeMap::new(); for (short, arm_path) in parsed { let parts = short.parts(); let Some(level) = array_level(&array_keys, &parts) else { continue; }; - let Some(path::Segment::Key(first_segment)) = - parts.get(level).and_then(|part| part.segments.first()) - else { + let Some(short_part) = parts.get(level) else { + continue; + }; + let Some(path::Segment::Key(first_segment)) = short_part.segments.first() else { continue; }; // Classify by the ARM part at this array's element level, not by the @@ -312,7 +423,18 @@ fn classify_envelope_fields( let arm_part = arm_parts.get(level); if let Some(part) = arm_part.filter(|part| part.has_flattened_wrapper()) { if let Some(path::Segment::Key(key)) = part.segments.get(1) { - wrapped.insert(key.to_ascii_lowercase()); + let name = short_part + .segments + .iter() + .map_while(|segment| match segment { + path::Segment::Key(segment_key) => Some(segment_key.to_ascii_lowercase()), + _ => None, + }) + .collect(); + wrapped + .entry(key.to_ascii_lowercase()) + .or_default() + .insert(name); } continue; } @@ -323,15 +445,33 @@ fn classify_envelope_fields( unwrapped.insert(key.to_ascii_lowercase()); } } - // A name that is also a wrapped field's ARM name stays wrapped, as it was - // before phase 2d gave fields their ARM names, whether it came from an - // ARM name or a short name. The standard envelope fields stay. + // A name that is also a wrapped field's ARM name may have come from + // either alias; the element decides. The standard envelope fields stay. envelope.extend(unwrapped); - envelope.retain(|field| { - !wrapped.contains(field) || ELEMENT_ENVELOPE_FIELDS.contains(&field.as_str()) + let mut shared = BTreeMap::new(); + envelope.retain(|field| match wrapped.get(field) { + Some(names) if !ELEMENT_ENVELOPE_FIELDS.contains(&field.as_str()) => { + shared.insert(field.clone(), names.clone()); + false + } + _ => true, }); - envelope + Fields { envelope, shared } +} + +/// Whether `keys` lead somewhere in `object`, matching keys in any case. +fn has_keys(object: &Object, keys: &[String]) -> bool { + let Some((first, rest)) = keys.split_first() else { + return true; + }; + let Some(child) = find_key_ci_btree(object, first).and_then(|key| object.get(&key)) else { + return false; + }; + match child { + Value::Object(child) => has_keys(child, rest), + _ => rest.is_empty(), + } } /// Number of leading short-name parts whose keys spell `array_keys`, i.e. @@ -360,16 +500,29 @@ fn array_level(array_keys: &[&str], parts: &[path::Part<'_>]) -> Option { /// Follow `keys` from `value` and re-wrap the elements of the array there. /// Like the normalizer's path tracking, arrays along the way are walked /// element by element and objects by key, so a name such as `a.b.c` matches -/// `a.b[*].c[*]` and `a[*].b[*].c[*]` alike. -fn rewrap_at(value: &mut Value, keys: &[&str], envelope_fields: &BTreeSet) { +/// `a.b[*].c[*]` and `a[*].b[*].c[*]` alike. `input` follows along in the +/// normalized value once the first `skip` keys, which have no counterpart +/// there, are passed. +fn rewrap_at( + value: &mut Value, + keys: &[&str], + fields: &Fields, + input: Option<&Value>, + skip: usize, +) { match value { Value::Array(arr) => { let inner = crate::Rc::make_mut(arr); - for elem in inner.iter_mut() { + for (index, elem) in inner.iter_mut().enumerate() { + let input = if skip == 0 { + input.and_then(|input| input.as_array().ok()?.get(index)) + } else { + input + }; if keys.is_empty() { - *elem = rewrap_element(elem, envelope_fields); + *elem = rewrap_element(elem, fields, input); } else { - rewrap_at(elem, keys, envelope_fields); + rewrap_at(elem, keys, fields, input, skip); } } } @@ -377,10 +530,17 @@ fn rewrap_at(value: &mut Value, keys: &[&str], envelope_fields: &BTreeSet input, + None => input.and_then(|input| { + let input = input.as_object().ok()?; + input.get(&find_key_ci_btree(input, first)?) + }), + }; let obj = crate::Rc::make_mut(obj); if let Some(key) = find_key_ci_btree(obj, first) { if let Some(child) = obj.get_mut(&key) { - rewrap_at(child, rest, envelope_fields); + rewrap_at(child, rest, fields, input, skip.saturating_sub(1)); } } } @@ -402,7 +562,7 @@ fn find_key_ci_btree(btree: &Object, key: &str) -> Option { /// Re-wrap a single sub-resource array element by moving non-envelope /// fields back under a `properties` object. -fn rewrap_element(element: &Value, envelope_fields: &BTreeSet) -> Value { +fn rewrap_element(element: &Value, fields: &Fields, input: Option<&Value>) -> Value { let obj = match element.as_object() { Ok(o) => o, Err(_) => return element.clone(), @@ -416,7 +576,7 @@ fn rewrap_element(element: &Value, envelope_fields: &BTreeSet) -> Value Some(s) => s, None => continue, }; - if envelope_fields.contains(&key_s.to_ascii_lowercase()) { + if fields.at_root(key_s, input) { obj_insert(&mut envelope, key_s, val.clone()); } else { obj_insert(&mut props, key_s, val.clone()); diff --git a/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs b/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs index 7ab2317d9..188853c3c 100644 --- a/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs +++ b/src/languages/azure_policy/aliases/normalizer/alias_resolution.rs @@ -102,6 +102,9 @@ pub fn apply_alias_entries( obj_insert(result, target_lc, val); continue; }; + // Keep the ARM-named key, as the loop above does when the + // casing matches. + obj_insert(result, source_lc, val); obj_insert(result, target_lc, resolved); // The remaps above ran before this value had its alias name. for remap in &agg.element_remaps { diff --git a/src/languages/azure_policy/aliases/obj_map.rs b/src/languages/azure_policy/aliases/obj_map.rs index 6f675913c..77e3e50d9 100644 --- a/src/languages/azure_policy/aliases/obj_map.rs +++ b/src/languages/azure_policy/aliases/obj_map.rs @@ -30,7 +30,7 @@ pub fn new_map() -> ObjMap { /// Find the key matching `key` in an ObjMap: an exact match if present, /// otherwise the smallest key equal to it ignoring ASCII case. Remap paths /// are lowercase, but the denormalizer writes keys with their ARM casing. -fn obj_key_ci(map: &ObjMap, key: &str) -> Option> { +pub fn obj_key_ci(map: &ObjMap, key: &str) -> Option> { match map.get_key_value(key) { Some((k, _)) => Some(k.clone()), None => map diff --git a/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml b/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml index c11388ca1..5e37b73a2 100644 --- a/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml +++ b/tests/azure_policy/normalization/cases/normalize_sub_resources.yaml @@ -1310,8 +1310,14 @@ cases: rawz: 1 # The array base rename supplies `x`; its elements are flattened and # remapped like those of a matching key. + # As with a matching key, the ARM-named key is kept too. expected_normalized: type: "Test/widgets" + items: + - y: + - name: one + properties: + rawz: 1 x: - y: - name: one @@ -1361,8 +1367,14 @@ cases: - rawState: s properties: z: 1 + # As with a matching key, the ARM-named key is kept too. expected_normalized: type: "Test/widgets" + items: + - subnets: + - properties: + z: 1 + rawstate: "s" x: - subnets: - state: s @@ -1554,8 +1566,15 @@ cases: keep: true # `items.y` and `a.y` are both sub-resource arrays. Each element's wrapper # is consumed once, so the payload's own `properties` stays. + # As with a matching key, the ARM-named key is kept too. expected_normalized: type: "Test/widgets" + items: + - y: + - name: "one" + properties: + keep: true + z: 1 a: - y: - name: one @@ -1605,8 +1624,13 @@ cases: k: 2 # `a.y` is not a sub-resource array, so its elements keep `properties`, # as they do when the input key is `items`. + # As with a matching key, the ARM-named key is kept too. expected_normalized: type: "Test/widgets" + items: + - y: + - k: 2 + z: 1 a: - y: - z: 1 @@ -1646,8 +1670,11 @@ cases: - b: 1 c: 2 # `a[*].d` reads ARM `c`, not the `b` that the `items[*].c` remap moved. + # As with a matching key, the ARM-named key is kept too. expected_normalized: type: "Test/widgets" + items: + - c: 1 a: - b: 1 d: 2 @@ -1811,3 +1838,295 @@ cases: - name: one properties: z: 1 + + - note: a write to an exact ancestor does not hide a later write that differs only in case from reverse remaps + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/p", "defaultPath": "properties.cfg", "paths": [] }, + { "name": "Test/widgets/p.subnets[*].z", "defaultPath": "properties.cfg.subnets[*].rawz", "paths": [] }, + { "name": "Test/widgets/q", "defaultPath": "properties.cfg.subNets", "paths": [] } + ] + } + ] + } + ] + input: + type: "Test/widgets" + p: {} + q: + - z: 2 + expected_denormalized: + type: "Test/widgets" + properties: + cfg: + subNets: + - z: 2 + + - note: a scalar sibling that differs only in case does not stop an array from being re-wrapped + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/a", "defaultPath": "properties.cfg", "paths": [] }, + { "name": "Test/widgets/a.Items[*].z", "defaultPath": "properties.cfg.Items[*].properties.z", "paths": [] }, + { "name": "Test/widgets/b", "defaultPath": "properties.cfg.items", "paths": [] } + ] + } + ] + } + ] + input: + type: "Test/widgets" + a: + items: + - z: 1 + b: 2 + expected_denormalized: + type: "Test/widgets" + properties: + cfg: + Items: + - properties: + z: 1 + items: 2 + + - note: an unwrapped field whose name is a wrapped field's ARM name stays unwrapped when the wrapped alias is absent + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { "name": "Test/widgets/config", "defaultPath": "properties.config", "paths": [] }, + { + "name": "Test/widgets/config.rules[*].rawstatus", + "defaultPath": "properties.config.rules[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/config.rules[*].other", + "defaultPath": "properties.config.rules[*].properties.rawstatus", + "paths": [] + } + ] + } + ] + } + ] + input: + type: "Test/widgets" + config: + rules: + - rawstatus: 1 + - other: 2 + expected_denormalized: + type: "Test/widgets" + properties: + config: + rules: + - rawstatus: 1 + - properties: + rawstatus: 2 + + # `z` stays unremapped in `Items`, as before this change: the remap looks up + # `ITEMS`, the smallest key differing only in case, which `q` replaced. This + # case checks that `rawz` does not land in `q`'s array. + - note: an element remap writes to the array the casing hint picks, not another alias's + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/Items[*].z", + "defaultPath": "properties.Items[*].rawz", + "paths": [] + }, + { + "name": "Test/widgets/q", + "defaultPath": "properties.ITEMS", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "items": [{"z": 1}], "q": [{"z": 2}]} + expected_denormalized: {"type": "Test/widgets", "properties": {"ITEMS": [{"z": 2}], "Items": [{"z": 1}]}} + + - note: a shared field stays at the element root when the element lacks the wrapped alias's full path + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/rules[*].rawstatus", + "defaultPath": "properties.rules[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/rules[*].other.code", + "defaultPath": "properties.rules[*].properties.rawstatus.code", + "paths": [] + }, + { + "name": "Test/widgets/rules[*].other.label", + "defaultPath": "properties.rules[*].properties.other.label", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "rules": [{"rawstatus": 1, "other": {"label": "ready"}}]} + expected_denormalized: {"type": "Test/widgets", "properties": {"rules": [{"rawstatus": 1, "properties": {"other": {"label": "ready"}}}]}} + + - note: a renamed array's elements decide shared fields by the renamed input + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/r[*].w", + "defaultPath": "properties.items[*].w", + "paths": [] + }, + { + "name": "Test/widgets/items[*].rawstatus", + "defaultPath": "properties.items[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/items[*].other", + "defaultPath": "properties.items[*].properties.rawstatus", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "r": [{"rawstatus": 1}, {"other": 2}]} + expected_denormalized: {"type": "Test/widgets", "properties": {"items": [{"rawstatus": 1}, {"properties": {"rawstatus": 2}}]}} + + - note: a collision-prefixed array decides shared fields by its own input + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/sku", + "defaultPath": "properties.sku", + "paths": [] + }, + { + "name": "Test/widgets/sku.items[*].rawstatus", + "defaultPath": "properties.sku.items[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/sku.items[*].other", + "defaultPath": "properties.sku.items[*].properties.rawstatus", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "sku": {"name": "S"}, "_p_sku": {"items": [{"rawstatus": 1}]}} + expected_denormalized: {"type": "Test/widgets", "sku": {"name": "S"}, "properties": {"sku": {"items": [{"rawstatus": 1}]}}} + + - note: a renamed array restored to another casing decides shared fields by its normalized key + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/R[*].w", + "defaultPath": "properties.items[*].w", + "paths": [] + }, + { + "name": "Test/widgets/items[*].rawstatus", + "defaultPath": "properties.items[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/items[*].other", + "defaultPath": "properties.items[*].properties.rawstatus", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "r": [{"rawstatus": 1}, {"other": 2}]} + expected_denormalized: {"type": "Test/widgets", "properties": {"items": [{"rawstatus": 1}, {"properties": {"rawstatus": 2}}]}} + + # The remap that moves `other.code` leaves `other` empty, as remaps do. + - note: a shared field is wrapped when the element has the wrapped alias's full path in any case + aliases_json: | + [ + { + "namespace": "Test", + "resourceTypes": [ + { + "resourceType": "widgets", + "aliases": [ + { + "name": "Test/widgets/rules[*].rawstatus", + "defaultPath": "properties.rules[*].rawstatus", + "paths": [] + }, + { + "name": "Test/widgets/rules[*].other.code", + "defaultPath": "properties.rules[*].properties.rawstatus.code", + "paths": [] + }, + { + "name": "Test/widgets/rules[*].other.label", + "defaultPath": "properties.rules[*].properties.other.label", + "paths": [] + } + ] + } + ] + } + ] + input: {"type": "Test/widgets", "rules": [{"rawstatus": 1}, {"Other": {"Code": "c"}}]} + expected_denormalized: {"type": "Test/widgets", "properties": {"rules": [{"rawstatus": 1}, {"properties": {"other": {}, "rawstatus": {"code": "c"}}}]}}