1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
//! Body transformation middleware for proxy requests and responses
//!
//! This module provides functionality to transform request and response bodies
//! using JSONPath expressions and template expansion. Useful for browser proxy
//! mode where you want to inspect and replace values in intercepted traffic.
use crate::proxy::config::{BodyTransform, BodyTransformRule, TransformOperation};
use crate::templating::TemplateEngine;
use crate::Result;
use serde_json::Value;
use tracing::{debug, error, warn};
/// Body transformation middleware that applies JSONPath-based transformations
pub struct BodyTransformationMiddleware {
/// Request transformation rules
request_rules: Vec<BodyTransformRule>,
/// Response transformation rules
response_rules: Vec<BodyTransformRule>,
/// Template engine for expanding template tokens
template_engine: TemplateEngine,
}
impl BodyTransformationMiddleware {
/// Create a new body transformation middleware
pub fn new(
request_rules: Vec<BodyTransformRule>,
response_rules: Vec<BodyTransformRule>,
) -> Self {
Self {
request_rules,
response_rules,
template_engine: TemplateEngine::new(),
}
}
/// Transform a request body based on configured rules
pub fn transform_request_body(&self, url: &str, body: &mut Option<Vec<u8>>) -> Result<()> {
if body.is_none() || self.request_rules.is_empty() {
return Ok(());
}
// Find matching rules for this URL
let matching_rules: Vec<&BodyTransformRule> =
self.request_rules.iter().filter(|rule| rule.matches_url(url)).collect();
if matching_rules.is_empty() {
return Ok(());
}
// Try to parse as JSON
let body_str = match String::from_utf8(body.as_ref().unwrap().clone()) {
Ok(s) => s,
Err(_) => {
// Not UTF-8, skip transformation
return Ok(());
}
};
// Try to parse as JSON
let mut json: Value = match serde_json::from_str(&body_str) {
Ok(v) => v,
Err(_) => {
// Not JSON, skip transformation
debug!("Request body is not JSON, skipping transformation");
return Ok(());
}
};
// Apply all matching rules
for rule in matching_rules {
if let Err(e) = self.apply_transform_rule(&mut json, rule) {
warn!("Failed to apply request transformation rule: {}", e);
}
}
// Serialize back to bytes
let new_body = serde_json::to_vec(&json)?;
*body = Some(new_body);
Ok(())
}
/// Transform a response body based on configured rules
pub fn transform_response_body(
&self,
url: &str,
status_code: u16,
body: &mut Option<Vec<u8>>,
) -> Result<()> {
if body.is_none() || self.response_rules.is_empty() {
return Ok(());
}
// Find matching rules for this URL
let matching_rules: Vec<&BodyTransformRule> = self
.response_rules
.iter()
.filter(|rule| rule.matches_url(url) && rule.matches_status_code(status_code))
.collect();
if matching_rules.is_empty() {
return Ok(());
}
// Try to parse as JSON
let body_str = match String::from_utf8(body.as_ref().unwrap().clone()) {
Ok(s) => s,
Err(_) => {
// Not UTF-8, skip transformation
return Ok(());
}
};
// Try to parse as JSON
let mut json: Value = match serde_json::from_str(&body_str) {
Ok(v) => v,
Err(_) => {
// Not JSON, skip transformation
debug!("Response body is not JSON, skipping transformation");
return Ok(());
}
};
// Apply all matching rules
for rule in matching_rules {
if let Err(e) = self.apply_transform_rule(&mut json, rule) {
warn!("Failed to apply response transformation rule: {}", e);
}
}
// Serialize back to bytes
let new_body = serde_json::to_vec(&json)?;
*body = Some(new_body);
Ok(())
}
/// Apply a single transformation rule to JSON
fn apply_transform_rule(&self, json: &mut Value, rule: &BodyTransformRule) -> Result<()> {
for transform in &rule.body_transforms {
match self.apply_single_transform(json, transform) {
Ok(_) => {
debug!("Applied transformation: {} -> {}", transform.path, transform.replace);
}
Err(e) => {
error!("Failed to apply transformation {}: {}", transform.path, e);
// Continue with other transforms even if one fails
}
}
}
Ok(())
}
/// Apply a single transform to JSON using JSONPath
/// Uses a simplified path-based approach for common JSONPath expressions
fn apply_single_transform(&self, json: &mut Value, transform: &BodyTransform) -> Result<()> {
// For now, use the simplified path-based approach
// Full JSONPath support can be added later if needed
self.apply_single_transform_simple(json, transform)
}
}
// Simplified implementation that works with direct path access
impl BodyTransformationMiddleware {
/// Apply a single transform using a simplified path-based approach
/// This works for simple paths like "$.field" or "$.field.subfield"
fn apply_single_transform_simple(
&self,
json: &mut Value,
transform: &BodyTransform,
) -> Result<()> {
// Expand template in replacement value
let replacement_value = self.template_engine.expand_str(&transform.replace);
// Parse replacement value as JSON if possible, otherwise use as string
let replacement_json: Value = match serde_json::from_str(&replacement_value) {
Ok(v) => v,
Err(_) => Value::String(replacement_value.clone()),
};
// Extract path components (simplified - supports $.field.subfield)
let path = transform.path.trim_start_matches("$.");
let parts: Vec<&str> = path.split('.').collect();
if parts.is_empty() {
return Err(crate::Error::internal("Empty JSONPath".to_string()));
}
// Navigate to the target location
let mut current = json;
for (i, part) in parts.iter().enumerate() {
let is_last = i == parts.len() - 1;
if is_last {
// Apply the transformation
// Check type first to avoid multiple mutable borrows
match transform.operation {
TransformOperation::Replace => {
match current {
Value::Object(ref mut obj) => {
obj.insert(part.to_string(), replacement_json.clone());
}
Value::Array(ref mut arr) => {
if let Ok(idx) = part.parse::<usize>() {
if idx < arr.len() {
arr[idx] = replacement_json.clone();
}
}
}
_ => {}
}
// Break early since we're done
break;
}
TransformOperation::Add => {
if let Value::Object(ref mut obj) = current {
obj.insert(part.to_string(), replacement_json.clone());
}
// Break early since we're done
break;
}
TransformOperation::Remove => {
match current {
Value::Object(ref mut obj) => {
// part is &str, which String can Borrow from
obj.remove(*part);
}
Value::Array(ref mut arr) => {
if let Ok(idx) = part.parse::<usize>() {
if idx < arr.len() {
arr.remove(idx);
}
}
}
_ => {}
}
// Break early since we're done
break;
}
}
} else {
// Navigate deeper - use match to avoid borrow conflicts
match current {
Value::Object(ref mut obj) => {
current = obj
.entry(part.to_string())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
}
Value::Array(ref mut arr) => {
if let Ok(idx) = part.parse::<usize>() {
if idx < arr.len() {
current = &mut arr[idx];
} else {
return Err(crate::Error::internal(format!(
"Array index {} out of bounds",
idx
)));
}
} else {
return Err(crate::Error::internal(format!(
"Invalid array index: {}",
part
)));
}
}
_ => {
// Create intermediate objects as needed
*current = Value::Object(serde_json::Map::new());
if let Value::Object(ref mut obj) = current {
current = obj
.entry(part.to_string())
.or_insert_with(|| Value::Object(serde_json::Map::new()));
}
}
}
}
}
Ok(())
}
}