-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathprebid.rs
More file actions
7367 lines (6601 loc) · 259 KB
/
Copy pathprebid.rs
File metadata and controls
7367 lines (6601 loc) · 259 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 std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Duration;
use async_trait::async_trait;
use base64::{
Engine as _,
engine::general_purpose::{
STANDARD as BASE64_STANDARD, STANDARD_NO_PAD as BASE64_STANDARD_NO_PAD,
},
};
use edgezero_core::body::Body as EdgeBody;
use error_stack::{Report, ResultExt};
use http::header::HeaderValue;
use http::{Method, StatusCode, header};
use serde::{Deserialize, Serialize};
use serde_json::Value as Json;
use url::{Url, Url as ParsedUrl};
use validator::{Validate, ValidationError};
use crate::auction::orchestrator::ERROR_TYPE_HTTP_STATUS;
use crate::auction::provider::AuctionProvider;
use crate::auction::types::{
AuctionContext, AuctionRequest, AuctionResponse, Bid as AuctionBid, MediaType,
};
use crate::consent_config::ConsentForwardingMode;
use crate::cookies::{CONSENT_COOKIE_NAMES, strip_cookies};
use crate::error::TrustedServerError;
use crate::http_util::RequestInfo;
use crate::integrations::{
AttributeRewriteAction, IntegrationAttributeContext, IntegrationAttributeRewriter,
IntegrationEndpoint, IntegrationHeadInjector, IntegrationHtmlContext, IntegrationProxy,
IntegrationRegistration, UPSTREAM_RTB_MAX_RESPONSE_BYTES, collect_response_bounded,
ensure_integration_backend_with_timeout, predict_integration_backend_name,
};
use crate::openrtb::{
Banner, ConsentedProvidersSettings, Device, Format, Geo, Imp, ImpExt, ImpStoredRequest,
OpenRtbRequest, PrebidExt, PrebidImpExt, Publisher, Regs, RegsExt, RequestExt, Site, ToExt,
TrustedServerExt, User, UserExt, to_openrtb_i32,
};
use crate::platform::{
PlatformHttpRequest, PlatformPendingRequest, PlatformResponse, RuntimeServices,
};
use crate::proxy::{ProxyRequestConfig, is_host_allowed, proxy_request};
use crate::request_signing::{RequestSigner, SIGNING_VERSION, SigningParams};
use crate::settings::{IntegrationConfig, Settings};
const PREBID_INTEGRATION_ID: &str = "prebid";
const PREBID_BUNDLE_ROUTE: &str = "/integrations/prebid/bundle.js";
const PREBID_BUNDLE_CONTENT_TYPE: &str = "application/javascript; charset=utf-8";
const PREBID_BUNDLE_IMMUTABLE_CACHE_CONTROL: &str = "public, max-age=31536000, immutable";
const PREBID_BUNDLE_REVALIDATION_CACHE_CONTROL: &str =
"public, max-age=300, s-maxage=300, stale-while-revalidate=60, stale-if-error=86400";
const PREBID_BUNDLE_ERROR_CACHE_CONTROL: &str = "no-store";
const PREBID_BUNDLE_ERROR_CONTENT_TYPE: &str = "text/plain; charset=utf-8";
const PREBID_BUNDLE_NOSNIFF_HEADER: &str = "x-content-type-options";
const PREBID_BUNDLE_NOSNIFF_VALUE: &str = "nosniff";
const TRUSTED_SERVER_BIDDER: &str = "trustedServer";
const BIDDER_PARAMS_KEY: &str = "bidderParams";
const ZONE_KEY: &str = "zone";
/// Default currency for `OpenRTB` bid floors and responses.
const DEFAULT_CURRENCY: &str = "USD";
const PREBID_PUBLIC_ERROR_MESSAGE_CHARS: usize = 500;
const PREBID_ERROR_BODY_PREVIEW_CHARS: usize = 1000;
const PREBID_ERROR_BODY_PREVIEW_BYTES: usize = PREBID_ERROR_BODY_PREVIEW_CHARS * 4;
const PREBID_ERROR_JSON_MAX_DEPTH: usize = 6;
const PREBID_ERROR_JSON_KEYS: [&str; 6] =
["message", "error", "errors", "detail", "title", "reason"];
#[derive(Debug, Eq, PartialEq)]
struct BoundedPrebidErrorText {
text: String,
truncated: bool,
}
fn bounded_prebid_error_text(value: &str, max_chars: usize) -> Option<BoundedPrebidErrorText> {
let mut text = String::new();
let mut char_count = 0;
let mut pending_space = false;
let mut truncated = false;
for character in value.chars() {
if character.is_whitespace() || character.is_control() {
pending_space = !text.is_empty();
continue;
}
if pending_space {
if char_count == max_chars {
truncated = true;
break;
}
text.push(' ');
char_count += 1;
pending_space = false;
}
if char_count == max_chars {
truncated = true;
break;
}
text.push(character);
char_count += 1;
}
(!text.is_empty()).then_some(BoundedPrebidErrorText { text, truncated })
}
fn prebid_body_preview(body: &[u8]) -> Option<BoundedPrebidErrorText> {
let bounded_body = &body[..body.len().min(PREBID_ERROR_BODY_PREVIEW_BYTES)];
let mut preview = bounded_prebid_error_text(
&String::from_utf8_lossy(bounded_body),
PREBID_ERROR_BODY_PREVIEW_CHARS,
)?;
preview.truncated |= body.len() > bounded_body.len();
Some(preview)
}
fn nested_prebid_json_error_message(
value: &Json,
depth: usize,
allow_direct_string: bool,
) -> Option<&str> {
if depth > PREBID_ERROR_JSON_MAX_DEPTH {
return None;
}
match value {
Json::String(message) if allow_direct_string => {
(!message.trim().is_empty()).then_some(message.as_str())
}
Json::Array(values) => values.iter().find_map(|value| {
nested_prebid_json_error_message(value, depth + 1, allow_direct_string)
}),
Json::Object(values) => PREBID_ERROR_JSON_KEYS
.iter()
.find_map(|key| {
values
.get(*key)
.and_then(|value| nested_prebid_json_error_message(value, depth + 1, true))
})
.or_else(|| {
values
.values()
.find_map(|value| nested_prebid_json_error_message(value, depth + 1, false))
}),
_ => None,
}
}
fn prebid_json_error_message(value: &Json) -> Option<&str> {
let Json::Object(values) = value else {
return None;
};
PREBID_ERROR_JSON_KEYS.iter().find_map(|key| {
values
.get(*key)
.and_then(|value| nested_prebid_json_error_message(value, 0, true))
})
}
fn is_plain_text_content_type(content_type: Option<&str>) -> bool {
content_type.is_some_and(|value| {
value
.split(';')
.next()
.is_some_and(|mime| mime.trim().eq_ignore_ascii_case("text/plain"))
})
}
fn extract_prebid_error_message(
body: &[u8],
content_type: Option<&str>,
) -> Option<BoundedPrebidErrorText> {
let candidate = match serde_json::from_slice::<Json>(body) {
Ok(value) => prebid_json_error_message(&value)?.to_owned(),
Err(_) if is_plain_text_content_type(content_type) => {
std::str::from_utf8(body).ok()?.to_owned()
}
Err(_) => return None,
};
// Do not expose an HTML error page even if an intermediary labels it as text/plain.
if candidate.trim_start().starts_with('<') {
return None;
}
bounded_prebid_error_text(&candidate, PREBID_PUBLIC_ERROR_MESSAGE_CHARS)
}
/// CCPA/US-privacy string sent when the `Sec-GPC` header signals opt-out.
///
/// Encodes: version `1`, notice given (`Y`), user opted out (`Y`), LSPA not
/// signed (`N`). The opt-out (position 2 = `Y`) matches GPC intent. Position 3
/// (`N` = LSPA not applicable) is a conservative default that may not hold for
/// all publishers — consider making this configurable per-publisher in the future.
#[cfg(test)]
const GPC_US_PRIVACY: &str = "1YYN";
#[derive(Debug, Clone, Deserialize, Serialize, Validate)]
pub struct PrebidIntegrationConfig {
#[serde(default = "default_enabled")]
pub enabled: bool,
#[validate(url)]
pub server_url: String,
/// Prebid Server account ID, injected into the client-side bundle via
/// `window.__tsjs_prebid.accountId` so publishers don't need to configure
/// it in JavaScript.
#[serde(default)]
pub account_id: Option<String>,
#[serde(default = "default_timeout_ms")]
pub timeout_ms: u32,
#[serde(
default = "default_bidders",
deserialize_with = "crate::settings::vec_from_seq_or_map"
)]
pub bidders: Vec<String>,
#[serde(default)]
pub debug: bool,
/// Sets the `OpenRTB` `test: 1` flag on outgoing requests. When enabled,
/// bidders treat the auction as non-billable test traffic, which can
/// significantly reduce fill rates. Separate from `debug` so you can get
/// debug diagnostics without suppressing real demand.
#[serde(default)]
pub test_mode: bool,
#[serde(default)]
pub debug_query_params: Option<String>,
/// Patterns to match Prebid script URLs for serving empty JS.
/// Supports suffix matching (e.g., "/prebid.min.js" matches any path ending with that)
/// and wildcard patterns (e.g., "/static/prebid/*" matches paths under that prefix).
#[serde(
default = "default_script_patterns",
deserialize_with = "crate::settings::vec_from_seq_or_map"
)]
pub script_patterns: Vec<String>,
/// Absolute HTTPS URL of the generated external Prebid bundle.
#[serde(default)]
#[validate(custom(function = "validate_external_bundle_url"))]
pub external_bundle_url: Option<String>,
/// Optional hex SHA-256 of the exact external bundle bytes.
#[serde(default)]
#[validate(custom(function = "validate_external_bundle_sha256"))]
pub external_bundle_sha256: Option<String>,
/// Optional browser Subresource Integrity value for the first-party script.
#[serde(default)]
#[validate(custom(function = "validate_external_bundle_sri"))]
pub external_bundle_sri: Option<String>,
/// Bidders that should run client-side in the browser via native Prebid.js
/// adapters instead of being routed through the server-side auction.
///
/// These bidders are **not** absorbed into the `trustedServer` adapter and
/// remain as standalone bids in each ad unit. The corresponding Prebid.js
/// adapter modules must be statically imported in the JS bundle so they are
/// available at runtime.
///
/// This list is independent of [`bidders`](Self::bidders) — the operator
/// manages both lists explicitly.
#[serde(default, deserialize_with = "crate::settings::vec_from_seq_or_map")]
pub client_side_bidders: Vec<String>,
/// Compatibility sugar for per-bidder, per-zone param overrides.
///
/// This preserves the natural `bidder -> zone -> params` config shape for
/// the existing zone-based use case, but it is normalized into the
/// canonical [`bid_param_override_rules`](Self::bid_param_override_rules)
/// engine before runtime use.
///
/// Example in TOML:
/// ```toml
/// [integrations.prebid.bid_param_zone_overrides.kargo]
/// header = {placementId = "_s2sHeaderId"}
/// in_content = {placementId = "_s2sContentId"}
/// fixed_bottom = {placementId = "_s2sBottomId"}
/// ```
#[serde(default)]
pub bid_param_zone_overrides: HashMap<String, HashMap<String, serde_json::Map<String, Json>>>,
/// Compatibility sugar for static per-bidder parameter overrides.
///
/// These rules are normalized into the canonical
/// [`bid_param_override_rules`](Self::bid_param_override_rules) engine and
/// therefore share the same validation and precedence behavior as explicit
/// rules.
///
/// Example in TOML:
/// ```toml
/// [integrations.prebid.bid_param_overrides.bidder-name]
/// param1 = 12345
/// param2 = "value"
/// ```
#[serde(default)]
pub bid_param_overrides: HashMap<String, serde_json::Map<String, Json>>,
/// Canonical ordered bidder-param override rules.
///
/// Each rule has structured `when` matchers and a non-empty `set` object
/// that is shallow-merged into the bidder params when every matcher
/// matches. Compatibility fields such as [`bid_param_overrides`](Self::bid_param_overrides)
/// and [`bid_param_zone_overrides`](Self::bid_param_zone_overrides) are
/// normalized into the same runtime rule engine before request handling.
///
/// Example in TOML:
/// ```toml
/// [[integrations.prebid.bid_param_override_rules]]
/// when.bidder = "kargo"
/// when.zone = "header"
/// set = { placementId = "_abc" }
/// ```
#[serde(default)]
pub bid_param_override_rules: Vec<BidParamOverrideRule>,
/// How consent signals are forwarded to Prebid Server.
///
/// - `openrtb_only` — consent in `OpenRTB` body only, consent cookies stripped
/// - `cookies_only` — consent cookies forwarded, body consent fields omitted
/// - `both` — consent in both cookies and body (default)
#[serde(default)]
pub consent_forwarding: ConsentForwardingMode,
/// Strip `nurl` and `burl` from PBS bids before they reach `window.tsjs.bids`.
///
/// Set to `true` when the PBS deployment is configured to fire win/billing
/// notifications server-side (e.g. `ext.prebid.events.enabled`), so the
/// client does not double-fire them via `sendBeacon`. Default: `false`.
#[serde(default)]
pub suppress_nurl: bool,
/// Bidder seats whose `nurl` and `burl` should be stripped before they reach
/// `window.tsjs.bids`.
///
/// Use this when only specific PBS seats fire win/billing notifications
/// internally. The global [`suppress_nurl`](Self::suppress_nurl) switch still
/// suppresses every bidder when set.
#[serde(default, deserialize_with = "crate::settings::vec_from_seq_or_map")]
pub suppress_nurl_bidders: Vec<String>,
}
impl IntegrationConfig for PrebidIntegrationConfig {
fn is_enabled(&self) -> bool {
self.enabled
}
}
/// Validate enabled Prebid config using the same startup-only checks as runtime registration.
///
/// # Errors
///
/// Returns a configuration error if enabled Prebid settings fail typed parsing,
/// schema validation, or bidder-param override compilation.
pub fn validate_config_for_startup(
settings: &Settings,
) -> Result<Option<PrebidIntegrationConfig>, Report<TrustedServerError>> {
let Some(config) =
settings.integration_config::<PrebidIntegrationConfig>(PREBID_INTEGRATION_ID)?
else {
return Ok(None);
};
BidParamOverrideEngine::try_from_config(&config)?;
validate_external_bundle_config(&config, &settings.proxy.allowed_domains)?;
Ok(Some(config))
}
/// Canonical bidder-param override rule.
///
/// A rule matches against the request-time facts in [`BidParamOverrideWhen`]
/// and shallow-merges [`set`](Self::set) into the bidder params when all
/// populated matchers are equal.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BidParamOverrideRule {
/// Structured exact-match conditions for this rule.
pub when: BidParamOverrideWhen,
/// Parameters shallow-merged into bidder params when the rule matches.
/// Top-level keys in this object are inserted or replaced; nested objects
/// are replaced wholesale rather than recursed into.
pub set: serde_json::Map<String, Json>,
}
/// Structured exact-match conditions for a [`BidParamOverrideRule`].
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BidParamOverrideWhen {
/// Bidder name matcher.
#[serde(default)]
pub bidder: Option<String>,
/// Zone matcher from `mediaTypes.banner.name` propagated via
/// `trustedServer.zone`.
#[serde(default)]
pub zone: Option<String>,
}
fn default_timeout_ms() -> u32 {
1000
}
fn default_bidders() -> Vec<String> {
vec!["mocktioneer".to_string()]
}
fn default_enabled() -> bool {
true
}
/// Default suffixes that identify Prebid scripts
const PREBID_SCRIPT_SUFFIXES: &[&str] = &[
"/prebid.js",
"/prebid.min.js",
"/prebidjs.js",
"/prebidjs.min.js",
];
fn default_script_patterns() -> Vec<String> {
PREBID_SCRIPT_SUFFIXES
.iter()
.map(|&s| s.to_owned())
.collect()
}
fn validate_external_bundle_url(value: &str) -> Result<(), ValidationError> {
let url = Url::parse(value).map_err(|_| {
let mut err = ValidationError::new("invalid_external_bundle_url");
err.message = Some("external_bundle_url must be a valid absolute URL".into());
err
})?;
if url.scheme() != "https" {
let mut err = ValidationError::new("invalid_external_bundle_scheme");
err.message = Some("external_bundle_url must use https".into());
return Err(err);
}
if url.host_str().is_none() {
let mut err = ValidationError::new("missing_external_bundle_host");
err.message = Some("external_bundle_url must include a host".into());
return Err(err);
}
Ok(())
}
fn validate_external_bundle_sha256(value: &str) -> Result<(), ValidationError> {
if value.len() == 64 && value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Ok(());
}
let mut err = ValidationError::new("invalid_external_bundle_sha256");
err.message = Some("external_bundle_sha256 must be a 64-character hex SHA-256".into());
Err(err)
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ExternalBundleSriAlgorithm {
Sha256,
Sha384,
Sha512,
}
impl ExternalBundleSriAlgorithm {
fn parse(value: &str) -> Option<Self> {
match value {
"sha256" => Some(Self::Sha256),
"sha384" => Some(Self::Sha384),
"sha512" => Some(Self::Sha512),
_ => None,
}
}
fn expected_digest_len(self) -> usize {
match self {
Self::Sha256 => 32,
Self::Sha384 => 48,
Self::Sha512 => 64,
}
}
}
fn external_bundle_sri_validation_error(message: &'static str) -> ValidationError {
let mut err = ValidationError::new("invalid_external_bundle_sri");
err.message = Some(message.into());
err
}
fn parse_external_bundle_sri(value: &str) -> Result<(), ValidationError> {
let trimmed = value.trim();
if trimmed.is_empty() || trimmed != value {
return Err(external_bundle_sri_validation_error(
"external_bundle_sri must be non-empty with no surrounding whitespace",
));
}
for token in trimmed.split_ascii_whitespace() {
let Some((algorithm_raw, digest_raw)) = token.split_once('-') else {
return Err(external_bundle_sri_validation_error(
"external_bundle_sri entries must use algorithm-digest format",
));
};
let Some(algorithm) = ExternalBundleSriAlgorithm::parse(algorithm_raw) else {
return Err(external_bundle_sri_validation_error(
"external_bundle_sri must use sha256, sha384, or sha512",
));
};
if digest_raw.is_empty() {
return Err(external_bundle_sri_validation_error(
"external_bundle_sri digest must be non-empty",
));
}
let digest = BASE64_STANDARD
.decode(digest_raw)
.or_else(|_| BASE64_STANDARD_NO_PAD.decode(digest_raw))
.map_err(|_| {
external_bundle_sri_validation_error("external_bundle_sri digest must be base64")
})?;
if digest.len() != algorithm.expected_digest_len() {
return Err(external_bundle_sri_validation_error(
"external_bundle_sri digest length does not match its algorithm",
));
}
}
Ok(())
}
fn validate_external_bundle_sri(value: &str) -> Result<(), ValidationError> {
parse_external_bundle_sri(value)
}
fn validate_external_bundle_config(
config: &PrebidIntegrationConfig,
allowed_domains: &[String],
) -> Result<(), Report<TrustedServerError>> {
let url = config.external_bundle_url.as_deref().ok_or_else(|| {
Report::new(TrustedServerError::Configuration {
message: "integrations.prebid.external_bundle_url is required when prebid is enabled"
.to_string(),
})
})?;
let parsed = Url::parse(url).map_err(|_| {
Report::new(TrustedServerError::Configuration {
message: "integrations.prebid.external_bundle_url must be a valid absolute URL"
.to_string(),
})
})?;
if parsed.scheme() != "https" {
return Err(Report::new(TrustedServerError::Configuration {
message: "integrations.prebid.external_bundle_url must use https".to_string(),
}));
}
let host = parsed.host_str().ok_or_else(|| {
Report::new(TrustedServerError::Configuration {
message: "integrations.prebid.external_bundle_url must include a host".to_string(),
})
})?;
if allowed_domains.is_empty() {
return Err(Report::new(TrustedServerError::Configuration {
message:
"proxy.allowed_domains must include the external Prebid bundle host when integrations.prebid.external_bundle_url is configured"
.to_string(),
}));
}
if !allowed_domains
.iter()
.any(|pattern| is_host_allowed(host, pattern))
{
return Err(Report::new(TrustedServerError::Configuration {
message: format!(
"integrations.prebid.external_bundle_url host `{host}` is not permitted by proxy.allowed_domains"
),
}));
}
Ok(())
}
pub struct PrebidIntegration {
config: PrebidIntegrationConfig,
engine: Arc<BidParamOverrideEngine>,
}
impl PrebidIntegration {
fn try_new(config: PrebidIntegrationConfig) -> Result<Arc<Self>, Report<TrustedServerError>> {
let engine = Arc::new(BidParamOverrideEngine::try_from_config(&config)?);
Ok(Arc::new(Self { config, engine }))
}
#[cfg(test)]
fn new(config: PrebidIntegrationConfig) -> Arc<Self> {
Self::try_new(config).expect("should compile prebid bid param overrides")
}
fn auction_provider(&self) -> PrebidAuctionProvider {
PrebidAuctionProvider {
config: self.config.clone(),
bid_param_override_engine: Arc::clone(&self.engine),
}
}
fn matches_script_url(&self, attr_value: &str) -> bool {
let trimmed = attr_value.trim();
let without_query = trimmed.split(['?', '#']).next().unwrap_or(trimmed);
if self.matches_script_pattern(without_query) {
return true;
}
if !without_query.starts_with('/')
&& !without_query.starts_with("//")
&& !without_query.contains("://")
{
let with_slash = format!("/{without_query}");
if self.matches_script_pattern(&with_slash) {
return true;
}
}
let parsed = if without_query.starts_with("//") {
ParsedUrl::parse(&format!("https:{without_query}"))
} else {
ParsedUrl::parse(without_query)
};
parsed
.ok()
.is_some_and(|url| self.matches_script_pattern(url.path()))
}
fn matches_script_pattern(&self, path: &str) -> bool {
// Normalize path to lowercase for case-insensitive matching
let path_lower = path.to_ascii_lowercase();
// Check if path matches any configured pattern
for pattern in &self.config.script_patterns {
let pattern_lower = pattern.to_ascii_lowercase();
// Check for wildcard patterns: /* or {*name}
if pattern_lower.ends_with("/*") || pattern_lower.contains("{*") {
// Extract prefix before the wildcard
let prefix = if pattern_lower.ends_with("/*") {
&pattern_lower[..pattern_lower.len() - 1] // Remove trailing *
} else {
// Find {* and extract prefix before it
pattern_lower.split("{*").next().unwrap_or("")
};
if path_lower.starts_with(prefix) {
// Check if it ends with a known Prebid script suffix
if PREBID_SCRIPT_SUFFIXES
.iter()
.any(|suffix| path_lower.ends_with(suffix))
{
return true;
}
}
} else {
// Exact match or suffix match
if path_lower.ends_with(&pattern_lower) {
return true;
}
}
}
false
}
fn handle_script_handler(
&self,
) -> Result<http::Response<EdgeBody>, Report<TrustedServerError>> {
let body = "// Script overridden by Trusted Server\n";
http::Response::builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, PREBID_BUNDLE_CONTENT_TYPE)
.header(header::CACHE_CONTROL, "public, max-age=31536000")
.body(EdgeBody::from(body))
.change_context(TrustedServerError::Prebid {
message: "Failed to build Prebid script handler response".to_string(),
})
}
fn external_bundle_script_src(&self) -> String {
match self.config.external_bundle_sha256.as_deref() {
Some(sha256) => format!("{PREBID_BUNDLE_ROUTE}?v={sha256}"),
None => PREBID_BUNDLE_ROUTE.to_string(),
}
}
fn external_bundle_script_tag(&self) -> String {
let src = self.external_bundle_script_src();
let integrity = self
.config
.external_bundle_sri
.as_deref()
.map(|value| format!(" integrity=\"{}\"", escape_html_attr(value)))
.unwrap_or_default();
format!("<script src=\"{src}\"{integrity} defer></script>")
}
fn is_managed_external(&self) -> bool {
self.config.external_bundle_url.is_some()
}
fn external_bundle_request_cache_mode(
&self,
req: &http::Request<EdgeBody>,
) -> Result<Option<ExternalBundleCacheMode>, Report<TrustedServerError>> {
let versions = req
.uri()
.query()
.map(|query| {
url::form_urlencoded::parse(query.as_bytes())
.filter(|(key, _)| key == "v")
.map(|(_, value)| value.into_owned())
.collect::<Vec<_>>()
})
.unwrap_or_default();
if versions.len() > 1 {
return Ok(None);
}
let requested_version = versions.first().map(String::as_str);
match (
self.config.external_bundle_sha256.as_deref(),
requested_version,
) {
(None, Some(_)) => Ok(None),
(Some(expected), Some(actual)) if expected != actual => Ok(None),
(Some(_), Some(_)) => Ok(Some(ExternalBundleCacheMode::Immutable)),
_ => Ok(Some(ExternalBundleCacheMode::Revalidate)),
}
}
fn apply_external_bundle_headers(
&self,
response: &mut http::Response<EdgeBody>,
mode: ExternalBundleCacheMode,
) {
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static(PREBID_BUNDLE_CONTENT_TYPE),
);
response.headers_mut().insert(
header::HeaderName::from_static(PREBID_BUNDLE_NOSNIFF_HEADER),
HeaderValue::from_static(PREBID_BUNDLE_NOSNIFF_VALUE),
);
match mode {
ExternalBundleCacheMode::Immutable => {
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static(PREBID_BUNDLE_IMMUTABLE_CACHE_CONTROL),
);
if let Some(sha256) = self.config.external_bundle_sha256.as_deref() {
response.headers_mut().insert(
header::ETAG,
HeaderValue::from_str(&format!("\"sha256:{sha256}\""))
.expect("should build etag header"),
);
}
}
ExternalBundleCacheMode::Revalidate => {
response.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static(PREBID_BUNDLE_REVALIDATION_CACHE_CONTROL),
);
if let Some(sha256) = self.config.external_bundle_sha256.as_deref() {
response.headers_mut().insert(
header::ETAG,
HeaderValue::from_str(&format!("\"sha256:{sha256}\""))
.expect("should build etag header"),
);
}
}
}
}
fn sanitize_external_bundle_response(
&self,
response: http::Response<EdgeBody>,
mode: ExternalBundleCacheMode,
) -> http::Response<EdgeBody> {
let status = response.status();
let content_encoding = response.headers().get(header::CONTENT_ENCODING).cloned();
let body = response.into_body();
let mut sanitized = http::Response::builder()
.status(status)
.body(body)
.expect("should build sanitized response");
if let Some(content_encoding) = content_encoding {
sanitized
.headers_mut()
.insert(header::CONTENT_ENCODING, content_encoding);
}
if status == StatusCode::OK {
self.apply_external_bundle_headers(&mut sanitized, mode);
} else {
sanitized.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static(PREBID_BUNDLE_ERROR_CONTENT_TYPE),
);
sanitized.headers_mut().insert(
header::CACHE_CONTROL,
HeaderValue::from_static(PREBID_BUNDLE_ERROR_CACHE_CONTROL),
);
sanitized.headers_mut().insert(
header::HeaderName::from_static(PREBID_BUNDLE_NOSNIFF_HEADER),
HeaderValue::from_static(PREBID_BUNDLE_NOSNIFF_VALUE),
);
}
sanitized
}
async fn handle_external_bundle(
&self,
settings: &Settings,
services: &RuntimeServices,
req: http::Request<EdgeBody>,
) -> Result<http::Response<EdgeBody>, Report<TrustedServerError>> {
let Some(cache_mode) = self.external_bundle_request_cache_mode(&req)? else {
return Ok(http::Response::builder()
.status(StatusCode::NOT_FOUND)
.body(EdgeBody::from("Not Found"))
.expect("should build not found response"));
};
let target_url = self.config.external_bundle_url.as_deref().ok_or_else(|| {
Report::new(TrustedServerError::Configuration {
message:
"integrations.prebid.external_bundle_url is required when prebid is enabled"
.to_string(),
})
})?;
let proxy_config = ProxyRequestConfig::new(target_url)
.without_ec_id()
.without_forward_headers()
.with_streaming()
.with_allowed_domains(&settings.proxy.allowed_domains)
.with_https_only();
let response = proxy_request(settings, req, proxy_config, services).await?;
Ok(self.sanitize_external_bundle_response(response, cache_mode))
}
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
enum ExternalBundleCacheMode {
Immutable,
Revalidate,
}
fn escape_html_attr(value: &str) -> String {
value
.replace('&', "&")
.replace('"', """)
.replace('<', "<")
.replace('>', ">")
}
fn build(
settings: &Settings,
) -> Result<Option<Arc<PrebidIntegration>>, Report<TrustedServerError>> {
let Some(config) =
settings.integration_config::<PrebidIntegrationConfig>(PREBID_INTEGRATION_ID)?
else {
return Ok(None);
};
validate_external_bundle_config(&config, &settings.proxy.allowed_domains)?;
// Warn about bidders that appear in both lists — this is likely a config
// mistake. A bidder should be in either `bidders` (server-side) or
// `client_side_bidders` (browser-side), not both.
for bidder in &config.client_side_bidders {
if config.bidders.iter().any(|b| b == bidder) {
log::warn!(
"prebid: bidder \"{}\" is in both bidders and client_side_bidders — \
it will run server-side AND be left for client-side, which is likely unintended",
bidder
);
}
}
Ok(Some(PrebidIntegration::try_new(config)?))
}
/// Register the Prebid integration when enabled.
///
/// # Errors
///
/// Returns an error when the Prebid integration is enabled with invalid
/// configuration.
pub fn register(
settings: &Settings,
) -> Result<Option<IntegrationRegistration>, Report<TrustedServerError>> {
let Some(integration) = build(settings)? else {
return Ok(None);
};
Ok(Some(
IntegrationRegistration::builder(PREBID_INTEGRATION_ID)
.with_proxy(integration.clone())
.with_attribute_rewriter(integration.clone())
.with_head_injector(integration)
.with_deferred_js()
.build(),
))
}
#[async_trait(?Send)]
impl IntegrationProxy for PrebidIntegration {
fn integration_name(&self) -> &'static str {
PREBID_INTEGRATION_ID
}
fn routes(&self) -> Vec<IntegrationEndpoint> {
let mut routes = vec![];
routes.push(self.get("/bundle.js"));
// Register routes for script removal patterns
// Patterns can be exact paths (e.g., "/prebid.min.js") or use matchit wildcards
// (e.g., "/static/prebid/{*rest}")
for pattern in &self.config.script_patterns {
// Intentional leak: runs once at startup and patterns are small.
// `IntegrationEndpoint` requires `&'static str`.
let static_path: &'static str = Box::leak(pattern.clone().into_boxed_str());
routes.push(IntegrationEndpoint::get(static_path));
}
routes
}
async fn handle(
&self,
settings: &Settings,
services: &RuntimeServices,
req: http::Request<EdgeBody>,
) -> Result<http::Response<EdgeBody>, Report<TrustedServerError>> {
let path = req.uri().path().to_string();
let method = req.method().clone();
match method {
Method::GET if self.is_managed_external() && path == PREBID_BUNDLE_ROUTE => {
self.handle_external_bundle(settings, services, req).await
}
// Serve empty JS for matching script patterns
Method::GET if self.matches_script_pattern(&path) => self.handle_script_handler(),
_ => http::Response::builder()
.status(StatusCode::NOT_FOUND)
.body(EdgeBody::from("Not Found"))
.change_context(TrustedServerError::Prebid {
message: "Failed to build Prebid not found response".to_string(),
}),
}
}
}
impl IntegrationAttributeRewriter for PrebidIntegration {
fn integration_id(&self) -> &'static str {
PREBID_INTEGRATION_ID
}
fn handles_attribute(&self, attribute: &str) -> bool {
matches!(attribute, "src" | "href")
}
fn rewrite(
&self,
_attr_name: &str,
attr_value: &str,
_ctx: &IntegrationAttributeContext<'_>,
) -> AttributeRewriteAction {
if self.matches_script_url(attr_value) {
AttributeRewriteAction::remove_element()
} else {
AttributeRewriteAction::keep()
}
}
}
impl IntegrationHeadInjector for PrebidIntegration {
fn integration_id(&self) -> &'static str {
PREBID_INTEGRATION_ID
}
fn head_inserts(&self, _ctx: &IntegrationHtmlContext<'_>) -> Vec<String> {
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct InjectedPrebidClientConfig<'a> {
account_id: &'a str,