proxelar 0.5.0

MITM proxy for HTTP/HTTPS traffic
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use bytes::Bytes;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use proxyapi::{InterceptConfig, InterceptDecision};
use proxyapi_models::ProxiedRequest;
use std::sync::Arc;
use tokio::sync::mpsc;

use super::state::{AppState, EditAction, EditSession};

/// Handle a key event. Returns true if the app should quit.
pub fn handle_key_event(
    key: KeyEvent,
    state: &mut AppState,
    intercept: &Arc<InterceptConfig>,
    replay_tx: &mpsc::Sender<ProxiedRequest>,
) -> bool {
    // Help overlay: consume all keys; ? or Esc closes it.
    if state.show_help {
        if matches!(key.code, KeyCode::Char('?') | KeyCode::Esc) {
            state.show_help = false;
        }
        return false;
    }

    // Inline editor: intercept ALL keys only while actively typing.
    if let Some(ref mut session) = state.edit_session {
        if session.typing {
            match session.handle_key(key) {
                EditAction::None => {}
                EditAction::StageEdits => {
                    session.typing = false;
                }
                EditAction::Discard => {
                    state.edit_session = None;
                }
            }
            return false;
        }
        // Review mode: only Esc is handled here; f/d/e fall through below.
        if key.code == KeyCode::Esc {
            state.edit_session = None;
            return false;
        }
    }

    // Filter mode: capture text input.
    if state.filter_mode {
        match key.code {
            KeyCode::Esc => {
                state.filter_mode = false;
                state.filter_input.clear();
                state.filter = None;
            }
            KeyCode::Enter => {
                state.filter_mode = false;
                if state.filter_input.is_empty() {
                    state.filter = None;
                } else {
                    state.filter = Some(state.filter_input.clone());
                }
            }
            KeyCode::Backspace => {
                state.filter_input.pop();
            }
            KeyCode::Char(c) => {
                state.filter_input.push(c);
            }
            _ => {}
        }
        return false;
    }

    // Detail panel focus: j/k scroll content, Tab switches tab, Enter/Esc return to table.
    if state.detail_focused {
        match key.code {
            KeyCode::Char('j') | KeyCode::Down => {
                state.frames_follow = false;
                state.detail_scroll = state.detail_scroll.saturating_add(1);
            }
            KeyCode::Char('k') | KeyCode::Up => {
                state.frames_follow = false;
                state.detail_scroll = state.detail_scroll.saturating_sub(1);
            }
            KeyCode::Tab => state.toggle_tab(),
            KeyCode::Enter | KeyCode::Esc => {
                state.detail_focused = false;
            }
            KeyCode::Char('q' | 'Q') => return true,
            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => return true,
            _ => {}
        }
        return false;
    }

    match key.code {
        KeyCode::Char('q' | 'Q') => return true,
        KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => return true,
        KeyCode::Char('j') | KeyCode::Down => state.select_next(),
        KeyCode::Char('k') | KeyCode::Up => state.select_prev(),
        KeyCode::Char('g') => state.select_first(),
        KeyCode::Char('G') => state.select_last(),
        KeyCode::Enter => {
            if state.detail_open {
                // Second Enter focuses the detail panel for scrolling.
                state.detail_focused = true;
            } else {
                state.detail_open = true;
            }
        }
        KeyCode::Tab => state.toggle_tab(),
        KeyCode::Char('/') => {
            state.filter_mode = true;
            state.filter_input.clear();
        }
        KeyCode::Esc => {
            if state.detail_open {
                state.detail_open = false;
                state.detail_focused = false;
            } else {
                state.filter = None;
            }
        }
        KeyCode::Char('c') => state.clear(),

        // Intercept controls
        KeyCode::Char('i') => {
            state.intercept_enabled = intercept.toggle();
        }
        KeyCode::Char('f') => {
            if let Some(ref session) = state.edit_session {
                // Try to parse first; only clear the session on success.
                let id = session.id;
                let text = session.to_text();
                match parse_edited_http_request(&text, session.binary_body) {
                    Ok((method, uri, headers, body)) => {
                        state.edit_session = None;
                        intercept.resolve(
                            id,
                            InterceptDecision::Modified {
                                method,
                                uri,
                                headers,
                                body,
                            },
                        );
                    }
                    Err(_) => {
                        // Keep the session open so the user can fix the text.
                        let s = state.edit_session.as_mut().unwrap();
                        s.parse_error = true;
                        s.typing = true;
                    }
                }
            } else if let Some(id) = state.selected_pending_id() {
                intercept.resolve(id, InterceptDecision::Forward);
            }
        }
        KeyCode::Char('d') => {
            // Discard any staged edits and drop the request.
            let id = state
                .edit_session
                .take()
                .map(|s| s.id)
                .or_else(|| state.selected_pending_id());
            if let Some(id) = id {
                intercept.resolve(
                    id,
                    InterceptDecision::Block {
                        status: 504,
                        body: Bytes::from_static(b"Blocked by Proxelar intercept"),
                    },
                );
                state.remove_pending_by_id(id);
            }
        }
        KeyCode::Char('e') => {
            // If a staged session already exists for this row, re-enter typing.
            if let Some(ref mut session) = state.edit_session {
                session.typing = true;
                session.parse_error = false;
                state.detail_open = true;
            } else if let Some((id, req)) = state.selected_pending_request() {
                let (text, binary_body) = request_to_text(req);
                let mut session = EditSession::new(id, &text);
                session.binary_body = binary_body;
                state.edit_session = Some(session);
                state.detail_open = true;
            }
        }

        KeyCode::Char('?') => state.show_help = true,

        KeyCode::Char('r') => {
            if let Some(req) = state.selected_request() {
                if replay_tx.try_send(req.clone()).is_err() {
                    tracing::warn!("Replay channel full, dropping request");
                }
            }
        }

        _ => {}
    }

    false
}

