-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpublisher.rs
More file actions
855 lines (747 loc) · 31 KB
/
Copy pathpublisher.rs
File metadata and controls
855 lines (747 loc) · 31 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
//! Publisher response handler.
//!
//! **Note on platform coupling:** This module is currently coupled to
//! `fastly::Body`/`Request`/`Response` at its handler boundaries — for example,
//! `process_response_streaming` accepts and returns `fastly::Body`. This is an
//! HTTP-type coupling that will be addressed in the HTTP-type migration alongside
//! all other `fastly::Request`/`Response`/`Body` migrations. It is not a
//! content-rewriting concern.
use error_stack::{Report, ResultExt};
use fastly::http::{header, StatusCode};
use fastly::{Body, Request, Response};
use crate::backend::BackendConfig;
use crate::consent::{allows_ssc_creation, build_consent_context, ConsentPipelineInput};
use crate::constants::{COOKIE_SYNTHETIC_ID, HEADER_X_COMPRESS_HINT, HEADER_X_SYNTHETIC_ID};
use crate::cookies::{expire_synthetic_cookie, handle_request_cookies, set_synthetic_cookie};
use crate::error::TrustedServerError;
use crate::http_util::{serve_static_with_etag, RequestInfo};
use crate::integrations::IntegrationRegistry;
use crate::platform::RuntimeServices;
use crate::rsc_flight::RscFlightUrlRewriter;
use crate::settings::Settings;
use crate::streaming_processor::{Compression, PipelineConfig, StreamProcessor, StreamingPipeline};
use crate::streaming_replacer::create_url_replacer;
use crate::synthetic::{get_or_generate_synthetic_id, is_valid_synthetic_id};
const SUPPORTED_ENCODING_VALUES: [&str; 3] = ["gzip", "deflate", "br"];
fn restrict_accept_encoding(req: &mut Request) {
// If the client sent no Accept-Encoding, leave the request unchanged so the
// origin responds without compression. Adding encodings here would cause the
// origin to compress its response even though the client never asked for it,
// and the client would then receive content it cannot decode.
let Some(current) = req
.get_header(header::ACCEPT_ENCODING)
.and_then(|value| value.to_str().ok())
else {
return;
};
req.set_header(
header::ACCEPT_ENCODING,
select_supported_accept_encoding(current),
);
}
fn select_supported_accept_encoding(client_accept_encoding: &str) -> String {
let supported_subset = SUPPORTED_ENCODING_VALUES
.into_iter()
.filter(|encoding| client_accepts_content_encoding(client_accept_encoding, encoding))
.collect::<Vec<_>>();
if supported_subset.is_empty() {
return "identity".to_string();
}
supported_subset.join(", ")
}
fn client_accepts_content_encoding(header_value: &str, encoding: &str) -> bool {
accept_encoding_qvalue(header_value, encoding)
.or_else(|| accept_encoding_qvalue(header_value, "*"))
.is_some_and(|qvalue| qvalue > 0.0)
}
fn accept_encoding_qvalue(header_value: &str, target: &str) -> Option<f32> {
let mut matched_qvalue = None;
for item in header_value.split(',') {
let item = item.trim();
if item.is_empty() {
continue;
}
let mut parts = item.split(';');
let Some(token) = parts.next().map(str::trim) else {
continue;
};
if !token.eq_ignore_ascii_case(target) {
continue;
}
let mut qvalue = 1.0;
for parameter in parts {
let Some((name, value)) = parameter.trim().split_once('=') else {
continue;
};
if name.trim().eq_ignore_ascii_case("q") {
if let Ok(parsed_qvalue) = value.trim().parse::<f32>() {
qvalue = parsed_qvalue;
}
}
}
// First match wins per RFC 7231 — duplicate tokens are non-normative,
// but using first-match is the conventional interpretation.
matched_qvalue = Some(qvalue);
break;
}
matched_qvalue
}
/// Unified tsjs static serving: `/static/tsjs=<filename>`
///
/// Serves two types of bundles:
/// - **Unified bundle** (`tsjs-unified.min.js`): core + immediate (non-deferred)
/// integration modules.
/// - **Deferred module** (`tsjs-{id}.min.js`): a single self-contained IIFE for
/// modules loaded with `defer` (e.g., prebid).
///
/// # Errors
///
/// This function never returns an error; the Result type is for API consistency.
pub fn handle_tsjs_dynamic(
req: &Request,
integration_registry: &IntegrationRegistry,
) -> Result<Response, Report<TrustedServerError>> {
const PREFIX: &str = "/static/tsjs=";
const UNIFIED_FILENAMES: &[&str] = &["tsjs-unified.js", "tsjs-unified.min.js"];
let path = req.get_path();
if !path.starts_with(PREFIX) {
return Ok(Response::from_status(StatusCode::NOT_FOUND).with_body("Not Found"));
}
let filename = &path[PREFIX.len()..];
if UNIFIED_FILENAMES.contains(&filename) {
// Serve core + immediate modules (excludes deferred like prebid)
let module_ids = integration_registry.js_module_ids_immediate();
let body = trusted_server_js::concatenate_modules(&module_ids);
let mut resp = serve_static_with_etag(&body, req, "application/javascript; charset=utf-8");
resp.set_header(HEADER_X_COMPRESS_HINT, "on");
return Ok(resp);
}
if let Some(module_id) = parse_deferred_module_filename(filename) {
// Only serve if the deferred module is actually enabled
let deferred_ids = integration_registry.js_module_ids_deferred();
if !deferred_ids.contains(&module_id) {
return Ok(Response::from_status(StatusCode::NOT_FOUND).with_body("Not Found"));
}
if let Some(content) = trusted_server_js::module_bundle(module_id) {
let mut resp =
serve_static_with_etag(content, req, "application/javascript; charset=utf-8");
resp.set_header(HEADER_X_COMPRESS_HINT, "on");
return Ok(resp);
}
}
Ok(Response::from_status(StatusCode::NOT_FOUND).with_body("Not Found"))
}
/// Extract a module ID from a deferred-module filename like `tsjs-prebid.min.js`.
///
/// Returns `Some(&'static str)` if the filename matches a known JS module ID,
/// `None` otherwise. The caller must additionally verify that the module is
/// both deferred and enabled via the [`IntegrationRegistry`].
#[must_use]
fn parse_deferred_module_filename(filename: &str) -> Option<&'static str> {
let stem = filename
.strip_prefix("tsjs-")
.and_then(|s| s.strip_suffix(".min.js").or_else(|| s.strip_suffix(".js")))?;
trusted_server_js::all_module_ids()
.into_iter()
.find(|&id| id == stem)
}
/// Parameters for processing response streaming
struct ProcessResponseParams<'a> {
content_encoding: &'a str,
origin_host: &'a str,
origin_url: &'a str,
request_host: &'a str,
request_scheme: &'a str,
settings: &'a Settings,
content_type: &'a str,
integration_registry: &'a IntegrationRegistry,
}
/// Process response body in streaming fashion with compression preservation
fn process_response_streaming(
body: Body,
params: &ProcessResponseParams,
) -> Result<Body, Report<TrustedServerError>> {
// Check if this is HTML content
let is_html = params.content_type.contains("text/html");
let is_rsc_flight = params.content_type.contains("text/x-component");
log::debug!(
"process_response_streaming: content_type={}, content_encoding={}, is_html={}, is_rsc_flight={}, origin_host={}",
params.content_type,
params.content_encoding,
is_html,
is_rsc_flight,
params.origin_host
);
// Determine compression type
let compression = Compression::from_content_encoding(params.content_encoding);
// Create output body to collect results
let mut output = Vec::new();
// Choose processor based on content type
if is_html {
// Use HTML rewriter for HTML content
let processor = create_html_stream_processor(
params.origin_host,
params.request_host,
params.request_scheme,
params.settings,
params.integration_registry,
)?;
let config = PipelineConfig {
input_compression: compression,
output_compression: compression,
chunk_size: 8192,
};
let mut pipeline = StreamingPipeline::new(config, processor);
pipeline.process(body, &mut output)?;
} else if is_rsc_flight {
// RSC Flight responses are length-prefixed (T rows). A naive string replacement will
// corrupt the stream by changing byte lengths without updating the prefixes.
let processor = RscFlightUrlRewriter::new(
params.origin_host,
params.origin_url,
params.request_host,
params.request_scheme,
);
let config = PipelineConfig {
input_compression: compression,
output_compression: compression,
chunk_size: 8192,
};
let mut pipeline = StreamingPipeline::new(config, processor);
pipeline.process(body, &mut output)?;
} else {
// Use simple text replacer for non-HTML content
let replacer = create_url_replacer(
params.origin_host,
params.origin_url,
params.request_host,
params.request_scheme,
);
let config = PipelineConfig {
input_compression: compression,
output_compression: compression,
chunk_size: 8192,
};
let mut pipeline = StreamingPipeline::new(config, replacer);
pipeline.process(body, &mut output)?;
}
log::debug!(
"Streaming processing complete - output size: {} bytes",
output.len()
);
Ok(Body::from(output))
}
/// Create a unified HTML stream processor
fn create_html_stream_processor(
origin_host: &str,
request_host: &str,
request_scheme: &str,
settings: &Settings,
integration_registry: &IntegrationRegistry,
) -> Result<impl StreamProcessor, Report<TrustedServerError>> {
use crate::html_processor::{create_html_processor, HtmlProcessorConfig};
let config = HtmlProcessorConfig::from_settings(
settings,
integration_registry,
origin_host,
request_host,
request_scheme,
);
Ok(create_html_processor(config))
}
/// Proxies requests to the publisher's origin server.
///
/// This function forwards incoming requests to the configured origin URL,
/// preserving headers and request body. It's used as a fallback for routes
/// not explicitly handled by the trusted server.
///
/// # Errors
///
/// Returns a [`TrustedServerError`] if:
/// - The proxy request fails
/// - The origin backend is unreachable
pub fn handle_publisher_request(
settings: &Settings,
integration_registry: &IntegrationRegistry,
services: &RuntimeServices,
mut req: Request,
) -> Result<Response, Report<TrustedServerError>> {
log::debug!("Proxying request to publisher_origin");
// Prebid.js requests are not intercepted here anymore. The HTML processor removes
// publisher-supplied Prebid scripts; the unified TSJS bundle includes Prebid.js when enabled.
// Extract request host and scheme (uses Host header and TLS detection after edge sanitization)
let request_info = RequestInfo::from_request(&req, &services.client_info);
let request_host = &request_info.host;
let request_scheme = &request_info.scheme;
log::debug!(
"Request info: host={}, scheme={} (X-Forwarded-Host: {:?}, Host: {:?}, X-Forwarded-Proto: {:?})",
request_host,
request_scheme,
req.get_header("x-forwarded-host"),
req.get_header(header::HOST),
req.get_header("x-forwarded-proto"),
);
// Parse cookies once for reuse by both consent extraction and synthetic ID logic.
let cookie_jar = handle_request_cookies(&req)?;
// Capture the current SSC cookie value for revocation handling.
// This must come from the cookie itself (not the x-synthetic-id header)
// to ensure KV deletion targets the same identifier being revoked.
let existing_ssc_cookie = cookie_jar
.as_ref()
.and_then(|jar| jar.get(COOKIE_SYNTHETIC_ID))
.map(|cookie| cookie.value().to_owned());
// Generate synthetic identifiers before the request body is consumed.
// Always generated for internal use (KV lookups, logging) even when
// consent is absent — the cookie is only *set* when consent allows it.
let synthetic_id = get_or_generate_synthetic_id(settings, services, &req)?;
// Extract, decode, and log consent signals (TCF, GPP, US Privacy, GPC)
// from the incoming request. The ConsentContext carries both raw strings
// (for OpenRTB forwarding) and decoded data (for enforcement).
// When a consent_store is configured, this also persists consent to KV
// and falls back to stored consent when cookies are absent.
let geo = services
.geo()
.lookup(services.client_info.client_ip)
.unwrap_or_else(|e| {
log::warn!("geo lookup failed: {e}");
None
});
let consent_context = build_consent_context(&ConsentPipelineInput {
jar: cookie_jar.as_ref(),
req: &req,
config: &settings.consent,
geo: geo.as_ref(),
synthetic_id: Some(synthetic_id.as_str()),
});
let ssc_allowed = allows_ssc_creation(&consent_context);
log::debug!(
"Proxy synthetic IDs - trusted: {}, ssc_allowed: {}",
synthetic_id,
ssc_allowed,
);
let backend_name = BackendConfig::from_url(
&settings.publisher.origin_url,
settings.proxy.certificate_check,
)?;
let origin_host = settings.publisher.origin_host();
log::debug!(
"Proxying to dynamic backend: {} (from {})",
backend_name,
settings.publisher.origin_url
);
// Only advertise encodings the rewrite pipeline can decode and re-encode.
restrict_accept_encoding(&mut req);
req.set_header("host", &origin_host);
let mut response = req
.send(&backend_name)
.change_context(TrustedServerError::Proxy {
message: "Failed to proxy request to origin".to_string(),
})?;
// Log all response headers for debugging
log::debug!("Response headers:");
for (name, value) in response.get_headers() {
log::debug!(" {}: {:?}", name, value);
}
// Check if the response has a text-based content type that we should process
let content_type = response
.get_header(header::CONTENT_TYPE)
.map(|h| h.to_str().unwrap_or_default())
.unwrap_or_default()
.to_string();
let should_process = content_type.contains("text/")
|| content_type.contains("application/javascript")
|| content_type.contains("application/json");
if should_process && !request_host.is_empty() {
// Check if the response is compressed
let content_encoding = response
.get_header(header::CONTENT_ENCODING)
.map(|h| h.to_str().unwrap_or_default())
.unwrap_or_default()
.to_lowercase();
// Log response details for debugging
log::debug!(
"Processing response - Content-Type: {}, Content-Encoding: {}, Request Host: {}, Origin Host: {}",
content_type, content_encoding, request_host, origin_host
);
// Take the response body for streaming processing
let body = response.take_body();
// Process the body using streaming approach
let params = ProcessResponseParams {
content_encoding: &content_encoding,
origin_host: &origin_host,
origin_url: &settings.publisher.origin_url,
request_host,
request_scheme,
settings,
content_type: &content_type,
integration_registry,
};
match process_response_streaming(body, ¶ms) {
Ok(processed_body) => {
// Set the processed body back
response.set_body(processed_body);
// Remove Content-Length as the size has likely changed
response.remove_header(header::CONTENT_LENGTH);
// Keep Content-Encoding header since we're returning compressed content
log::debug!(
"Preserved Content-Encoding: {} for compressed response",
content_encoding
);
log::debug!("Completed streaming processing of response body");
}
Err(e) => {
log::error!("Failed to process response body: {:?}", e);
// Return an error response
return Err(e);
}
}
} else {
log::debug!(
"Skipping response processing - should_process: {}, request_host: '{}'",
should_process,
request_host
);
}
// Consent-gated SSC creation:
// - Consent given → set synthetic ID header + cookie.
// - Consent absent + existing cookie → revoke (expire cookie + delete KV entry).
// - Consent absent + no cookie → do nothing.
if ssc_allowed {
// Fastly's HeaderValue API rejects \r, \n, and \0, so the synthetic ID
// cannot inject additional response headers.
response.set_header(HEADER_X_SYNTHETIC_ID, synthetic_id.as_str());
// Cookie persistence is skipped if the synthetic ID contains RFC 6265-illegal
// characters. The header is still emitted when consent allows it.
set_synthetic_cookie(settings, &mut response, synthetic_id.as_str());
} else if let Some(cookie_synthetic_id) = existing_ssc_cookie.as_deref() {
// Always expire the cookie — consent is withdrawn regardless of whether the
// stored value is well-formed.
expire_synthetic_cookie(settings, &mut response);
if is_valid_synthetic_id(cookie_synthetic_id) {
log::info!(
"SSC revoked: consent withdrawn (jurisdiction={})",
consent_context.jurisdiction,
);
if let Some(store_name) = &settings.consent.consent_store {
crate::consent::kv::delete_consent_from_kv(store_name, cookie_synthetic_id);
}
} else {
log::warn!(
"SSC cookie has invalid format, skipping KV deletion (len={}, jurisdiction={})",
cookie_synthetic_id.len(),
consent_context.jurisdiction,
);
}
} else {
log::debug!(
"SSC skipped: no consent and no existing cookie (jurisdiction={})",
consent_context.jurisdiction,
);
}
Ok(response)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::integrations::IntegrationRegistry;
use crate::platform::test_support::noop_services;
use crate::test_support::tests::{create_test_settings, VALID_SYNTHETIC_ID};
use fastly::http::{header, Method, StatusCode};
#[test]
fn test_content_type_detection() {
// Test which content types should be processed
let test_cases = vec![
("text/html", true),
("text/html; charset=utf-8", true),
("text/css", true),
("text/javascript", true),
("application/javascript", true),
("application/json", true),
("application/json; charset=utf-8", true),
("image/jpeg", false),
("image/png", false),
("application/pdf", false),
("video/mp4", false),
("application/octet-stream", false),
];
for (content_type, should_process) in test_cases {
let result = content_type.contains("text/html")
|| content_type.contains("text/css")
|| content_type.contains("text/javascript")
|| content_type.contains("application/javascript")
|| content_type.contains("application/json");
assert_eq!(
result, should_process,
"Content-Type '{}' should_process: expected {}, got {}",
content_type, should_process, result
);
}
}
#[test]
fn test_publisher_origin_host_extraction() {
let settings = create_test_settings();
let origin_host = settings.publisher.origin_host();
assert_eq!(origin_host, "origin.test-publisher.com");
// Test with port
let mut settings_with_port = create_test_settings();
settings_with_port.publisher.origin_url = "origin.test-publisher.com:8080".to_string();
assert_eq!(
settings_with_port.publisher.origin_host(),
"origin.test-publisher.com:8080"
);
}
#[test]
fn test_invalid_utf8_handling() {
// Test that invalid UTF-8 bytes are handled gracefully
let invalid_utf8_bytes = vec![0xFF, 0xFE, 0xFD]; // Invalid UTF-8 sequence
// Verify these bytes cannot be converted to a valid UTF-8 string
assert!(String::from_utf8(invalid_utf8_bytes.clone()).is_err());
// In the actual function, invalid UTF-8 would be passed through unchanged
// This test verifies our approach is sound
}
#[test]
fn test_utf8_conversion_edge_cases() {
// Test various UTF-8 edge cases
let test_cases = vec![
// Valid UTF-8 with special characters
(vec![0xE2, 0x98, 0x83], true), // ☃ (snowman)
(vec![0xF0, 0x9F, 0x98, 0x80], true), // 😀 (emoji)
// Invalid UTF-8 sequences
(vec![0xFF, 0xFE], false), // Invalid start byte
(vec![0xC0, 0x80], false), // Overlong encoding
(vec![0xED, 0xA0, 0x80], false), // Surrogate half
];
for (bytes, should_be_valid) in test_cases {
let result = String::from_utf8(bytes.clone());
assert_eq!(
result.is_ok(),
should_be_valid,
"UTF-8 validation failed for bytes: {:?}",
bytes
);
}
}
// Note: test_streaming_compressed_content removed as it directly tested private function
// process_response_streaming. The functionality is tested through handle_publisher_request.
// Note: test_streaming_brotli_content removed as it directly tested private function
// process_response_streaming. The functionality is tested through handle_publisher_request.
#[test]
fn test_content_encoding_detection() {
// Test that we properly handle responses with various content encodings
let test_encodings = vec!["gzip", "deflate", "br", "identity", ""];
for encoding in test_encodings {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header("accept-encoding", "gzip, deflate, br");
if !encoding.is_empty() {
req.set_header("content-encoding", encoding);
}
let content_encoding = req
.get_header("content-encoding")
.map(|h| h.to_str().unwrap_or_default())
.unwrap_or_default();
assert_eq!(content_encoding, encoding);
}
}
#[test]
fn publisher_proxy_does_not_add_accept_encoding_when_absent() {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
// No Accept-Encoding header set by the client.
restrict_accept_encoding(&mut req);
assert_eq!(
req.get_header_str(header::ACCEPT_ENCODING),
None,
"publisher proxy should not inject Accept-Encoding when the client sent none"
);
}
#[test]
fn publisher_proxy_limits_accept_encoding_to_supported_values() {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header(header::ACCEPT_ENCODING, "gzip, deflate, br, zstd");
restrict_accept_encoding(&mut req);
assert_eq!(
req.get_header_str(header::ACCEPT_ENCODING),
Some("gzip, deflate, br"),
"publisher fallback should only advertise encodings the rewrite pipeline supports"
);
}
#[test]
fn publisher_proxy_preserves_identity_only_accept_encoding() {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header(header::ACCEPT_ENCODING, "identity");
restrict_accept_encoding(&mut req);
assert_eq!(
req.get_header_str(header::ACCEPT_ENCODING),
Some("identity"),
"publisher fallback should preserve identity-only clients"
);
}
#[test]
fn publisher_proxy_respects_supported_client_subset() {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header(header::ACCEPT_ENCODING, "br, gzip;q=0, zstd");
restrict_accept_encoding(&mut req);
assert_eq!(
req.get_header_str(header::ACCEPT_ENCODING),
Some("br"),
"publisher fallback should only advertise the supported encodings the client accepts"
);
}
#[test]
fn publisher_proxy_falls_back_to_identity_for_unsupported_client_encodings() {
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header(header::ACCEPT_ENCODING, "zstd");
restrict_accept_encoding(&mut req);
assert_eq!(
req.get_header_str(header::ACCEPT_ENCODING),
Some("identity"),
"publisher fallback should request identity when the client only accepts unsupported encodings"
);
}
#[test]
fn revocation_targets_cookie_synthetic_id_not_header() {
let settings = create_test_settings();
let cookie_synthetic_id =
"b2a1c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0c1d2e3f4a5b6c7d8e9f0b1a2.Zx98y7";
let mut req = Request::new(Method::GET, "https://test.example.com/page");
req.set_header(HEADER_X_SYNTHETIC_ID, VALID_SYNTHETIC_ID);
req.set_header(
header::COOKIE,
format!("synthetic_id={cookie_synthetic_id}; other=value"),
);
let cookie_jar = handle_request_cookies(&req).expect("should parse cookies");
let existing_ssc_cookie = cookie_jar
.as_ref()
.and_then(|jar| jar.get(COOKIE_SYNTHETIC_ID))
.map(|cookie| cookie.value().to_owned());
let resolved_synthetic_id = get_or_generate_synthetic_id(&settings, &noop_services(), &req)
.expect("should resolve synthetic id");
assert_eq!(
existing_ssc_cookie.as_deref(),
Some(cookie_synthetic_id),
"should read revocation target from cookie value"
);
assert_eq!(
resolved_synthetic_id, VALID_SYNTHETIC_ID,
"should still resolve request synthetic ID from header precedence"
);
}
#[test]
fn tsjs_dynamic_returns_not_found_for_unknown_filename() {
let settings = create_test_settings();
let registry =
IntegrationRegistry::new(&settings).expect("should create integration registry");
let req = Request::new(
Method::GET,
"https://publisher.example/static/tsjs=unknown.js",
);
let response = handle_tsjs_dynamic(&req, ®istry).expect("should handle tsjs request");
assert_eq!(response.get_status(), StatusCode::NOT_FOUND);
}
#[test]
fn tsjs_dynamic_serves_unified_bundle_for_known_filename() {
let settings = create_test_settings();
let registry =
IntegrationRegistry::new(&settings).expect("should create integration registry");
let req = Request::new(
Method::GET,
"https://publisher.example/static/tsjs=tsjs-unified.min.js",
);
let response = handle_tsjs_dynamic(&req, ®istry).expect("should handle tsjs request");
assert_eq!(response.get_status(), StatusCode::OK);
}
#[test]
fn parse_deferred_module_filename_extracts_known_id() {
assert_eq!(
parse_deferred_module_filename("tsjs-prebid.min.js"),
Some("prebid"),
"should extract prebid from minified filename"
);
assert_eq!(
parse_deferred_module_filename("tsjs-prebid.js"),
Some("prebid"),
"should extract prebid from unminified filename"
);
}
#[test]
fn parse_deferred_module_filename_rejects_unknown_ids() {
assert_eq!(
parse_deferred_module_filename("tsjs-evil.min.js"),
None,
"should reject unknown module names"
);
assert_eq!(
parse_deferred_module_filename("tsjs-core.min.js"),
Some("core"),
"should accept any known module ID (deferred check happens in caller)"
);
assert_eq!(
parse_deferred_module_filename("prebid.min.js"),
None,
"should reject without tsjs- prefix"
);
assert_eq!(
parse_deferred_module_filename("tsjs-prebid.txt"),
None,
"should reject non-js extension"
);
}
#[test]
fn tsjs_dynamic_serves_deferred_prebid_when_enabled() {
// Default test settings include prebid enabled
let settings = create_test_settings();
let registry =
IntegrationRegistry::new(&settings).expect("should create integration registry");
let req = Request::new(
Method::GET,
"https://publisher.example/static/tsjs=tsjs-prebid.min.js",
);
let response = handle_tsjs_dynamic(&req, ®istry).expect("should handle tsjs request");
assert_eq!(
response.get_status(),
StatusCode::OK,
"should serve deferred prebid module when enabled"
);
}
#[test]
fn tsjs_dynamic_returns_not_found_for_disabled_deferred_module() {
let mut settings = create_test_settings();
settings
.integrations
.insert_config(
"prebid",
&serde_json::json!({
"enabled": false,
"server_url": "https://test-prebid.com/openrtb2/auction"
}),
)
.expect("should update prebid config");
let registry =
IntegrationRegistry::new(&settings).expect("should create integration registry");
let req = Request::new(
Method::GET,
"https://publisher.example/static/tsjs=tsjs-prebid.min.js",
);
let response = handle_tsjs_dynamic(&req, ®istry).expect("should handle tsjs request");
assert_eq!(
response.get_status(),
StatusCode::NOT_FOUND,
"should return 404 for disabled deferred module"
);
}
#[test]
fn tsjs_dynamic_returns_not_found_for_arbitrary_module_name() {
let settings = create_test_settings();
let registry =
IntegrationRegistry::new(&settings).expect("should create integration registry");
let req = Request::new(
Method::GET,
"https://publisher.example/static/tsjs=tsjs-evil.min.js",
);
let response = handle_tsjs_dynamic(&req, ®istry).expect("should handle tsjs request");
assert_eq!(
response.get_status(),
StatusCode::NOT_FOUND,
"should reject unknown module names"
);
}
}