-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathproxy.rs
More file actions
1863 lines (1694 loc) · 65.8 KB
/
proxy.rs
File metadata and controls
1863 lines (1694 loc) · 65.8 KB
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
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::http_util::{compute_encrypted_sha256_token, ct_str_eq};
use error_stack::{Report, ResultExt};
use fastly::http::{header, HeaderValue, Method, StatusCode};
use fastly::{Request, Response};
use serde::{Deserialize, Serialize};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use crate::constants::{
HEADER_ACCEPT, HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_LANGUAGE, HEADER_REFERER,
HEADER_USER_AGENT, HEADER_X_FORWARDED_FOR,
};
use crate::creative::{CreativeCssProcessor, CreativeHtmlProcessor};
use crate::error::TrustedServerError;
use crate::settings::Settings;
use crate::streaming_processor::{Compression, PipelineConfig, StreamProcessor, StreamingPipeline};
use crate::synthetic::get_synthetic_id;
/// Chunk size used for streaming content through the rewrite pipeline.
const STREAMING_CHUNK_SIZE: usize = 8192;
#[derive(Deserialize)]
struct ProxySignReq {
url: String,
}
#[derive(Serialize)]
struct ProxySignResp {
href: String,
base: String,
}
/// Configuration for outbound proxying from integration routes.
#[derive(Debug, Clone)]
pub struct ProxyRequestConfig<'a> {
/// Target URL to proxy to (must be http/https).
pub target_url: &'a str,
/// Whether redirects should be followed automatically.
pub follow_redirects: bool,
/// Whether to append the caller's synthetic ID as a query param.
pub forward_synthetic_id: bool,
/// Optional body to send to the origin.
pub body: Option<Vec<u8>>,
/// Additional headers to forward to the origin.
pub headers: Vec<(header::HeaderName, HeaderValue)>,
/// Whether to forward the helper's curated request-header set.
pub copy_request_headers: bool,
/// When true, stream the origin response without HTML/CSS rewrites.
pub stream_passthrough: bool,
}
impl<'a> ProxyRequestConfig<'a> {
/// Build a proxy configuration that follows redirects and forwards the synthetic ID.
#[must_use]
pub fn new(target_url: &'a str) -> Self {
Self {
target_url,
follow_redirects: true,
forward_synthetic_id: true,
body: None,
headers: Vec::new(),
copy_request_headers: true,
stream_passthrough: false,
}
}
/// Attach a request body to the proxied request.
#[must_use]
pub fn with_body(mut self, body: Vec<u8>) -> Self {
self.body = Some(body);
self
}
/// Append an additional header to the proxied request.
#[must_use]
pub fn with_header(mut self, name: header::HeaderName, value: HeaderValue) -> Self {
self.headers.push((name, value));
self
}
/// Disable forwarding of the helper's curated request-header set.
#[must_use]
pub fn without_forward_headers(mut self) -> Self {
self.copy_request_headers = false;
self
}
/// Enable streaming passthrough (no HTML/CSS rewrites).
#[must_use]
pub fn with_streaming(mut self) -> Self {
self.stream_passthrough = true;
self
}
}
/// Encodings we support decompressing in `finalize_proxied_response`.
/// We override the client's Accept-Encoding to only advertise these.
const SUPPORTED_ENCODINGS: &str = "gzip, deflate, br";
/// Copy a curated set of request headers to a proxied request.
fn copy_proxy_forward_headers(src: &Request, dst: &mut Request) {
for header_name in [
HEADER_USER_AGENT,
HEADER_ACCEPT,
HEADER_ACCEPT_LANGUAGE,
HEADER_REFERER,
HEADER_X_FORWARDED_FOR,
] {
if let Some(v) = src.get_header(&header_name) {
dst.set_header(&header_name, v);
}
}
// Only advertise encodings we can decompress (excludes zstd, etc.)
dst.set_header(HEADER_ACCEPT_ENCODING, SUPPORTED_ENCODINGS);
}
/// Rebuild a response with a new body, preserving headers except Content-Length.
/// If `preserve_encoding` is true, the Content-Encoding header is kept (for compressed responses).
/// If false, Content-Encoding is stripped (for decompressed responses).
fn rebuild_response_with_body(
beresp: &Response,
content_type: &'static str,
body: Vec<u8>,
preserve_encoding: bool,
) -> Response {
let status = beresp.get_status();
let headers: Vec<(header::HeaderName, HeaderValue)> = beresp
.get_headers()
.map(|(name, value)| (name.clone(), value.clone()))
.collect();
let mut resp = Response::from_status(status);
for (name, value) in headers {
// Always skip Content-Length (size changed) and Content-Type (we set it)
if name == header::CONTENT_LENGTH || name == header::CONTENT_TYPE {
continue;
}
// Skip Content-Encoding only if we're not preserving it
if name == header::CONTENT_ENCODING && !preserve_encoding {
continue;
}
resp.set_header(name, value);
}
resp.set_header(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
resp.set_body(body);
resp
}
/// Process a response body through a streaming pipeline with the given processor.
///
/// Handles decompression, content processing, and re-compression while preserving
/// the response status and headers.
fn process_response_with_pipeline<P: StreamProcessor>(
mut beresp: Response,
processor: P,
compression: Compression,
content_type: &'static str,
error_context: &'static str,
) -> Result<Response, Report<TrustedServerError>> {
let config = PipelineConfig {
input_compression: compression,
output_compression: compression,
chunk_size: STREAMING_CHUNK_SIZE,
};
let body = beresp.take_body();
let mut output = Vec::new();
let mut pipeline = StreamingPipeline::new(config, processor);
pipeline
.process(body, &mut output)
.change_context(TrustedServerError::Proxy {
message: error_context.to_string(),
})?;
Ok(rebuild_response_with_body(
&beresp,
content_type,
output,
compression != Compression::None,
))
}
fn finalize_proxied_response(
settings: &Settings,
req: &Request,
target_url: &str,
mut beresp: Response,
) -> Result<Response, Report<TrustedServerError>> {
// Determine content-type and content-encoding from response headers
let status_code = beresp.get_status().as_u16();
let ct_raw = beresp
.get_header(header::CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.unwrap_or("")
.to_string();
let content_encoding = beresp
.get_header(header::CONTENT_ENCODING)
.and_then(|h| h.to_str().ok())
.unwrap_or("")
.to_string();
let cl_raw = beresp
.get_header(header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.unwrap_or("-");
let accept_raw = req
.get_header(HEADER_ACCEPT)
.and_then(|h| h.to_str().ok())
.unwrap_or("-");
let ct_for_log: &str = if ct_raw.is_empty() { "-" } else { &ct_raw };
let ce_for_log: &str = if content_encoding.is_empty() {
"-"
} else {
&content_encoding
};
log::info!(
"origin response status={} ct={} ce={} cl={} accept={} url={}",
status_code,
ct_for_log,
ce_for_log,
cl_raw,
accept_raw,
target_url
);
let ct = ct_raw.to_ascii_lowercase();
let compression = Compression::from_content_encoding(&content_encoding);
if ct.contains("text/html") {
let processor = CreativeHtmlProcessor::new(settings);
return process_response_with_pipeline(
beresp,
processor,
compression,
"text/html; charset=utf-8",
"Failed to process HTML response",
);
}
if ct.contains("text/css") {
let processor = CreativeCssProcessor::new(settings);
return process_response_with_pipeline(
beresp,
processor,
compression,
"text/css; charset=utf-8",
"Failed to process CSS response",
);
}
// Image handling: set generic content-type if missing and log pixel heuristics
let req_accept_images = req
.get_header(HEADER_ACCEPT)
.and_then(|h| h.to_str().ok())
.map(|s| s.to_ascii_lowercase().contains("image/"))
.unwrap_or(false);
if ct.starts_with("image/") || req_accept_images {
if beresp.get_header(header::CONTENT_TYPE).is_none() {
beresp.set_header(header::CONTENT_TYPE, "image/*");
}
// Heuristics to log likely tracking pixels without altering response
let mut is_pixel = false;
if let Some(cl) = beresp
.get_header(header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
if cl <= 256 {
// typical 1x1 PNG/GIF are very small
is_pixel = true;
}
}
// Path heuristics: common pixel patterns
if !is_pixel {
let lower = target_url.to_ascii_lowercase();
if lower.contains("/pixel")
|| lower.ends_with("/p.gif")
|| lower.contains("1x1")
|| lower.contains("/track")
{
is_pixel = true;
}
}
if is_pixel {
log::info!("likely pixel image fetched: {} ct={}", target_url, ct);
}
return Ok(beresp);
}
// Passthrough for non-text, non-image responses
Ok(beresp)
}
fn finalize_proxied_response_streaming(
req: &Request,
target_url: &str,
mut beresp: Response,
) -> Response {
let status_code = beresp.get_status().as_u16();
let ct_raw = beresp
.get_header(header::CONTENT_TYPE)
.and_then(|h| h.to_str().ok())
.unwrap_or("")
.to_string();
let cl_raw = beresp
.get_header(header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.unwrap_or("-");
let accept_raw = req
.get_header(HEADER_ACCEPT)
.and_then(|h| h.to_str().ok())
.unwrap_or("-");
let ct_for_log: &str = if ct_raw.is_empty() { "-" } else { &ct_raw };
log::info!(
"origin response status={} ct={} cl={} accept={} url={}",
status_code,
ct_for_log,
cl_raw,
accept_raw,
target_url
);
let ct = ct_raw.to_ascii_lowercase();
let req_accept_images = req
.get_header(HEADER_ACCEPT)
.and_then(|h| h.to_str().ok())
.map(|s| s.to_ascii_lowercase().contains("image/"))
.unwrap_or(false);
if ct.starts_with("image/") || req_accept_images {
if beresp.get_header(header::CONTENT_TYPE).is_none() {
beresp.set_header(header::CONTENT_TYPE, "image/*");
}
let mut is_pixel = false;
if let Some(cl) = beresp
.get_header(header::CONTENT_LENGTH)
.and_then(|h| h.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
{
if cl <= 256 {
is_pixel = true;
}
}
if !is_pixel {
let lower = target_url.to_ascii_lowercase();
if lower.contains("/pixel")
|| lower.ends_with("/p.gif")
|| lower.contains("1x1")
|| lower.contains("/track")
{
is_pixel = true;
}
}
if is_pixel {
log::info!(
"stream: likely pixel image fetched: {} ct={}",
target_url,
ct
);
}
}
beresp
}
/// Finalize a proxied response, choosing between streaming passthrough and full
/// content processing based on the `stream_passthrough` flag.
fn finalize_response(
settings: &Settings,
req: &Request,
url: &str,
beresp: Response,
stream_passthrough: bool,
) -> Result<Response, Report<TrustedServerError>> {
if stream_passthrough {
Ok(finalize_proxied_response_streaming(req, url, beresp))
} else {
finalize_proxied_response(settings, req, url, beresp)
}
}
struct ProxyRequestHeaders<'a> {
additional_headers: &'a [(header::HeaderName, HeaderValue)],
copy_request_headers: bool,
}
/// Proxy a request to a clear target URL while reusing creative rewrite logic.
///
/// This forwards a curated header set, follows redirects when enabled, and can append
/// the caller's synthetic ID as a `synthetic_id` query parameter to the target URL.
/// Optional bodies/headers can be supplied via [`ProxyRequestConfig`].
///
/// # Errors
///
/// - [`TrustedServerError::Proxy`] if the target URL is invalid, uses an unsupported
/// scheme, lacks a host, or the upstream fetch fails
pub async fn proxy_request(
settings: &Settings,
req: Request,
config: ProxyRequestConfig<'_>,
) -> Result<Response, Report<TrustedServerError>> {
let ProxyRequestConfig {
target_url,
follow_redirects,
forward_synthetic_id,
body,
headers,
copy_request_headers,
stream_passthrough,
} = config;
let mut target_url_parsed = url::Url::parse(target_url).map_err(|_| {
Report::new(TrustedServerError::Proxy {
message: "invalid url".to_string(),
})
})?;
if forward_synthetic_id {
append_synthetic_id(&req, &mut target_url_parsed);
}
proxy_with_redirects(
settings,
&req,
target_url_parsed,
follow_redirects,
body.as_deref(),
ProxyRequestHeaders {
additional_headers: &headers,
copy_request_headers,
},
stream_passthrough,
)
.await
}
fn append_synthetic_id(req: &Request, target_url_parsed: &mut url::Url) {
let synthetic_id_param = match get_synthetic_id(req) {
Ok(id) => id,
Err(e) => {
log::warn!("failed to extract synthetic ID for forwarding: {:?}", e);
None
}
};
if let Some(synthetic_id) = synthetic_id_param {
let mut pairs: Vec<(String, String)> = target_url_parsed
.query_pairs()
.filter(|(k, _)| k.as_ref() != "synthetic_id")
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect();
pairs.push(("synthetic_id".to_string(), synthetic_id));
target_url_parsed.set_query(None);
if !pairs.is_empty() {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
for (k, v) in &pairs {
serializer.append_pair(k, v);
}
let query_str = serializer.finish();
target_url_parsed.set_query(Some(&query_str));
}
log::debug!(
"forwarding synthetic_id to origin url {}",
target_url_parsed.as_str()
);
} else {
log::debug!("no synthetic_id to forward to origin");
}
}
async fn proxy_with_redirects(
settings: &Settings,
req: &Request,
target_url_parsed: url::Url,
follow_redirects: bool,
body: Option<&[u8]>,
request_headers: ProxyRequestHeaders<'_>,
stream_passthrough: bool,
) -> Result<Response, Report<TrustedServerError>> {
const MAX_REDIRECTS: usize = 4;
let mut current_url = target_url_parsed.to_string();
let mut current_method: Method = req.get_method().clone();
for redirect_attempt in 0..=MAX_REDIRECTS {
let parsed_url = url::Url::parse(¤t_url).map_err(|_| {
Report::new(TrustedServerError::Proxy {
message: "invalid url".to_string(),
})
})?;
let scheme = parsed_url.scheme().to_ascii_lowercase();
if scheme != "http" && scheme != "https" {
return Err(Report::new(TrustedServerError::Proxy {
message: "unsupported scheme".to_string(),
}));
}
let host = parsed_url.host_str().unwrap_or("");
if host.is_empty() {
return Err(Report::new(TrustedServerError::Proxy {
message: "missing host".to_string(),
}));
}
let backend_name = crate::backend::BackendConfig::new(&scheme, host)
.port(parsed_url.port())
.certificate_check(settings.proxy.certificate_check)
.ensure()?;
let mut proxy_req = Request::new(current_method.clone(), ¤t_url);
if request_headers.copy_request_headers {
copy_proxy_forward_headers(req, &mut proxy_req);
}
if let Some(body_bytes) = body {
proxy_req.set_body(body_bytes.to_vec());
}
for (name, value) in request_headers.additional_headers {
proxy_req.set_header(name.clone(), value.clone());
}
let beresp = proxy_req
.send(&backend_name)
.change_context(TrustedServerError::Proxy {
message: "Failed to proxy".to_string(),
})?;
if !follow_redirects {
return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough);
}
let status = beresp.get_status();
let is_redirect = matches!(
status,
StatusCode::MOVED_PERMANENTLY
| StatusCode::FOUND
| StatusCode::SEE_OTHER
| StatusCode::TEMPORARY_REDIRECT
| StatusCode::PERMANENT_REDIRECT
);
if !is_redirect {
return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough);
}
let Some(location) = beresp
.get_header(header::LOCATION)
.and_then(|h| h.to_str().ok())
.filter(|value| !value.is_empty())
else {
return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough);
};
if redirect_attempt == MAX_REDIRECTS {
log::warn!(
"redirect limit reached for {}; returning redirect response",
current_url
);
return finalize_proxied_response(settings, req, ¤t_url, beresp);
}
let next_url = url::Url::parse(location)
.or_else(|_| parsed_url.join(location))
.map_err(|_| {
Report::new(TrustedServerError::Proxy {
message: "invalid redirect".to_string(),
})
})?;
let next_scheme = next_url.scheme().to_ascii_lowercase();
if next_scheme != "http" && next_scheme != "https" {
return finalize_response(settings, req, ¤t_url, beresp, stream_passthrough);
}
log::info!(
"following redirect {} => {} (status {})",
current_url,
next_url,
status.as_u16()
);
current_url = next_url.to_string();
if status == StatusCode::SEE_OTHER {
current_method = Method::GET;
}
}
Err(Report::new(TrustedServerError::Proxy {
message: "redirect handling failed".to_string(),
}))
}
/// Unified proxy endpoint for resources referenced by ad creatives.
///
/// Accepts:
/// - `u`: Base64 URL-safe (no padding) encoded URL of the third-party resource.
///
/// Behavior:
/// - Proxies the decoded URL via a dynamic backend derived from scheme/host/port.
/// - If the response `Content-Type` contains `text/html`, rewrites the HTML creative
/// (img/srcset/iframe to first-party) before returning `text/html; charset=utf-8`.
/// - If the response is an image or the request `Accept` indicates images, ensures a
/// generic `image/*` content type if origin omitted it, and logs likely 1×1 pixels
/// using simple size/URL heuristics. No special response (still proxied).
///
/// # Errors
///
/// Returns an error if the signed target cannot be reconstructed or validation fails.
pub async fn handle_first_party_proxy(
settings: &Settings,
req: Request,
) -> Result<Response, Report<TrustedServerError>> {
// Parse, reconstruct, and validate the signed target URL
let SignedTarget { target_url, .. } =
reconstruct_and_validate_signed_target(settings, req.get_url_str())?;
proxy_request(
settings,
req,
ProxyRequestConfig {
target_url: &target_url,
follow_redirects: true,
forward_synthetic_id: true,
body: None,
headers: Vec::new(),
copy_request_headers: true,
stream_passthrough: false,
},
)
.await
}
/// First-party click redirect endpoint.
///
/// Accepts the same parameters as the proxy scheme, but instead of proxying the
/// content, it validates the URL and issues a 302 redirect to the reconstructed
/// target URL. This avoids parsing/downloading the content and lets the browser
/// navigate directly to the destination under first-party control.
///
/// # Errors
///
/// Returns an error if the signed target cannot be reconstructed or validation fails.
pub async fn handle_first_party_click(
settings: &Settings,
req: Request,
) -> Result<Response, Report<TrustedServerError>> {
let SignedTarget {
target_url: full_for_token,
tsurl,
had_params,
} = reconstruct_and_validate_signed_target(settings, req.get_url_str())?;
let synthetic_id = match get_synthetic_id(&req) {
Ok(id) => id,
Err(e) => {
log::warn!("failed to extract synthetic ID for forwarding: {:?}", e);
None
}
};
let mut redirect_target = full_for_token.clone();
if let Some(ref synthetic_id_value) = synthetic_id {
match url::Url::parse(&redirect_target) {
Ok(mut url) => {
let mut pairs: Vec<(String, String)> = url
.query_pairs()
.filter(|(k, _)| k.as_ref() != "synthetic_id")
.map(|(k, v)| (k.into_owned(), v.into_owned()))
.collect();
pairs.push(("synthetic_id".to_string(), synthetic_id_value.clone()));
url.set_query(None);
if !pairs.is_empty() {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
for (k, v) in &pairs {
serializer.append_pair(k, v);
}
let query_str = serializer.finish();
url.set_query(Some(&query_str));
}
let final_target = url.to_string();
log::debug!("forwarding synthetic_id to target url {}", final_target);
redirect_target = final_target;
}
Err(e) => {
log::warn!(
"failed to parse target url for synthetic forwarding: {:?}",
e
);
}
}
}
// Log click metadata for observability
let ua = req
.get_header(HEADER_USER_AGENT)
.and_then(|h| h.to_str().ok())
.unwrap_or("");
let referer = req
.get_header(HEADER_REFERER)
.and_then(|h| h.to_str().ok())
.unwrap_or("");
log::info!(
"redirect tsurl={} params_present={} target={} referer={} ua={} synthetic_id={}",
tsurl,
had_params,
redirect_target,
referer,
ua,
synthetic_id.as_deref().unwrap_or("")
);
// 302 redirect to target URL
Ok(Response::from_status(fastly::http::StatusCode::FOUND)
.with_header(header::LOCATION, &redirect_target)
.with_header(header::CACHE_CONTROL, "no-store, private"))
}
/// Sign an arbitrary asset URL so creatives can request first-party proxying at runtime.
/// Supports POST JSON and GET query (`?url=`) payloads. Embeds a short-lived `tsexp` (30s)
/// in the signature so the signed URL cannot be replayed indefinitely. Returns JSON
/// `{ href, base }` where `href` is the signed `/first-party/proxy?...` path and `base`
/// is the normalized clear URL.
///
/// # Errors
///
/// Returns an error if JSON parsing fails, the URL cannot be parsed, or the URL uses an unsupported scheme.
pub async fn handle_first_party_proxy_sign(
settings: &Settings,
mut req: Request,
) -> Result<Response, Report<TrustedServerError>> {
let method = req.get_method().clone();
let payload = if method == fastly::http::Method::POST {
let body = req.take_body_str();
serde_json::from_str::<ProxySignReq>(&body).change_context(TrustedServerError::Proxy {
message: "invalid JSON".to_string(),
})?
} else {
let parsed =
url::Url::parse(req.get_url_str()).change_context(TrustedServerError::Proxy {
message: "Invalid URL".to_string(),
})?;
let url = parsed
.query_pairs()
.find(|(k, _)| k == "url")
.map(|(_, v)| v.into_owned())
.ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "missing url".to_string(),
})
})?;
ProxySignReq { url }
};
let trimmed = payload.url.trim();
let abs = if trimmed.starts_with("//") {
let default_scheme = url::Url::parse(req.get_url_str())
.ok()
.map(|u| u.scheme().to_ascii_lowercase())
.filter(|scheme| !scheme.is_empty())
.unwrap_or_else(|| "https".to_string());
format!("{}:{}", default_scheme, trimmed)
} else {
crate::creative::to_abs(settings, trimmed).ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "unsupported url".to_string(),
})
})?
};
let parsed = url::Url::parse(&abs).change_context(TrustedServerError::Proxy {
message: "invalid url".to_string(),
})?;
let scheme = parsed.scheme();
if scheme != "http" && scheme != "https" {
return Err(Report::new(TrustedServerError::Proxy {
message: "unsupported scheme".to_string(),
}));
}
let now = SystemTime::now();
let expires = now.checked_add(Duration::from_secs(30)).unwrap_or(now);
let tsexp = expires
.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_secs()
.to_string();
let extras = vec![(String::from("tsexp"), tsexp)];
let mut base = parsed.clone();
base.set_query(None);
base.set_fragment(None);
let proxied = crate::creative::build_proxy_url_with_extras(settings, &abs, &extras);
let resp = ProxySignResp {
href: proxied,
base: base.to_string(),
};
let mut response = Response::from_status(fastly::http::StatusCode::OK);
response.set_header(header::CONTENT_TYPE, "application/json; charset=utf-8");
response.set_body(
serde_json::to_string(&resp).change_context(TrustedServerError::Proxy {
message: "failed to serialize".to_string(),
})?,
);
Ok(response)
}
#[derive(Deserialize)]
struct ProxyRebuildReq {
tsclick: String,
add: Option<std::collections::HashMap<String, String>>,
del: Option<Vec<String>>,
}
#[derive(Serialize)]
struct ProxyRebuildResp {
href: String,
base: String,
added: std::collections::BTreeMap<String, String>,
removed: Vec<String>,
}
/// Proxy rebuild endpoint.
/// POST /first-party/proxy-rebuild
/// Body: { tsclick: "/first-party/click?tsurl=...&a=1", add: {"b":"2"}, del: ["c"] }
/// - Only allows adding new parameters or removing existing ones.
/// - Base tsurl cannot change.
///
/// # Errors
///
/// Returns an error if JSON parsing fails, the URL is invalid, or the request body cannot be read.
pub async fn handle_first_party_proxy_rebuild(
settings: &Settings,
mut req: Request,
) -> Result<Response, Report<TrustedServerError>> {
let method = req.get_method().clone();
let payload = if method == fastly::http::Method::POST {
let body = req.take_body_str();
serde_json::from_str::<ProxyRebuildReq>(&body).change_context(
TrustedServerError::Proxy {
message: "invalid JSON".to_string(),
},
)?
} else {
// Support GET: /first-party/proxy-rebuild?tsclick=...&add=...&del=...
let parsed =
url::Url::parse(req.get_url_str()).change_context(TrustedServerError::Proxy {
message: "Invalid URL".to_string(),
})?;
let mut tsclick: Option<String> = None;
let mut add: Option<std::collections::HashMap<String, String>> = None;
let mut del: Option<Vec<String>> = None;
for (k, v) in parsed.query_pairs() {
match k.as_ref() {
"tsclick" => tsclick = Some(v.into_owned()),
"add" => {
if let Ok(m) =
serde_json::from_str::<std::collections::HashMap<String, String>>(&v)
{
add = Some(m);
}
}
"del" => {
if let Ok(arr) = serde_json::from_str::<Vec<String>>(&v) {
del = Some(arr);
}
}
_ => {}
}
}
ProxyRebuildReq {
tsclick: tsclick.ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "missing tsclick".to_string(),
})
})?,
add,
del,
}
};
let base = "https://edge.local"; // dummy origin to parse relative path
let c_url = url::Url::parse(&format!("{}{}", base, payload.tsclick)).change_context(
TrustedServerError::Proxy {
message: "invalid tsclick".to_string(),
},
)?;
if c_url.path() != "/first-party/click" {
return Err(Report::new(TrustedServerError::Proxy {
message: "invalid tsclick path".to_string(),
}));
}
// Extract tsurl and original params (exclude tstoken if present)
let mut tsurl: Option<String> = None;
let mut orig: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
for (k, v) in c_url.query_pairs() {
let key = k.as_ref();
if key == "tsurl" {
tsurl = Some(v.into_owned());
} else if key != "tstoken" {
orig.insert(key.to_string(), v.into_owned());
}
}
let tsurl = tsurl.ok_or_else(|| {
Report::new(TrustedServerError::Proxy {
message: "missing tsurl".to_string(),
})
})?;
// Keep a snapshot before modifications for diagnostics
let orig_before = orig.clone();
// Apply removals
if let Some(del) = &payload.del {
for k in del {
orig.remove(k);
}
}
// Apply additions (must be new keys only)
if let Some(add) = &payload.add {
for (k, v) in add {
if orig.contains_key(k) {
return Err(Report::new(TrustedServerError::Proxy {
message: format!("cannot modify existing parameter: {}", k),
}));
}
orig.insert(k.clone(), v.clone());
}
}
// Compute token over tsurl + updated params
let full_for_token = if orig.is_empty() {
tsurl.clone()
} else {
let mut s = url::form_urlencoded::Serializer::new(String::new());
for (k, v) in &orig {
s.append_pair(k, v);
}
format!("{}?{}", tsurl, s.finish())
};
let token = compute_encrypted_sha256_token(settings, &full_for_token);
// Build final href
let mut qs = url::form_urlencoded::Serializer::new(String::new());
qs.append_pair("tsurl", &tsurl);
for (k, v) in &orig {
qs.append_pair(k, v);
}
qs.append_pair("tstoken", &token);
let href = format!("/first-party/click?{}", qs.finish());
// Compute diagnostics: added and removed
let mut added: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
for (k, v) in &orig {
if !orig_before.contains_key(k) {
added.insert(k.clone(), v.clone());
}
}
let mut removed: Vec<String> = Vec::new();
for k in orig_before.keys() {
if !orig.contains_key(k) {
removed.push(k.clone());
}
}
if method == fastly::http::Method::GET {
// Redirect for GET usage to streamline navigation
Ok(Response::from_status(fastly::http::StatusCode::FOUND)
.with_header(header::LOCATION, href)
.with_header(header::CACHE_CONTROL, "no-store, private"))
} else {
let json = serde_json::to_string(&ProxyRebuildResp {
href,
base: tsurl.clone(),
added,
removed,
})
.unwrap_or_else(|_| "{}".to_string());
Ok(Response::from_status(fastly::http::StatusCode::OK)
.with_header(header::CONTENT_TYPE, "application/json; charset=utf-8")
.with_header(header::CACHE_CONTROL, "no-store, private")
.with_body(json))
}
}