/// Serialise a `ProxiedRequest` as raw HTTP text for inline editing.
///
/// Returns `(text, binary_body)` where Protobuf/MessagePack bodies use a
/// structured JSON marker and other invalid UTF-8 bodies use hexadecimal.
fn request_to_text(req: &proxyapi_models::ProxiedRequest) -> (String, bool) {
    let mut text = format!("{} {} {:?}\n", req.method(), req.uri(), req.version());
    for (name, value) in req.headers() {
        text.push_str(&format!(
            "{}: {}\n",
            name,
            String::from_utf8_lossy(value.as_bytes())
        ));
    }
    text.push('\n');
    let structured = proxyapi::content::editable_content(req.headers(), req.body())
        .ok()
        .flatten();
    let binary_body = structured.is_some()
        || (!req.body().is_empty() && std::str::from_utf8(req.body()).is_err());
    if !req.body().is_empty() {
        if let Some(editor) = structured {
            text.push_str("@proxelar:");
            text.push_str(editor.format.as_str());
            text.push('\n');
            text.push_str(&editor.text);
        } else if binary_body {
            text.push_str("@proxelar:hex\n");
            for (index, byte) in req.body().iter().enumerate() {
                if index > 0 {
                    text.push(if index % 16 == 0 { '\n' } else { ' ' });
                }
                text.push_str(&format!("{byte:02x}"));
            }
        } else {
            text.push_str(&String::from_utf8_lossy(req.body()));
        }
    }
    (text, binary_body)
}

