Skip to main content

rigg_core/
normalize.rs

1//! JSON normalization for consistent Git diffs
2
3use serde_json::{Map, Value};
4
5use crate::resources::traits::ResourceKind;
6
7/// Normalize a JSON value for consistent Git diffs
8///
9/// This performs:
10/// 1. Strips volatile fields (@odata.etag, @odata.context, credentials, etc.)
11/// 2. Preserves the property order from the Azure API response
12/// 3. Preserves array element order as returned by the API
13pub fn normalize(value: &Value, volatile_fields: &[&str]) -> Value {
14    normalize_value(value, volatile_fields)
15}
16
17fn normalize_value(value: &Value, volatile_fields: &[&str]) -> Value {
18    match value {
19        Value::Object(map) => {
20            // Preserve original key order, just filter out volatile fields
21            let filtered: Map<String, Value> = map
22                .iter()
23                .filter(|(k, _)| !volatile_fields.contains(&k.as_str()))
24                .map(|(k, v)| (k.clone(), normalize_value(v, volatile_fields)))
25                .collect();
26
27            Value::Object(filtered)
28        }
29        Value::Array(arr) => {
30            let normalized: Vec<Value> = arr
31                .iter()
32                .map(|v| normalize_value(v, volatile_fields))
33                .collect();
34
35            Value::Array(normalized)
36        }
37        _ => value.clone(),
38    }
39}
40
41/// Normalize a resource for storage on disk: strips the kind's volatile and
42/// read-only fields (registry-driven) while preserving Azure's property order.
43/// Rigg-local `x-rigg-*` annotations are kept.
44pub fn normalize_for_disk(kind: ResourceKind, value: &Value) -> Value {
45    let meta = crate::registry::meta(kind);
46    let mut out = value.clone();
47    for field in meta.volatile_fields.iter().chain(meta.read_only_fields) {
48        strip_field(&mut out, field);
49    }
50    out
51}
52
53/// Normalize a resource for pushing to Azure: everything `normalize_for_disk`
54/// strips, plus all `x-rigg-*` annotation keys at any depth.
55pub fn normalize_for_push(kind: ResourceKind, value: &Value) -> Value {
56    let mut out = normalize_for_disk(kind, value);
57    strip_x_rigg_keys(&mut out);
58    out
59}
60
61/// Normalize for comparison: like `normalize_for_push`, and additionally
62/// strips write-only fields (which the server never echoes back).
63pub fn normalize_for_compare(kind: ResourceKind, value: &Value) -> Value {
64    let mut out = normalize_for_push(kind, value);
65    for field in crate::registry::meta(kind).write_only_fields {
66        strip_field(&mut out, field);
67    }
68    out
69}
70
71/// Are two documents semantically equal for this kind (after normalization)?
72pub fn semantic_eq(kind: ResourceKind, a: &Value, b: &Value) -> bool {
73    let na = normalize_for_compare(kind, a);
74    let nb = normalize_for_compare(kind, b);
75    rigg_diff::semantic::diff(&na, &nb, "name").is_equal
76}
77
78/// Strip one registry field spec from a document.
79///
80/// - Specs containing `.` or `[]` are paths from the root (e.g.
81///   `properties.provisioningState`, `models[].apiKey`).
82/// - Bare names are removed at any depth (e.g. `@odata.etag` — note the
83///   leading `@` key itself contains dots but is matched as a literal key).
84fn strip_field(value: &mut Value, spec: &str) {
85    let is_literal_key = spec.starts_with('@') || (!spec.contains('.') && !spec.contains("[]"));
86    if is_literal_key {
87        remove_key_recursive(value, spec);
88    } else {
89        remove_path(value, &spec.split('.').collect::<Vec<_>>());
90    }
91}
92
93fn remove_key_recursive(value: &mut Value, key: &str) {
94    match value {
95        Value::Object(map) => {
96            map.remove(key);
97            for (_, v) in map.iter_mut() {
98                remove_key_recursive(v, key);
99            }
100        }
101        Value::Array(arr) => {
102            for item in arr {
103                remove_key_recursive(item, key);
104            }
105        }
106        _ => {}
107    }
108}
109
110fn remove_path(value: &mut Value, segments: &[&str]) {
111    let Some((head, rest)) = segments.split_first() else {
112        return;
113    };
114    if let Some(key) = head.strip_suffix("[]") {
115        let target = if key.is_empty() {
116            Some(value)
117        } else {
118            value.get_mut(key)
119        };
120        if let Some(Value::Array(arr)) = target {
121            for item in arr {
122                if rest.is_empty() {
123                    continue; // removing whole array elements is not a thing
124                }
125                remove_path(item, rest);
126            }
127        }
128    } else if rest.is_empty() {
129        if let Value::Object(map) = value {
130            map.remove(*head);
131        }
132    } else if let Some(next) = value.get_mut(*head) {
133        remove_path(next, rest);
134    }
135}
136
137/// Remove every `x-rigg-*` key at any depth (Rigg-local annotations).
138pub fn strip_x_rigg_keys(value: &mut Value) {
139    match value {
140        Value::Object(map) => {
141            map.retain(|k, _| !k.starts_with("x-rigg-"));
142            for (_, v) in map.iter_mut() {
143                strip_x_rigg_keys(v);
144            }
145        }
146        Value::Array(arr) => {
147            for item in arr {
148                strip_x_rigg_keys(item);
149            }
150        }
151        _ => {}
152    }
153}
154
155/// Format JSON with consistent formatting (2-space indent, trailing newline, sorted keys)
156pub fn format_json(value: &Value) -> String {
157    let mut output = serde_json::to_string_pretty(value).unwrap_or_default();
158    if !output.ends_with('\n') {
159        output.push('\n');
160    }
161    output
162}
163
164/// Strip sensitive fields from credentials objects
165pub fn redact_credentials(value: &mut Value) {
166    if let Some(obj) = value.as_object_mut() {
167        // Redact connection strings
168        if let Some(creds) = obj.get_mut("credentials")
169            && let Some(creds_obj) = creds.as_object_mut()
170            && creds_obj.contains_key("connectionString")
171        {
172            creds_obj.insert(
173                "connectionString".to_string(),
174                Value::String("<REDACTED>".to_string()),
175            );
176        }
177
178        // Redact storage connection strings
179        if obj.contains_key("storageConnectionStringSecret") {
180            obj.insert(
181                "storageConnectionStringSecret".to_string(),
182                Value::String("<REDACTED>".to_string()),
183            );
184        }
185
186        // Recursively process nested objects
187        for (_, v) in obj.iter_mut() {
188            redact_credentials(v);
189        }
190    } else if let Some(arr) = value.as_array_mut() {
191        for item in arr {
192            redact_credentials(item);
193        }
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200    use serde_json::json;
201
202    #[test]
203    fn disk_normalization_strips_volatile_and_read_only() {
204        let indexer = json!({
205            "@odata.etag": "0x123",
206            "name": "idxr",
207            "dataSourceName": "ds",
208            "status": "running",
209            "lastResult": {"status": "success"},
210            "nested": {"@odata.etag": "0x456", "keep": true}
211        });
212        let out = normalize_for_disk(ResourceKind::Indexer, &indexer);
213        assert!(out.get("@odata.etag").is_none());
214        assert!(out.get("status").is_none(), "read-only stripped");
215        assert!(out.get("lastResult").is_none());
216        assert!(
217            out["nested"].get("@odata.etag").is_none(),
218            "etag stripped at depth"
219        );
220        assert_eq!(out["nested"]["keep"], json!(true));
221        assert_eq!(out["dataSourceName"], json!("ds"));
222    }
223
224    #[test]
225    fn dotted_path_stripping_for_arm_kinds() {
226        let dep = json!({
227            "name": "gpt-5-mini",
228            "properties": {
229                "model": {"name": "gpt-5-mini", "callRateLimit": {"count": 1}},
230                "provisioningState": "Succeeded",
231                "raiPolicyName": "default"
232            },
233            "systemData": {"createdAt": "2026-01-01"}
234        });
235        let out = normalize_for_disk(ResourceKind::Deployment, &dep);
236        assert!(out.get("systemData").is_none());
237        assert!(out["properties"].get("provisioningState").is_none());
238        assert!(out["properties"]["model"].get("callRateLimit").is_none());
239        assert_eq!(out["properties"]["raiPolicyName"], json!("default"));
240    }
241
242    #[test]
243    fn push_normalization_strips_x_rigg_but_disk_keeps() {
244        let agent = json!({
245            "name": "a",
246            "tools": [{"type": "mcp", "x-rigg-ref": "knowledge-bases/kb", "server_url": ""}]
247        });
248        let disk = normalize_for_disk(ResourceKind::Agent, &agent);
249        assert_eq!(disk["tools"][0]["x-rigg-ref"], json!("knowledge-bases/kb"));
250        let push = normalize_for_push(ResourceKind::Agent, &agent);
251        assert!(push["tools"][0].get("x-rigg-ref").is_none());
252        assert_eq!(push["tools"][0]["type"], json!("mcp"));
253    }
254
255    #[test]
256    fn push_normalization_strips_x_rigg_pin_annotation() {
257        // x-rigg-pin (rigg promote's per-resource pin list) is just another
258        // x-rigg-* key: normalize_for_push's generic strip covers it without
259        // needing a dedicated rule.
260        let doc = json!({
261            "name": "a",
262            "properties": {"target": "https://prod.example"},
263            "x-rigg-pin": ["properties.target"]
264        });
265        let disk = normalize_for_disk(ResourceKind::Connection, &doc);
266        assert_eq!(disk["x-rigg-pin"], json!(["properties.target"]));
267        let push = normalize_for_push(ResourceKind::Connection, &doc);
268        assert!(push.get("x-rigg-pin").is_none());
269    }
270
271    #[test]
272    fn semantic_eq_ignores_volatile_and_order() {
273        let a = json!({"name": "i", "@odata.etag": "1", "fields": [{"name": "f1"}]});
274        let b = json!({"@odata.etag": "2", "fields": [{"name": "f1"}], "name": "i"});
275        assert!(semantic_eq(ResourceKind::Index, &a, &b));
276        let c = json!({"name": "i", "fields": [{"name": "f2"}]});
277        assert!(!semantic_eq(ResourceKind::Index, &a, &c));
278    }
279
280    #[test]
281    fn test_strips_volatile_fields() {
282        let input = json!({
283            "@odata.etag": "abc123",
284            "@odata.context": "https://...",
285            "name": "test",
286            "fields": []
287        });
288
289        let result = normalize(&input, &["@odata.etag", "@odata.context"]);
290
291        assert!(result.get("@odata.etag").is_none());
292        assert!(result.get("@odata.context").is_none());
293        assert_eq!(result.get("name"), Some(&json!("test")));
294    }
295
296    #[test]
297    fn test_preserves_key_order() {
298        // Build a map with explicit insertion order
299        let mut map = serde_json::Map::new();
300        map.insert("zebra".to_string(), json!(1));
301        map.insert("apple".to_string(), json!(2));
302        map.insert("mango".to_string(), json!(3));
303        let input = Value::Object(map);
304
305        let result = normalize(&input, &[]);
306        let formatted = serde_json::to_string(&result).unwrap();
307
308        // Keys should preserve insertion order (not alphabetical)
309        let zebra_pos = formatted.find("zebra").unwrap();
310        let apple_pos = formatted.find("apple").unwrap();
311        let mango_pos = formatted.find("mango").unwrap();
312
313        assert!(zebra_pos < apple_pos);
314        assert!(apple_pos < mango_pos);
315    }
316
317    #[test]
318    fn test_preserves_array_order() {
319        let input = json!({
320            "items": [
321                {"name": "charlie", "value": 3},
322                {"name": "alice", "value": 1},
323                {"name": "bob", "value": 2}
324            ]
325        });
326
327        let result = normalize(&input, &[]);
328        let items = result.get("items").unwrap().as_array().unwrap();
329
330        // Order should be preserved as-is, not sorted
331        assert_eq!(items[0].get("name").unwrap(), "charlie");
332        assert_eq!(items[1].get("name").unwrap(), "alice");
333        assert_eq!(items[2].get("name").unwrap(), "bob");
334    }
335
336    #[test]
337    fn test_redact_credentials() {
338        let mut input = json!({
339            "name": "test",
340            "credentials": {
341                "connectionString": "secret-connection-string"
342            }
343        });
344
345        redact_credentials(&mut input);
346
347        assert_eq!(input["credentials"]["connectionString"], "<REDACTED>");
348    }
349
350    #[test]
351    fn test_deeply_nested_volatile_fields() {
352        let input = json!({
353            "name": "top",
354            "@odata.etag": "top-etag",
355            "nested": {
356                "@odata.etag": "nested-etag",
357                "value": 1,
358                "deeper": {
359                    "@odata.context": "ctx",
360                    "keep": true
361                }
362            }
363        });
364
365        let result = normalize(&input, &["@odata.etag", "@odata.context"]);
366
367        assert!(result.get("@odata.etag").is_none());
368        let nested = result.get("nested").unwrap();
369        assert!(nested.get("@odata.etag").is_none());
370        assert_eq!(nested.get("value"), Some(&json!(1)));
371        let deeper = nested.get("deeper").unwrap();
372        assert!(deeper.get("@odata.context").is_none());
373        assert_eq!(deeper.get("keep"), Some(&json!(true)));
374    }
375
376    #[test]
377    fn test_primitive_array_order_preserved() {
378        let input = json!({
379            "values": [3, 1, 2]
380        });
381
382        let result = normalize(&input, &[]);
383        let values = result.get("values").unwrap().as_array().unwrap();
384
385        assert_eq!(values[0], json!(3));
386        assert_eq!(values[1], json!(1));
387        assert_eq!(values[2], json!(2));
388    }
389
390    #[test]
391    fn test_empty_object_preserved() {
392        let input = json!({});
393        let result = normalize(&input, &[]);
394        assert_eq!(result, json!({}));
395    }
396
397    #[test]
398    fn test_empty_array_preserved() {
399        let input = json!({
400            "items": []
401        });
402
403        let result = normalize(&input, &[]);
404        let items = result.get("items").unwrap().as_array().unwrap();
405        assert!(items.is_empty());
406    }
407
408    #[test]
409    fn test_redact_nested_credentials() {
410        let mut input = json!({
411            "name": "test",
412            "outer": {
413                "credentials": {
414                    "connectionString": "nested-secret"
415                }
416            }
417        });
418
419        redact_credentials(&mut input);
420
421        assert_eq!(
422            input["outer"]["credentials"]["connectionString"],
423            "<REDACTED>"
424        );
425    }
426
427    #[test]
428    fn test_redact_storage_connection_string() {
429        let mut input = json!({
430            "name": "test",
431            "storageConnectionStringSecret": "my-storage-secret"
432        });
433
434        redact_credentials(&mut input);
435
436        assert_eq!(input["storageConnectionStringSecret"], "<REDACTED>");
437    }
438
439    #[test]
440    fn test_redact_multiple_targets() {
441        let mut input = json!({
442            "name": "test",
443            "credentials": {
444                "connectionString": "secret-conn"
445            },
446            "storageConnectionStringSecret": "secret-storage"
447        });
448
449        redact_credentials(&mut input);
450
451        assert_eq!(input["credentials"]["connectionString"], "<REDACTED>");
452        assert_eq!(input["storageConnectionStringSecret"], "<REDACTED>");
453    }
454
455    #[test]
456    fn test_redact_credentials_in_array() {
457        let mut input = json!({
458            "dataSources": [
459                {
460                    "name": "ds1",
461                    "credentials": {
462                        "connectionString": "secret1"
463                    }
464                },
465                {
466                    "name": "ds2",
467                    "credentials": {
468                        "connectionString": "secret2"
469                    }
470                }
471            ]
472        });
473
474        redact_credentials(&mut input);
475
476        assert_eq!(
477            input["dataSources"][0]["credentials"]["connectionString"],
478            "<REDACTED>"
479        );
480        assert_eq!(
481            input["dataSources"][1]["credentials"]["connectionString"],
482            "<REDACTED>"
483        );
484    }
485
486    #[test]
487    fn test_format_json_trailing_newline() {
488        let input = json!({"key": "value"});
489        let output = format_json(&input);
490        assert!(output.ends_with('\n'));
491    }
492
493    #[test]
494    fn test_format_json_empty_object() {
495        let input = json!({});
496        let output = format_json(&input);
497        assert_eq!(output, "{}\n");
498    }
499}