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            if let Some(creds_obj) = creds.as_object_mut() {
170                if creds_obj.contains_key("connectionString") {
171                    creds_obj.insert(
172                        "connectionString".to_string(),
173                        Value::String("<REDACTED>".to_string()),
174                    );
175                }
176            }
177        }
178
179        // Redact storage connection strings
180        if obj.contains_key("storageConnectionStringSecret") {
181            obj.insert(
182                "storageConnectionStringSecret".to_string(),
183                Value::String("<REDACTED>".to_string()),
184            );
185        }
186
187        // Recursively process nested objects
188        for (_, v) in obj.iter_mut() {
189            redact_credentials(v);
190        }
191    } else if let Some(arr) = value.as_array_mut() {
192        for item in arr {
193            redact_credentials(item);
194        }
195    }
196}
197
198#[cfg(test)]
199mod tests {
200    use super::*;
201    use serde_json::json;
202
203    #[test]
204    fn disk_normalization_strips_volatile_and_read_only() {
205        let indexer = json!({
206            "@odata.etag": "0x123",
207            "name": "idxr",
208            "dataSourceName": "ds",
209            "status": "running",
210            "lastResult": {"status": "success"},
211            "nested": {"@odata.etag": "0x456", "keep": true}
212        });
213        let out = normalize_for_disk(ResourceKind::Indexer, &indexer);
214        assert!(out.get("@odata.etag").is_none());
215        assert!(out.get("status").is_none(), "read-only stripped");
216        assert!(out.get("lastResult").is_none());
217        assert!(
218            out["nested"].get("@odata.etag").is_none(),
219            "etag stripped at depth"
220        );
221        assert_eq!(out["nested"]["keep"], json!(true));
222        assert_eq!(out["dataSourceName"], json!("ds"));
223    }
224
225    #[test]
226    fn dotted_path_stripping_for_arm_kinds() {
227        let dep = json!({
228            "name": "gpt-5-mini",
229            "properties": {
230                "model": {"name": "gpt-5-mini", "callRateLimit": {"count": 1}},
231                "provisioningState": "Succeeded",
232                "raiPolicyName": "default"
233            },
234            "systemData": {"createdAt": "2026-01-01"}
235        });
236        let out = normalize_for_disk(ResourceKind::Deployment, &dep);
237        assert!(out.get("systemData").is_none());
238        assert!(out["properties"].get("provisioningState").is_none());
239        assert!(out["properties"]["model"].get("callRateLimit").is_none());
240        assert_eq!(out["properties"]["raiPolicyName"], json!("default"));
241    }
242
243    #[test]
244    fn push_normalization_strips_x_rigg_but_disk_keeps() {
245        let agent = json!({
246            "name": "a",
247            "tools": [{"type": "mcp", "x-rigg-ref": "knowledge-bases/kb", "server_url": ""}]
248        });
249        let disk = normalize_for_disk(ResourceKind::Agent, &agent);
250        assert_eq!(disk["tools"][0]["x-rigg-ref"], json!("knowledge-bases/kb"));
251        let push = normalize_for_push(ResourceKind::Agent, &agent);
252        assert!(push["tools"][0].get("x-rigg-ref").is_none());
253        assert_eq!(push["tools"][0]["type"], json!("mcp"));
254    }
255
256    #[test]
257    fn semantic_eq_ignores_volatile_and_order() {
258        let a = json!({"name": "i", "@odata.etag": "1", "fields": [{"name": "f1"}]});
259        let b = json!({"@odata.etag": "2", "fields": [{"name": "f1"}], "name": "i"});
260        assert!(semantic_eq(ResourceKind::Index, &a, &b));
261        let c = json!({"name": "i", "fields": [{"name": "f2"}]});
262        assert!(!semantic_eq(ResourceKind::Index, &a, &c));
263    }
264
265    #[test]
266    fn test_strips_volatile_fields() {
267        let input = json!({
268            "@odata.etag": "abc123",
269            "@odata.context": "https://...",
270            "name": "test",
271            "fields": []
272        });
273
274        let result = normalize(&input, &["@odata.etag", "@odata.context"]);
275
276        assert!(result.get("@odata.etag").is_none());
277        assert!(result.get("@odata.context").is_none());
278        assert_eq!(result.get("name"), Some(&json!("test")));
279    }
280
281    #[test]
282    fn test_preserves_key_order() {
283        // Build a map with explicit insertion order
284        let mut map = serde_json::Map::new();
285        map.insert("zebra".to_string(), json!(1));
286        map.insert("apple".to_string(), json!(2));
287        map.insert("mango".to_string(), json!(3));
288        let input = Value::Object(map);
289
290        let result = normalize(&input, &[]);
291        let formatted = serde_json::to_string(&result).unwrap();
292
293        // Keys should preserve insertion order (not alphabetical)
294        let zebra_pos = formatted.find("zebra").unwrap();
295        let apple_pos = formatted.find("apple").unwrap();
296        let mango_pos = formatted.find("mango").unwrap();
297
298        assert!(zebra_pos < apple_pos);
299        assert!(apple_pos < mango_pos);
300    }
301
302    #[test]
303    fn test_preserves_array_order() {
304        let input = json!({
305            "items": [
306                {"name": "charlie", "value": 3},
307                {"name": "alice", "value": 1},
308                {"name": "bob", "value": 2}
309            ]
310        });
311
312        let result = normalize(&input, &[]);
313        let items = result.get("items").unwrap().as_array().unwrap();
314
315        // Order should be preserved as-is, not sorted
316        assert_eq!(items[0].get("name").unwrap(), "charlie");
317        assert_eq!(items[1].get("name").unwrap(), "alice");
318        assert_eq!(items[2].get("name").unwrap(), "bob");
319    }
320
321    #[test]
322    fn test_redact_credentials() {
323        let mut input = json!({
324            "name": "test",
325            "credentials": {
326                "connectionString": "secret-connection-string"
327            }
328        });
329
330        redact_credentials(&mut input);
331
332        assert_eq!(input["credentials"]["connectionString"], "<REDACTED>");
333    }
334
335    #[test]
336    fn test_deeply_nested_volatile_fields() {
337        let input = json!({
338            "name": "top",
339            "@odata.etag": "top-etag",
340            "nested": {
341                "@odata.etag": "nested-etag",
342                "value": 1,
343                "deeper": {
344                    "@odata.context": "ctx",
345                    "keep": true
346                }
347            }
348        });
349
350        let result = normalize(&input, &["@odata.etag", "@odata.context"]);
351
352        assert!(result.get("@odata.etag").is_none());
353        let nested = result.get("nested").unwrap();
354        assert!(nested.get("@odata.etag").is_none());
355        assert_eq!(nested.get("value"), Some(&json!(1)));
356        let deeper = nested.get("deeper").unwrap();
357        assert!(deeper.get("@odata.context").is_none());
358        assert_eq!(deeper.get("keep"), Some(&json!(true)));
359    }
360
361    #[test]
362    fn test_primitive_array_order_preserved() {
363        let input = json!({
364            "values": [3, 1, 2]
365        });
366
367        let result = normalize(&input, &[]);
368        let values = result.get("values").unwrap().as_array().unwrap();
369
370        assert_eq!(values[0], json!(3));
371        assert_eq!(values[1], json!(1));
372        assert_eq!(values[2], json!(2));
373    }
374
375    #[test]
376    fn test_empty_object_preserved() {
377        let input = json!({});
378        let result = normalize(&input, &[]);
379        assert_eq!(result, json!({}));
380    }
381
382    #[test]
383    fn test_empty_array_preserved() {
384        let input = json!({
385            "items": []
386        });
387
388        let result = normalize(&input, &[]);
389        let items = result.get("items").unwrap().as_array().unwrap();
390        assert!(items.is_empty());
391    }
392
393    #[test]
394    fn test_redact_nested_credentials() {
395        let mut input = json!({
396            "name": "test",
397            "outer": {
398                "credentials": {
399                    "connectionString": "nested-secret"
400                }
401            }
402        });
403
404        redact_credentials(&mut input);
405
406        assert_eq!(
407            input["outer"]["credentials"]["connectionString"],
408            "<REDACTED>"
409        );
410    }
411
412    #[test]
413    fn test_redact_storage_connection_string() {
414        let mut input = json!({
415            "name": "test",
416            "storageConnectionStringSecret": "my-storage-secret"
417        });
418
419        redact_credentials(&mut input);
420
421        assert_eq!(input["storageConnectionStringSecret"], "<REDACTED>");
422    }
423
424    #[test]
425    fn test_redact_multiple_targets() {
426        let mut input = json!({
427            "name": "test",
428            "credentials": {
429                "connectionString": "secret-conn"
430            },
431            "storageConnectionStringSecret": "secret-storage"
432        });
433
434        redact_credentials(&mut input);
435
436        assert_eq!(input["credentials"]["connectionString"], "<REDACTED>");
437        assert_eq!(input["storageConnectionStringSecret"], "<REDACTED>");
438    }
439
440    #[test]
441    fn test_redact_credentials_in_array() {
442        let mut input = json!({
443            "dataSources": [
444                {
445                    "name": "ds1",
446                    "credentials": {
447                        "connectionString": "secret1"
448                    }
449                },
450                {
451                    "name": "ds2",
452                    "credentials": {
453                        "connectionString": "secret2"
454                    }
455                }
456            ]
457        });
458
459        redact_credentials(&mut input);
460
461        assert_eq!(
462            input["dataSources"][0]["credentials"]["connectionString"],
463            "<REDACTED>"
464        );
465        assert_eq!(
466            input["dataSources"][1]["credentials"]["connectionString"],
467            "<REDACTED>"
468        );
469    }
470
471    #[test]
472    fn test_format_json_trailing_newline() {
473        let input = json!({"key": "value"});
474        let output = format_json(&input);
475        assert!(output.ends_with('\n'));
476    }
477
478    #[test]
479    fn test_format_json_empty_object() {
480        let input = json!({});
481        let output = format_json(&input);
482        assert_eq!(output, "{}\n");
483    }
484}