/// Parse a raw HTTP request text into (method, uri, headers, body).
///
/// Both `\r\n` and `\n` line endings are accepted.
fn parse_raw_http_request(text: &str) -> Result<(String, String, http::HeaderMap, Bytes), String> {
    let normalised = text.replace("\r\n", "\n");
    let mut parts = normalised.splitn(2, "\n\n");

    let header_section = parts.next().unwrap_or("");
    let body_str = parts.next().unwrap_or("");

    let mut header_lines = header_section.lines();

    let request_line = header_lines
        .next()
        .ok_or("Missing request line")?
        .trim_end();
    let mut fields = request_line.split_whitespace();
    let method = fields.next().ok_or("Missing method")?.trim().to_uppercase();
    let uri = fields.next().ok_or("Missing URI")?.trim().to_string();
    let version = fields.next().ok_or("Missing HTTP version")?;
    if fields.next().is_some() || !matches!(version, "HTTP/1.0" | "HTTP/1.1") {
        return Err("Request line must end with HTTP/1.0 or HTTP/1.1".to_owned());
    }
    method
        .parse::<http::Method>()
        .map_err(|error| format!("Invalid method: {error}"))?;
    uri.parse::<http::Uri>()
        .map_err(|error| format!("Invalid URI: {error}"))?;

    let mut headers = http::HeaderMap::new();
    for line in header_lines {
        let line = line.trim_end();
        if line.is_empty() {
            break;
        }
        let (name, value) = line
            .split_once(':')
            .ok_or_else(|| format!("Invalid header line: {line}"))?;
        let name = http::header::HeaderName::from_bytes(name.trim().as_bytes())
            .map_err(|error| format!("Invalid header name: {error}"))?;
        let value = http::header::HeaderValue::from_str(value.trim())
            .map_err(|error| format!("Invalid header value: {error}"))?;
        headers.append(name, value);
    }

    let body = Bytes::copy_from_slice(body_str.as_bytes());
    Ok((method, uri, headers, body))
}

