ivoryvalley 0.1.0

A transparent deduplication proxy for Mastodon and the Fediverse
Documentation
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! HTTP proxy handlers
//!
//! This module implements the core proxy functionality that forwards requests
//! from Mastodon clients to the upstream Mastodon server.

use axum::{
    body::Body,
    extract::{Request, State},
    http::{header, HeaderMap, Method, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

use crate::config::{AppState, Config};
use crate::db::{extract_dedup_uri, SeenUriStore};
use crate::recording::{now_timestamp, RecordedExchange, RecordedRequest, RecordedResponse};
use crate::websocket::{streaming_handler, WebSocketState};
use std::collections::HashMap;
use std::sync::Arc;

/// Headers that should NOT be forwarded to upstream
/// Note: accept-encoding is stripped to prevent gzip responses, which we need to parse as JSON
const STRIP_HEADERS: &[&str] = &["host", "connection", "transfer-encoding", "accept-encoding"];

/// Timeline endpoint prefixes that should have deduplication applied
const TIMELINE_ENDPOINTS: &[&str] = &[
    "/api/v1/timelines/home",
    "/api/v1/timelines/public",
    "/api/v1/timelines/list/",
    "/api/v1/timelines/tag/",
    "/api/v1/timelines/link",
    "/api/v1/trends/statuses",
];

/// Extract the proxy's base URL from the incoming request for redirect rewriting.
///
/// This determines how clients are reaching the proxy so we can rewrite
/// upstream redirect URLs to point back to the proxy.
fn get_proxy_base_url(headers: &HeaderMap, uri: &axum::http::Uri) -> Option<String> {
    // Try to get the Host header
    let host = headers
        .get("host")
        .and_then(|v| v.to_str().ok())
        .or_else(|| uri.host())?;

    // Determine scheme - check X-Forwarded-Proto first (for reverse proxies),
    // then fall back to the URI scheme, then default to http
    let scheme = headers
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok())
        .or_else(|| uri.scheme_str())
        .unwrap_or("http");

    Some(format!("{}://{}", scheme, host))
}

/// Rewrite a Set-Cookie header for proxy compatibility.
///
/// Removes Domain and Secure attributes so cookies work on the proxy origin.
fn rewrite_set_cookie_header(cookie: &str) -> String {
    let mut parts: Vec<&str> = cookie.split(';').map(|s| s.trim()).collect();

    // Filter out Domain and Secure attributes
    parts.retain(|part| {
        let lower = part.to_lowercase();
        !lower.starts_with("domain=") && lower != "secure"
    });

    parts.join("; ")
}

/// Rewrite a Location header value, replacing the upstream URL with the proxy URL.
fn rewrite_location_header(
    location: &str,
    upstream_url: &str,
    proxy_base_url: &Option<String>,
) -> String {
    let Some(ref proxy_url) = proxy_base_url else {
        return location.to_string();
    };

    // Parse both URLs to compare their origins properly
    let Ok(location_parsed) = url::Url::parse(location) else {
        return location.to_string();
    };

    let Ok(upstream_parsed) = url::Url::parse(upstream_url) else {
        return location.to_string();
    };

    // Compare scheme, host, and port (origins must match exactly)
    let location_origin = location_parsed.origin();
    let upstream_origin = upstream_parsed.origin();

    if location_origin == upstream_origin {
        // Parse proxy URL to extract its components
        if let Ok(proxy_parsed) = url::Url::parse(proxy_url) {
            // Build new URL with proxy origin but location's path/query/fragment
            let mut new_url = proxy_parsed.clone();
            new_url.set_path(location_parsed.path());
            new_url.set_query(location_parsed.query());
            new_url.set_fragment(location_parsed.fragment());
            return new_url.to_string();
        }
    }

    location.to_string()
}

/// Check if the given path is a timeline endpoint that should be filtered
fn is_timeline_endpoint(path: &str) -> bool {
    // Extract just the path without query parameters
    let path_only = path.split('?').next().unwrap_or(path);

    TIMELINE_ENDPOINTS
        .iter()
        .any(|prefix| path_only.starts_with(prefix))
}

/// Create the proxy router with all routes
pub fn create_proxy_router(config: Config, seen_store: SeenUriStore) -> Router {
    // Wrap the store in Arc to share between HTTP proxy and WebSocket handlers
    let seen_store = Arc::new(seen_store);

    let app_state = AppState::new(config, seen_store.clone());
    let ws_state = WebSocketState::new(app_state.clone(), seen_store);

    // The streaming route uses WebSocketState (with SeenUriStore for deduplication).
    // The fallback HTTP proxy uses AppState. Axum's .with_state() applies to
    // routes added before that call, so the order here is intentional.
    Router::new()
        .route("/api/v1/streaming", get(streaming_handler))
        .with_state(ws_state)
        .fallback(proxy_handler)
        .with_state(app_state)
}

/// Main proxy handler that forwards all requests to the upstream server
async fn proxy_handler(
    State(state): State<AppState>,
    request: Request<Body>,
) -> Result<Response, ProxyError> {
    let method = request.method().clone();
    let path = request
        .uri()
        .path_and_query()
        .map(|pq| pq.as_str())
        .unwrap_or("/")
        .to_string();

    // Capture the proxy's base URL from the Host header for rewriting redirects
    let proxy_base_url = get_proxy_base_url(request.headers(), request.uri());

    // Determine if this is a timeline endpoint that should be filtered
    let should_filter = method == Method::GET && is_timeline_endpoint(&path);

    // Check if we should record this request (only API requests)
    let should_record = state.traffic_recorder.is_some() && path.starts_with("/api/");

    // Capture request headers for recording
    let request_headers_for_recording: HashMap<String, String> = if should_record {
        request
            .headers()
            .iter()
            .filter_map(|(name, value)| {
                value
                    .to_str()
                    .ok()
                    .map(|v| (name.as_str().to_string(), v.to_string()))
            })
            .collect()
    } else {
        HashMap::new()
    };

    // Log request path for debugging
    // All API requests at trace level (useful for discovering which endpoints clients use)
    if path.starts_with("/api/") {
        tracing::trace!(
            "API request: {} {} (dedup: {})",
            method,
            path,
            should_filter
        );
    }
    // Timeline requests with filtering at debug level
    if should_filter {
        tracing::debug!("Timeline request (filtering enabled): {} {}", method, path);
    }

    // Build the upstream URL
    let upstream_url = format!("{}{}", state.config.upstream_url, path);

    // Build the upstream request
    let mut upstream_request = state.http_client.request(method.clone(), &upstream_url);

    // Forward headers (rewriting Origin/Referer for CSRF)
    let headers = build_upstream_headers(request.headers(), &state.config.upstream_url);
    for (name, value) in headers.iter() {
        if let Ok(value_str) = value.to_str() {
            upstream_request = upstream_request.header(name.as_str(), value_str);
        }
    }

    // Forward body for methods that have one, capturing for recording if needed
    let request_body_for_recording: Option<String> =
        if method == Method::POST || method == Method::PUT || method == Method::PATCH {
            let max_body_size = state.config.max_body_size;
            let body_bytes = axum::body::to_bytes(request.into_body(), max_body_size)
                .await
                .map_err(|e| {
                    // Check if this is a length limit error
                    let error_msg = e.to_string();
                    if error_msg.contains("length limit exceeded") {
                        ProxyError::PayloadTooLarge
                    } else {
                        ProxyError::BodyRead(error_msg)
                    }
                })?;

            // Capture body for recording (as UTF-8 string if possible)
            let body_for_recording = if should_record {
                String::from_utf8(body_bytes.to_vec()).ok()
            } else {
                None
            };

            upstream_request = upstream_request.body(body_bytes);
            body_for_recording
        } else {
            None
        };

    // Send request to upstream
    let upstream_response = upstream_request.send().await.map_err(|e| {
        if e.is_timeout() {
            ProxyError::Timeout(e.to_string())
        } else {
            ProxyError::Upstream(e.to_string())
        }
    })?;

    // Convert the response
    let status = upstream_response.status();
    let response_headers = upstream_response.headers().clone();
    let body = upstream_response
        .bytes()
        .await
        .map_err(|e| ProxyError::ResponseRead(e.to_string()))?;

    // Record the exchange if traffic recording is enabled
    if should_record {
        if let Some(ref recorder) = state.traffic_recorder {
            let response_headers_map: HashMap<String, String> = response_headers
                .iter()
                .filter_map(|(name, value)| {
                    value
                        .to_str()
                        .ok()
                        .map(|v| (name.as_str().to_string(), v.to_string()))
                })
                .collect();

            let exchange = RecordedExchange {
                timestamp: now_timestamp(),
                request: RecordedRequest {
                    method: method.to_string(),
                    path: path.clone(),
                    headers: request_headers_for_recording,
                    body: request_body_for_recording,
                },
                response: RecordedResponse {
                    status: status.as_u16(),
                    headers: response_headers_map,
                    body: String::from_utf8_lossy(&body).to_string(),
                },
            };

            if let Err(e) = recorder.record(&exchange) {
                tracing::warn!("Failed to record traffic: {}", e);
            }
        }
    }

    // Filter timeline responses if applicable
    let final_body = if should_filter && status.is_success() {
        filter_timeline_response(&body, &state)
    } else {
        body.to_vec()
    };

    // Build the response
    let mut response = Response::builder().status(status);

    // Forward response headers (except Content-Length which may have changed)
    for (name, value) in response_headers.iter() {
        let name_lower = name.as_str().to_lowercase();
        if STRIP_HEADERS.contains(&name_lower.as_str()) || name_lower == "content-length" {
            continue;
        }

        // Rewrite Location headers to point back to the proxy
        if name_lower == "location" {
            if let Ok(location_str) = value.to_str() {
                let rewritten = rewrite_location_header(
                    location_str,
                    &state.config.upstream_url,
                    &proxy_base_url,
                );
                if let Ok(header_value) = rewritten.parse::<header::HeaderValue>() {
                    tracing::debug!("Rewrote Location header: {} -> {}", location_str, rewritten);
                    response = response.header(name, header_value);
                    continue;
                }
            }
        }

        // Rewrite Set-Cookie headers to work with the proxy origin
        if name_lower == "set-cookie" {
            if let Ok(cookie_str) = value.to_str() {
                let rewritten = rewrite_set_cookie_header(cookie_str);
                if let Ok(header_value) = rewritten.parse::<header::HeaderValue>() {
                    tracing::debug!("Rewrote Set-Cookie header: {} -> {}", cookie_str, rewritten);
                    response = response.header(name, header_value);
                    continue;
                }
            }
        }

        response = response.header(name, value);
    }

    response
        .body(Body::from(final_body))
        .map_err(|e| ProxyError::ResponseBuild(e.to_string()))
}

/// Filter a timeline response, removing statuses that have already been seen.
///
/// Returns the filtered JSON as bytes. If parsing fails, returns the original body unchanged.
/// Handles edge cases like empty bodies (304 Not Modified) and non-JSON responses (HTML errors).
fn filter_timeline_response(body: &[u8], state: &AppState) -> Vec<u8> {
    // Handle empty body (e.g., 304 Not Modified responses)
    if body.is_empty() {
        tracing::debug!("Empty timeline response body, passing through");
        return body.to_vec();
    }

    // Quick check if response looks like a JSON array (starts with '[')
    // This avoids trying to parse HTML error pages or other non-JSON content
    let first_byte = body.first().copied().unwrap_or(0);
    if first_byte != b'[' {
        tracing::debug!(
            "Timeline response is not a JSON array (starts with '{}'{}), passing through",
            first_byte as char,
            if body.len() > 1 {
                format!("{}...", body.get(1).map(|b| *b as char).unwrap_or(' '))
            } else {
                String::new()
            }
        );
        return body.to_vec();
    }

    // Try to parse the body as a JSON array of statuses
    let statuses: Vec<serde_json::Value> = match serde_json::from_slice(body) {
        Ok(v) => v,
        Err(e) => {
            tracing::debug!("Failed to parse timeline response as JSON array: {}", e);
            // If we can't parse it, just pass through unchanged
            return body.to_vec();
        }
    };

    let original_count = statuses.len();
    tracing::debug!("Processing {} statuses for deduplication", original_count);

    // Filter out statuses we've already seen
    let mut filtered = Vec::new();
    let mut filtered_count = 0;
    let mut error_count = 0;

    for status in statuses {
        // Extract the deduplication URI
        let should_include = if let Some(uri) = extract_dedup_uri(&status) {
            // Atomically check if seen and mark as seen
            match state.seen_uri_store.check_and_mark(uri) {
                Ok(was_seen) => {
                    if was_seen {
                        tracing::debug!("Filtered duplicate status with URI: {}", uri);
                        filtered_count += 1;
                        false
                    } else {
                        tracing::trace!("Allowing new status with URI: {}", uri);
                        true
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to check/mark URI {}: {}", uri, e);
                    error_count += 1;
                    // On error, pass through the status
                    true
                }
            }
        } else {
            // No URI to deduplicate on, pass through
            tracing::trace!("Allowing status without URI field");
            true
        };

        if should_include {
            filtered.push(status);
        }
    }

    let final_count = filtered.len();
    if filtered_count > 0 || error_count > 0 {
        tracing::info!(
            "Timeline filtering: {} total, {} filtered, {} passed, {} errors",
            original_count,
            filtered_count,
            final_count,
            error_count
        );
    }

    // Serialize the filtered list back to JSON
    serde_json::to_vec(&filtered).unwrap_or_else(|e| {
        tracing::error!("Failed to serialize filtered timeline: {}", e);
        body.to_vec()
    })
}

/// Build headers to send to upstream, filtering and transforming as needed.
///
/// Rewrites Origin and Referer headers to point to the upstream server
/// so CSRF protection works correctly.
fn build_upstream_headers(client_headers: &HeaderMap, upstream_url: &str) -> HeaderMap {
    let mut upstream_headers = HeaderMap::new();

    // Parse upstream URL to get its origin
    let upstream_origin = url::Url::parse(upstream_url)
        .ok()
        .map(|u| format!("{}://{}", u.scheme(), u.host_str().unwrap_or("")));

    for (name, value) in client_headers.iter() {
        let name_lower = name.as_str().to_lowercase();

        // Skip headers we shouldn't forward
        if STRIP_HEADERS.contains(&name_lower.as_str()) {
            continue;
        }

        // Rewrite Origin header to upstream (for CSRF protection)
        if name_lower == "origin" {
            if let Some(ref origin) = upstream_origin {
                if let Ok(header_value) = origin.parse::<header::HeaderValue>() {
                    tracing::debug!("Rewrote Origin header to upstream: {}", origin);
                    upstream_headers.insert(name.clone(), header_value);
                    continue;
                }
            }
        }

        // Rewrite Referer header to upstream (for CSRF protection)
        if name_lower == "referer" {
            if let Ok(referer_str) = value.to_str() {
                // Replace the proxy origin with upstream origin in the referer
                if let (Ok(referer_url), Ok(upstream_parsed)) =
                    (url::Url::parse(referer_str), url::Url::parse(upstream_url))
                {
                    let mut new_referer = upstream_parsed.clone();
                    new_referer.set_path(referer_url.path());
                    new_referer.set_query(referer_url.query());
                    new_referer.set_fragment(referer_url.fragment());
                    if let Ok(header_value) = new_referer.as_str().parse::<header::HeaderValue>() {
                        tracing::debug!(
                            "Rewrote Referer header: {} -> {}",
                            referer_str,
                            new_referer
                        );
                        upstream_headers.insert(name.clone(), header_value);
                        continue;
                    }
                }
            }
        }

        // Forward all other headers
        upstream_headers.insert(name.clone(), value.clone());
    }

    upstream_headers
}

/// Errors that can occur during proxying
#[derive(Debug)]
pub enum ProxyError {
    /// Failed to read request body
    BodyRead(String),
    /// Request body exceeds the configured size limit
    PayloadTooLarge,
    /// Request to upstream server timed out
    Timeout(String),
    /// Failed to reach upstream server
    Upstream(String),
    /// Failed to read response from upstream
    ResponseRead(String),
    /// Failed to build response
    ResponseBuild(String),
}

impl IntoResponse for ProxyError {
    fn into_response(self) -> Response {
        let (status, message) = match self {
            ProxyError::BodyRead(e) => (StatusCode::BAD_REQUEST, format!("Body read error: {}", e)),
            ProxyError::PayloadTooLarge => (
                StatusCode::PAYLOAD_TOO_LARGE,
                "Request body exceeds maximum allowed size".to_string(),
            ),
            ProxyError::Timeout(e) => (
                StatusCode::GATEWAY_TIMEOUT,
                format!("Gateway timeout: {}", e),
            ),
            ProxyError::Upstream(e) => (StatusCode::BAD_GATEWAY, format!("Upstream error: {}", e)),
            ProxyError::ResponseRead(e) => (
                StatusCode::BAD_GATEWAY,
                format!("Response read error: {}", e),
            ),
            ProxyError::ResponseBuild(e) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("Response build error: {}", e),
            ),
        };

        Response::builder()
            .status(status)
            .header(header::CONTENT_TYPE, "application/json")
            .body(Body::from(format!(r#"{{"error":"{}"}}"#, message)))
            .unwrap_or_else(|_| {
                // Fallback: minimal response that always succeeds
                Response::builder()
                    .status(StatusCode::INTERNAL_SERVER_ERROR)
                    .body(Body::empty())
                    .expect("minimal response build should never fail")
            })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_build_upstream_headers_filters_host() {
        let mut client_headers = HeaderMap::new();
        client_headers.insert("host", "proxy.local".parse().unwrap());
        client_headers.insert("authorization", "Bearer token".parse().unwrap());

        let upstream = build_upstream_headers(&client_headers, "https://mastodon.social");

        assert!(upstream.get("host").is_none());
        assert!(upstream.get("authorization").is_some());
    }

    #[test]
    fn test_build_upstream_headers_passes_auth() {
        let mut client_headers = HeaderMap::new();
        client_headers.insert("authorization", "Bearer test_token".parse().unwrap());
        client_headers.insert("content-type", "application/json".parse().unwrap());

        let upstream = build_upstream_headers(&client_headers, "https://mastodon.social");

        assert_eq!(upstream.get("authorization").unwrap(), "Bearer test_token");
        assert_eq!(upstream.get("content-type").unwrap(), "application/json");
    }

    #[test]
    fn test_build_upstream_headers_rewrites_origin() {
        let mut client_headers = HeaderMap::new();
        client_headers.insert("origin", "http://localhost:8080".parse().unwrap());

        let upstream = build_upstream_headers(&client_headers, "https://nerdculture.de");

        assert_eq!(upstream.get("origin").unwrap(), "https://nerdculture.de");
    }

    #[test]
    fn test_build_upstream_headers_rewrites_referer() {
        let mut client_headers = HeaderMap::new();
        client_headers.insert(
            "referer",
            "http://localhost:8080/auth/sign_in".parse().unwrap(),
        );

        let upstream = build_upstream_headers(&client_headers, "https://nerdculture.de");

        assert_eq!(
            upstream.get("referer").unwrap(),
            "https://nerdculture.de/auth/sign_in"
        );
    }

    #[test]
    fn test_build_upstream_headers_strips_accept_encoding() {
        // Accept-Encoding must be stripped to prevent gzip responses
        // that the proxy cannot parse for deduplication
        let mut client_headers = HeaderMap::new();
        client_headers.insert("accept-encoding", "gzip, deflate, br".parse().unwrap());
        client_headers.insert("authorization", "Bearer token".parse().unwrap());

        let upstream = build_upstream_headers(&client_headers, "https://mastodon.social");

        assert!(
            upstream.get("accept-encoding").is_none(),
            "Accept-Encoding should be stripped to prevent gzip responses"
        );
        // Other headers should still pass through
        assert!(upstream.get("authorization").is_some());
    }

    #[test]
    fn test_is_timeline_endpoint_home() {
        assert!(is_timeline_endpoint("/api/v1/timelines/home"));
        assert!(is_timeline_endpoint("/api/v1/timelines/home?limit=20"));
        assert!(is_timeline_endpoint(
            "/api/v1/timelines/home?max_id=123&limit=20"
        ));
    }

    #[test]
    fn test_is_timeline_endpoint_public() {
        assert!(is_timeline_endpoint("/api/v1/timelines/public"));
        assert!(is_timeline_endpoint("/api/v1/timelines/public?local=true"));
    }

    #[test]
    fn test_is_timeline_endpoint_list() {
        assert!(is_timeline_endpoint("/api/v1/timelines/list/12345"));
        assert!(is_timeline_endpoint(
            "/api/v1/timelines/list/12345?limit=20"
        ));
    }

    #[test]
    fn test_is_timeline_endpoint_tag() {
        assert!(is_timeline_endpoint("/api/v1/timelines/tag/rust"));
        assert!(is_timeline_endpoint(
            "/api/v1/timelines/tag/mastodon?limit=40"
        ));
    }

    #[test]
    fn test_is_timeline_endpoint_link() {
        // Trending article timeline (added in newer Mastodon versions)
        assert!(is_timeline_endpoint("/api/v1/timelines/link"));
        assert!(is_timeline_endpoint("/api/v1/timelines/link?limit=20"));
        assert!(is_timeline_endpoint(
            "/api/v1/timelines/link?url=https://example.com/article"
        ));
    }

    #[test]
    fn test_is_timeline_endpoint_trends_statuses() {
        // Trending statuses endpoint
        assert!(is_timeline_endpoint("/api/v1/trends/statuses"));
        assert!(is_timeline_endpoint("/api/v1/trends/statuses?limit=20"));
        assert!(is_timeline_endpoint("/api/v1/trends/statuses?offset=10"));
    }

    #[test]
    fn test_is_timeline_endpoint_trends_tags_not_filtered() {
        // Trends/tags returns Tag objects, not statuses - should NOT be filtered
        assert!(!is_timeline_endpoint("/api/v1/trends/tags"));
        assert!(!is_timeline_endpoint("/api/v1/trends/links"));
    }

    #[test]
    fn test_is_timeline_endpoint_bookmarks_not_filtered() {
        // User wants to see all bookmarks, no filtering
        assert!(!is_timeline_endpoint("/api/v1/bookmarks"));
        assert!(!is_timeline_endpoint("/api/v1/bookmarks?limit=40"));
    }

    #[test]
    fn test_is_timeline_endpoint_favourites_not_filtered() {
        // User wants to see all favourites, no filtering
        assert!(!is_timeline_endpoint("/api/v1/favourites"));
        assert!(!is_timeline_endpoint("/api/v1/favourites?limit=40"));
    }

    #[test]
    fn test_is_timeline_endpoint_non_timeline() {
        assert!(!is_timeline_endpoint("/api/v1/accounts/verify_credentials"));
        assert!(!is_timeline_endpoint("/api/v1/statuses"));
        assert!(!is_timeline_endpoint("/api/v1/notifications"));
        assert!(!is_timeline_endpoint("/oauth/token"));
    }

    #[tokio::test]
    async fn test_proxy_error_into_response_body_read() {
        let error = ProxyError::BodyRead("test error".to_string());
        let response = error.into_response();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        assert_eq!(
            response.headers().get(header::CONTENT_TYPE).unwrap(),
            "application/json"
        );

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(body_str.contains("Body read error"));
        assert!(body_str.contains("test error"));
    }

    #[tokio::test]
    async fn test_proxy_error_into_response_upstream() {
        let error = ProxyError::Upstream("connection refused".to_string());
        let response = error.into_response();

        assert_eq!(response.status(), StatusCode::BAD_GATEWAY);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(body_str.contains("Upstream error"));
        assert!(body_str.contains("connection refused"));
    }

    #[tokio::test]
    async fn test_proxy_error_into_response_response_read() {
        let error = ProxyError::ResponseRead("timeout".to_string());
        let response = error.into_response();

        assert_eq!(response.status(), StatusCode::BAD_GATEWAY);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(body_str.contains("Response read error"));
    }

    #[tokio::test]
    async fn test_proxy_error_into_response_response_build() {
        let error = ProxyError::ResponseBuild("invalid header".to_string());
        let response = error.into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);

        let body = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let body_str = String::from_utf8(body.to_vec()).unwrap();
        assert!(body_str.contains("Response build error"));
    }

    #[test]
    fn test_rewrite_set_cookie_removes_domain_and_secure() {
        let cookie = "_mastodon_session=abc123; Domain=nerdculture.de; Path=/; Secure; HttpOnly; SameSite=Lax";
        let result = rewrite_set_cookie_header(cookie);

        assert_eq!(
            result,
            "_mastodon_session=abc123; Path=/; HttpOnly; SameSite=Lax"
        );
    }

    #[test]
    fn test_rewrite_set_cookie_preserves_simple_cookie() {
        let cookie = "session=xyz; Path=/; HttpOnly";
        let result = rewrite_set_cookie_header(cookie);

        assert_eq!(result, "session=xyz; Path=/; HttpOnly");
    }

    #[test]
    fn test_get_proxy_base_url_from_host_header() {
        let mut headers = HeaderMap::new();
        headers.insert("host", "localhost:8080".parse().unwrap());

        let uri: axum::http::Uri = "/api/v1/instance".parse().unwrap();
        let result = get_proxy_base_url(&headers, &uri);

        assert_eq!(result, Some("http://localhost:8080".to_string()));
    }

    #[test]
    fn test_get_proxy_base_url_with_forwarded_proto() {
        let mut headers = HeaderMap::new();
        headers.insert("host", "proxy.example.com".parse().unwrap());
        headers.insert("x-forwarded-proto", "https".parse().unwrap());

        let uri: axum::http::Uri = "/api/v1/instance".parse().unwrap();
        let result = get_proxy_base_url(&headers, &uri);

        assert_eq!(result, Some("https://proxy.example.com".to_string()));
    }

    #[test]
    fn test_get_proxy_base_url_no_host() {
        let headers = HeaderMap::new();
        let uri: axum::http::Uri = "/api/v1/instance".parse().unwrap();
        let result = get_proxy_base_url(&headers, &uri);

        assert_eq!(result, None);
    }

    #[test]
    fn test_rewrite_location_header_rewrites_upstream() {
        let location = "https://mastodon.social/oauth/authorize?client_id=abc";
        let upstream_url = "https://mastodon.social";
        let proxy_base_url = Some("http://localhost:8080".to_string());

        let result = rewrite_location_header(location, upstream_url, &proxy_base_url);

        assert_eq!(
            result,
            "http://localhost:8080/oauth/authorize?client_id=abc"
        );
    }

    #[test]
    fn test_rewrite_location_header_preserves_non_upstream() {
        let location = "https://other.example.com/callback";
        let upstream_url = "https://mastodon.social";
        let proxy_base_url = Some("http://localhost:8080".to_string());

        let result = rewrite_location_header(location, upstream_url, &proxy_base_url);

        // Should not rewrite URLs that don't match the upstream
        assert_eq!(result, "https://other.example.com/callback");
    }

    #[test]
    fn test_rewrite_location_header_no_proxy_url() {
        let location = "https://mastodon.social/oauth/authorize";
        let upstream_url = "https://mastodon.social";
        let proxy_base_url = None;

        let result = rewrite_location_header(location, upstream_url, &proxy_base_url);

        // Should pass through unchanged when no proxy URL
        assert_eq!(result, "https://mastodon.social/oauth/authorize");
    }

    #[test]
    fn test_rewrite_location_header_with_default_port() {
        // Port 443 is the default for https, so these are the same origin
        let location = "https://nerdculture.de:443/oauth/authorize?response_type=code";
        let upstream_url = "https://nerdculture.de";
        let proxy_base_url = Some("http://localhost:8080".to_string());

        let result = rewrite_location_header(location, upstream_url, &proxy_base_url);

        // Default port 443 is equivalent to no port for https - should rewrite
        assert_eq!(
            result,
            "http://localhost:8080/oauth/authorize?response_type=code"
        );
    }

    #[test]
    fn test_rewrite_location_header_with_non_default_port() {
        // Port 8443 is NOT the default for https, so these are different origins
        let location = "https://nerdculture.de:8443/oauth/authorize?response_type=code";
        let upstream_url = "https://nerdculture.de";
        let proxy_base_url = Some("http://localhost:8080".to_string());

        let result = rewrite_location_header(location, upstream_url, &proxy_base_url);

        // Different port means different origin - should NOT rewrite
        assert_eq!(
            result,
            "https://nerdculture.de:8443/oauth/authorize?response_type=code"
        );
    }
}