fn parse_edited_http_request(
    text: &str,
    binary_body: bool,
) -> Result<(String, String, http::HeaderMap, Bytes), String> {
    let (method, uri, headers, body) = parse_raw_http_request(text)?;
    if !binary_body {
        return Ok((method, uri, headers, body));
    }
    let body = std::str::from_utf8(&body).map_err(|_| "Hex editor body is not UTF-8")?;
    if let Some(document) = body.strip_prefix("@proxelar:protobuf\n") {
        return proxyapi::content::encode_edit("protobuf", document)
            .map(|body| (method, uri, headers, body))
            .map_err(|error| error.to_string());
    }
    if let Some(document) = body.strip_prefix("@proxelar:messagepack\n") {
        return proxyapi::content::encode_edit("messagepack", document)
            .map(|body| (method, uri, headers, body))
            .map_err(|error| error.to_string());
    }
    let hex = body
        .strip_prefix("@proxelar:hex\n")
        .ok_or("Binary body must keep a supported @proxelar marker")?;
    let compact = hex
        .chars()
        .filter(|character| !character.is_whitespace())
        .collect::<String>();
    if compact.len() % 2 != 0 {
        return Err("Hex body must contain pairs of digits".to_owned());
    }
    let decoded = compact
        .as_bytes()
        .chunks_exact(2)
        .map(|pair| {
            let pair = std::str::from_utf8(pair).map_err(|_| "Invalid hex body")?;
            u8::from_str_radix(pair, 16).map_err(|_| "Invalid hex body")
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok((method, uri, headers, Bytes::from(decoded)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::KeyModifiers;
    use http::{HeaderMap, Method, Version};
    use proxyapi::ProxyEvent;
    use proxyapi_models::{ProxiedRequest, ProxiedResponse};

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn request(body: Bytes) -> ProxiedRequest {
        let mut headers = HeaderMap::new();
        headers.append("x-test", "one".parse().unwrap());
        headers.append("x-test", "two".parse().unwrap());
        ProxiedRequest::new(
            Method::POST,
            "http://api.test/path?x=1".parse().unwrap(),
            Version::HTTP_11,
            headers,
            body,
            100,
        )
    }

    #[test]
    fn parse_raw_http_request_accepts_crlf_and_repeated_headers() {
        let (method, uri, headers, body) = parse_raw_http_request(
            "patch http://api.test/items HTTP/1.1\r\n\
             x-test: one\r\n\
             x-test: two\r\n\
             \r\n\
             body",
        )
        .unwrap();

        assert_eq!(method, "PATCH");
        assert_eq!(uri, "http://api.test/items");
        assert_eq!(headers.get_all("x-test").iter().count(), 2);
        assert_eq!(body.as_ref(), b"body");
    }

    #[test]
    fn parse_raw_http_request_rejects_malformed_request_lines_and_headers() {
        for text in [
            "GET /missing-version\n\n",
            "GET %%% HTTP/1.1\n\n",
            "GET / HTTP/2\n\n",
            "GET / HTTP/1.1\ninvalid header\n\n",
        ] {
            assert!(
                parse_raw_http_request(text).is_err(),
                "should reject {text:?}"
            );
        }
    }

    #[test]
    fn request_to_text_preserves_headers_and_marks_binary_body() {
        let (text, binary_body) = request_to_text(&request(Bytes::from_static(b"\xff\x00")));

        assert!(text.starts_with("POST http://api.test/path?x=1 HTTP/1.1\n"));
        assert!(text.contains("x-test: one\n"));
        assert!(text.contains("x-test: two\n"));
        assert!(text.ends_with("@proxelar:hex\nff 00"));
        assert!(binary_body);
        let (_, _, _, body) = parse_edited_http_request(&text, binary_body).unwrap();
        assert_eq!(body.as_ref(), b"\xff\x00");
    }

    #[test]
    fn request_to_text_roundtrips_structured_protobuf_fields() {
        let mut headers = HeaderMap::new();
        headers.insert(
            http::header::CONTENT_TYPE,
            "application/x-protobuf".parse().unwrap(),
        );
        let request = ProxiedRequest::new(
            Method::POST,
            "http://api.test/protobuf".parse().unwrap(),
            Version::HTTP_11,
            headers,
            Bytes::from_static(&[0x08, 0x96, 0x01]),
            100,
        );
        let (text, structured) = request_to_text(&request);
        assert!(structured);
        assert!(text.contains("@proxelar:protobuf\n"));
        assert!(text.contains("\"value\": \"150\""));
        let edited = text.replacen("\"150\"", "\"151\"", 1);
        let (_, _, _, body) = parse_edited_http_request(&edited, true).unwrap();
        assert_eq!(body.as_ref(), &[0x08, 0x97, 0x01]);
    }

    #[test]
    fn handle_key_event_filter_mode_sets_and_clears_filter() {
        let intercept = InterceptConfig::new();
        let (replay_tx, _replay_rx) = mpsc::channel(1);
        let mut state = AppState::new();

        assert!(!handle_key_event(
            key(KeyCode::Char('/')),
            &mut state,
            &intercept,
            &replay_tx
        ));
        assert!(state.filter_mode);

        handle_key_event(key(KeyCode::Char('g')), &mut state, &intercept, &replay_tx);
        handle_key_event(key(KeyCode::Char('e')), &mut state, &intercept, &replay_tx);
        handle_key_event(key(KeyCode::Enter), &mut state, &intercept, &replay_tx);

        assert!(!state.filter_mode);
        assert_eq!(state.filter.as_deref(), Some("ge"));

        handle_key_event(key(KeyCode::Esc), &mut state, &intercept, &replay_tx);
        assert_eq!(state.filter, None);
    }

    #[test]
    fn handle_key_event_replays_selected_request() {
        let intercept = InterceptConfig::new();
        let (replay_tx, mut replay_rx) = mpsc::channel(1);
        let mut state = AppState::new();
        state.add_event(ProxyEvent::RequestComplete {
            id: 1,
            request: Box::new(request(Bytes::from_static(b"body"))),
            response: Box::new(ProxiedResponse::new(
                http::StatusCode::OK,
                Version::HTTP_11,
                HeaderMap::new(),
                Bytes::new(),
                200,
            )),
        });
        state.select_first();

        handle_key_event(key(KeyCode::Char('r')), &mut state, &intercept, &replay_tx);

        let replayed = replay_rx.try_recv().unwrap();
        assert_eq!(replayed.uri().path(), "/path");
        assert_eq!(replayed.body().as_ref(), b"body");
    }
}