-
Notifications
You must be signed in to change notification settings - Fork 742
/
auction.go
2007 lines (1744 loc) · 63.6 KB
/
auction.go
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
package openrtb2
import (
"compress/gzip"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"time"
"github.com/buger/jsonparser"
"github.com/gofrs/uuid"
"github.com/golang/glog"
"github.com/julienschmidt/httprouter"
gpplib "github.com/prebid/go-gpp"
"github.com/prebid/go-gpp/constants"
"github.com/prebid/openrtb/v20/openrtb2"
"github.com/prebid/openrtb/v20/openrtb3"
"github.com/prebid/prebid-server/v3/bidadjustment"
"github.com/prebid/prebid-server/v3/hooks"
"github.com/prebid/prebid-server/v3/ortb"
"github.com/prebid/prebid-server/v3/privacy"
"github.com/prebid/prebid-server/v3/privacysandbox"
"github.com/prebid/prebid-server/v3/schain"
"golang.org/x/net/publicsuffix"
jsonpatch "gopkg.in/evanphx/json-patch.v4"
accountService "github.com/prebid/prebid-server/v3/account"
"github.com/prebid/prebid-server/v3/analytics"
"github.com/prebid/prebid-server/v3/config"
"github.com/prebid/prebid-server/v3/currency"
"github.com/prebid/prebid-server/v3/errortypes"
"github.com/prebid/prebid-server/v3/exchange"
"github.com/prebid/prebid-server/v3/gdpr"
"github.com/prebid/prebid-server/v3/hooks/hookexecution"
"github.com/prebid/prebid-server/v3/metrics"
"github.com/prebid/prebid-server/v3/openrtb_ext"
"github.com/prebid/prebid-server/v3/prebid_cache_client"
"github.com/prebid/prebid-server/v3/privacy/ccpa"
"github.com/prebid/prebid-server/v3/privacy/lmt"
"github.com/prebid/prebid-server/v3/stored_requests"
"github.com/prebid/prebid-server/v3/stored_requests/backends/empty_fetcher"
"github.com/prebid/prebid-server/v3/stored_responses"
"github.com/prebid/prebid-server/v3/usersync"
"github.com/prebid/prebid-server/v3/util/httputil"
"github.com/prebid/prebid-server/v3/util/iputil"
"github.com/prebid/prebid-server/v3/util/jsonutil"
"github.com/prebid/prebid-server/v3/util/uuidutil"
"github.com/prebid/prebid-server/v3/version"
)
const ampChannel = "amp"
const appChannel = "app"
const secCookieDeprecation = "Sec-Cookie-Deprecation"
const secBrowsingTopics = "Sec-Browsing-Topics"
const observeBrowsingTopics = "Observe-Browsing-Topics"
const observeBrowsingTopicsValue = "?1"
var (
dntKey string = http.CanonicalHeaderKey("DNT")
secGPCKey string = http.CanonicalHeaderKey("Sec-GPC")
dntDisabled int8 = 0
dntEnabled int8 = 1
notAmp int8 = 0
)
var accountIdSearchPath = [...]struct {
isApp bool
isDOOH bool
key []string
}{
{true, false, []string{"app", "publisher", "ext", openrtb_ext.PrebidExtKey, "parentAccount"}},
{true, false, []string{"app", "publisher", "id"}},
{false, false, []string{"site", "publisher", "ext", openrtb_ext.PrebidExtKey, "parentAccount"}},
{false, false, []string{"site", "publisher", "id"}},
{false, true, []string{"dooh", "publisher", "ext", openrtb_ext.PrebidExtKey, "parentAccount"}},
{false, true, []string{"dooh", "publisher", "id"}},
}
func NewEndpoint(
uuidGenerator uuidutil.UUIDGenerator,
ex exchange.Exchange,
requestValidator ortb.RequestValidator,
requestsById stored_requests.Fetcher,
accounts stored_requests.AccountFetcher,
cfg *config.Configuration,
metricsEngine metrics.MetricsEngine,
analyticsRunner analytics.Runner,
disabledBidders map[string]string,
defReqJSON []byte,
bidderMap map[string]openrtb_ext.BidderName,
storedRespFetcher stored_requests.Fetcher,
hookExecutionPlanBuilder hooks.ExecutionPlanBuilder,
tmaxAdjustments *exchange.TmaxAdjustmentsPreprocessed,
) (httprouter.Handle, error) {
if ex == nil || requestValidator == nil || requestsById == nil || accounts == nil || cfg == nil || metricsEngine == nil {
return nil, errors.New("NewEndpoint requires non-nil arguments.")
}
defRequest := len(defReqJSON) > 0
ipValidator := iputil.PublicNetworkIPValidator{
IPv4PrivateNetworks: cfg.RequestValidation.IPv4PrivateNetworksParsed,
IPv6PrivateNetworks: cfg.RequestValidation.IPv6PrivateNetworksParsed,
}
return httprouter.Handle((&endpointDeps{
uuidGenerator,
ex,
requestValidator,
requestsById,
empty_fetcher.EmptyFetcher{},
accounts,
cfg,
metricsEngine,
analyticsRunner,
disabledBidders,
defRequest,
defReqJSON,
bidderMap,
nil,
nil,
ipValidator,
storedRespFetcher,
hookExecutionPlanBuilder,
tmaxAdjustments,
openrtb_ext.NormalizeBidderName}).Auction), nil
}
type endpointDeps struct {
uuidGenerator uuidutil.UUIDGenerator
ex exchange.Exchange
requestValidator ortb.RequestValidator
storedReqFetcher stored_requests.Fetcher
videoFetcher stored_requests.Fetcher
accounts stored_requests.AccountFetcher
cfg *config.Configuration
metricsEngine metrics.MetricsEngine
analytics analytics.Runner
disabledBidders map[string]string
defaultRequest bool
defReqJSON []byte
bidderMap map[string]openrtb_ext.BidderName
cache prebid_cache_client.Client
debugLogRegexp *regexp.Regexp
privateNetworkIPValidator iputil.IPValidator
storedRespFetcher stored_requests.Fetcher
hookExecutionPlanBuilder hooks.ExecutionPlanBuilder
tmaxAdjustments *exchange.TmaxAdjustmentsPreprocessed
normalizeBidderName openrtb_ext.BidderNameNormalizer
}
func (deps *endpointDeps) Auction(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Prebid Server interprets request.tmax to be the maximum amount of time that a caller is willing
// to wait for bids. However, tmax may be defined in the Stored Request data.
//
// If so, then the trip to the backend might use a significant amount of this time.
// We can respect timeouts more accurately if we note the *real* start time, and use it
// to compute the auction timeout.
start := time.Now()
hookExecutor := hookexecution.NewHookExecutor(deps.hookExecutionPlanBuilder, hookexecution.EndpointAuction, deps.metricsEngine)
ao := analytics.AuctionObject{
Status: http.StatusOK,
Errors: make([]error, 0),
StartTime: start,
}
labels := metrics.Labels{
Source: metrics.DemandUnknown,
RType: metrics.ReqTypeORTB2Web,
PubID: metrics.PublisherUnknown,
CookieFlag: metrics.CookieFlagUnknown,
RequestStatus: metrics.RequestStatusOK,
}
activityControl := privacy.ActivityControl{}
defer func() {
deps.metricsEngine.RecordRequest(labels)
deps.metricsEngine.RecordRequestTime(labels, time.Since(start))
deps.analytics.LogAuctionObject(&ao, activityControl)
}()
w.Header().Set("X-Prebid", version.BuildXPrebidHeader(version.Ver))
setBrowsingTopicsHeader(w, r)
req, impExtInfoMap, storedAuctionResponses, storedBidResponses, bidderImpReplaceImp, account, errL := deps.parseRequest(r, &labels, hookExecutor)
if errortypes.ContainsFatalError(errL) && writeError(errL, w, &labels) {
return
}
if rejectErr := hookexecution.FindFirstRejectOrNil(errL); rejectErr != nil {
ao.RequestWrapper = req
labels, ao = rejectAuctionRequest(*rejectErr, w, hookExecutor, req.BidRequest, account, labels, ao)
return
}
tcf2Config := gdpr.NewTCF2Config(deps.cfg.GDPR.TCF2, account.GDPR)
activityControl = privacy.NewActivityControl(&account.Privacy)
hookExecutor.SetActivityControl(activityControl)
hookExecutor.SetAccount(account)
ctx := context.Background()
timeout := deps.cfg.AuctionTimeouts.LimitAuctionTimeout(time.Duration(req.TMax) * time.Millisecond)
if timeout > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, start.Add(timeout))
defer cancel()
}
// Read Usersyncs/Cookie
decoder := usersync.Base64Decoder{}
usersyncs := usersync.ReadCookie(r, decoder, &deps.cfg.HostCookie)
usersync.SyncHostCookie(r, usersyncs, &deps.cfg.HostCookie)
if req.Site != nil {
if usersyncs.HasAnyLiveSyncs() {
labels.CookieFlag = metrics.CookieFlagYes
} else {
labels.CookieFlag = metrics.CookieFlagNo
}
}
// Set Integration Information
err := deps.setIntegrationType(req, account)
if err != nil {
errL = append(errL, err)
writeError(errL, w, &labels)
return
}
secGPC := r.Header.Get("Sec-GPC")
warnings := errortypes.WarningOnly(errL)
auctionRequest := &exchange.AuctionRequest{
BidRequestWrapper: req,
Account: *account,
UserSyncs: usersyncs,
RequestType: labels.RType,
StartTime: start,
LegacyLabels: labels,
Warnings: warnings,
GlobalPrivacyControlHeader: secGPC,
ImpExtInfoMap: impExtInfoMap,
StoredAuctionResponses: storedAuctionResponses,
StoredBidResponses: storedBidResponses,
BidderImpReplaceImpID: bidderImpReplaceImp,
PubID: labels.PubID,
HookExecutor: hookExecutor,
TCF2Config: tcf2Config,
Activities: activityControl,
TmaxAdjustments: deps.tmaxAdjustments,
}
auctionResponse, err := deps.ex.HoldAuction(ctx, auctionRequest, nil)
defer func() {
if !auctionRequest.BidderResponseStartTime.IsZero() {
deps.metricsEngine.RecordOverheadTime(metrics.MakeAuctionResponse, time.Since(auctionRequest.BidderResponseStartTime))
}
}()
ao.RequestWrapper = req
ao.Account = account
var response *openrtb2.BidResponse
if auctionResponse != nil {
response = auctionResponse.BidResponse
}
ao.Response = response
ao.SeatNonBid = auctionResponse.GetSeatNonBid()
rejectErr, isRejectErr := hookexecution.CastRejectErr(err)
if err != nil && !isRejectErr {
if errortypes.ReadCode(err) == errortypes.BadInputErrorCode {
writeError([]error{err}, w, &labels)
return
}
labels.RequestStatus = metrics.RequestStatusErr
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Critical error while running the auction: %v", err)
glog.Errorf("/openrtb2/auction Critical error: %v", err)
ao.Status = http.StatusInternalServerError
ao.Errors = append(ao.Errors, err)
return
} else if isRejectErr {
labels, ao = rejectAuctionRequest(*rejectErr, w, hookExecutor, req.BidRequest, account, labels, ao)
return
}
err = setSeatNonBidRaw(req, auctionResponse)
if err != nil {
glog.Errorf("Error setting seat non-bid: %v", err)
}
labels, ao = sendAuctionResponse(w, hookExecutor, response, req.BidRequest, account, labels, ao)
}
// setSeatNonBidRaw is transitional function for setting SeatNonBid inside bidResponse.Ext
// Because,
// 1. today exchange.HoldAuction prepares and marshals some piece of response.Ext which is then used by auction.go, amp_auction.go and video_auction.go
// 2. As per discussion with Prebid Team we are planning to move away from - HoldAuction building openrtb2.BidResponse. instead respective auction modules will build this object
// 3. So, we will need this method to do first, unmarshalling of response.Ext
func setSeatNonBidRaw(request *openrtb_ext.RequestWrapper, auctionResponse *exchange.AuctionResponse) error {
if auctionResponse == nil || auctionResponse.BidResponse == nil {
return nil
}
// unmarshalling is required here, until we are moving away from bidResponse.Ext, which is populated
// by HoldAuction
response := auctionResponse.BidResponse
respExt := &openrtb_ext.ExtBidResponse{}
if err := jsonutil.Unmarshal(response.Ext, &respExt); err != nil {
return err
}
if setSeatNonBid(respExt, request, auctionResponse) {
if respExtJson, err := jsonutil.Marshal(respExt); err == nil {
response.Ext = respExtJson
return nil
} else {
return err
}
}
return nil
}
func rejectAuctionRequest(
rejectErr hookexecution.RejectError,
w http.ResponseWriter,
hookExecutor hookexecution.HookStageExecutor,
request *openrtb2.BidRequest,
account *config.Account,
labels metrics.Labels,
ao analytics.AuctionObject,
) (metrics.Labels, analytics.AuctionObject) {
response := &openrtb2.BidResponse{NBR: openrtb3.NoBidReason(rejectErr.NBR).Ptr()}
if request != nil {
response.ID = request.ID
}
ao.Response = response
ao.Errors = append(ao.Errors, rejectErr)
return sendAuctionResponse(w, hookExecutor, response, request, account, labels, ao)
}
func sendAuctionResponse(
w http.ResponseWriter,
hookExecutor hookexecution.HookStageExecutor,
response *openrtb2.BidResponse,
request *openrtb2.BidRequest,
account *config.Account,
labels metrics.Labels,
ao analytics.AuctionObject,
) (metrics.Labels, analytics.AuctionObject) {
hookExecutor.ExecuteAuctionResponseStage(response)
if response != nil {
stageOutcomes := hookExecutor.GetOutcomes()
ao.HookExecutionOutcome = stageOutcomes
ext, warns, err := hookexecution.EnrichExtBidResponse(response.Ext, stageOutcomes, request, account)
if err != nil {
err = fmt.Errorf("Failed to enrich Bid Response with hook debug information: %s", err)
glog.Errorf(err.Error())
ao.Errors = append(ao.Errors, err)
} else {
response.Ext = ext
}
if len(warns) > 0 {
ao.Errors = append(ao.Errors, warns...)
}
}
// Fixes #231
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
w.Header().Set("Content-Type", "application/json")
// If an error happens when encoding the response, there isn't much we can do.
// If we've sent _any_ bytes, then Go would have sent the 200 status code first.
// That status code can't be un-sent... so the best we can do is log the error.
if err := enc.Encode(response); err != nil {
labels.RequestStatus = metrics.RequestStatusNetworkErr
ao.Errors = append(ao.Errors, fmt.Errorf("/openrtb2/auction Failed to send response: %v", err))
}
return labels, ao
}
// setBrowsingTopicsHeader always set the Observe-Browsing-Topics header to a value of ?1 if the Sec-Browsing-Topics is present in request
func setBrowsingTopicsHeader(w http.ResponseWriter, r *http.Request) {
if value := r.Header.Get(secBrowsingTopics); value != "" {
w.Header().Set(observeBrowsingTopics, observeBrowsingTopicsValue)
}
}
// parseRequest turns the HTTP request into an OpenRTB request. This is guaranteed to return:
//
// - A context which times out appropriately, given the request.
// - A cancellation function which should be called if the auction finishes early.
//
// If the errors list is empty, then the returned request will be valid according to the OpenRTB 2.5 spec.
// In case of "strong recommendations" in the spec, it tends to be restrictive. If a better workaround is
// possible, it will return errors with messages that suggest improvements.
//
// If the errors list has at least one element, then no guarantees are made about the returned request.
func (deps *endpointDeps) parseRequest(httpRequest *http.Request, labels *metrics.Labels, hookExecutor hookexecution.HookStageExecutor) (req *openrtb_ext.RequestWrapper, impExtInfoMap map[string]exchange.ImpExtInfo, storedAuctionResponses stored_responses.ImpsWithBidResponses, storedBidResponses stored_responses.ImpBidderStoredResp, bidderImpReplaceImpId stored_responses.BidderImpReplaceImpID, account *config.Account, errs []error) {
errs = nil
var err error
var errL []error
var r io.ReadCloser = httpRequest.Body
reqContentEncoding := httputil.ContentEncoding(httpRequest.Header.Get("Content-Encoding"))
if reqContentEncoding != "" {
if !deps.cfg.Compression.Request.IsSupported(reqContentEncoding) {
errs = []error{fmt.Errorf("Content-Encoding of type %s is not supported", reqContentEncoding)}
return
} else {
r, err = getCompressionEnabledReader(httpRequest.Body, reqContentEncoding)
if err != nil {
errs = []error{err}
return
}
}
}
defer r.Close()
limitedReqReader := &io.LimitedReader{
R: r,
N: deps.cfg.MaxRequestSize,
}
requestJson, err := io.ReadAll(limitedReqReader)
if err != nil {
errs = []error{err}
return
}
if limitedReqReader.N <= 0 {
// Limited Reader returns 0 if the request was exactly at the max size or over the limit.
// This is because it only reads up to N bytes. To check if the request was too large,
// we need to look at the next byte of its underlying reader, limitedReader.R.
if _, err := limitedReqReader.R.Read(make([]byte, 1)); err != io.EOF {
// Discard the rest of the request body so that the connection can be reused.
io.Copy(io.Discard, httpRequest.Body)
errs = []error{fmt.Errorf("request size exceeded max size of %d bytes.", deps.cfg.MaxRequestSize)}
return
}
}
req = &openrtb_ext.RequestWrapper{}
req.BidRequest = &openrtb2.BidRequest{}
requestJson, rejectErr := hookExecutor.ExecuteEntrypointStage(httpRequest, requestJson)
if rejectErr != nil {
errs = []error{rejectErr}
if err = jsonutil.UnmarshalValid(requestJson, req.BidRequest); err != nil {
glog.Errorf("Failed to unmarshal BidRequest during entrypoint rejection: %s", err)
}
return
}
timeout := parseTimeout(requestJson, time.Duration(deps.cfg.StoredRequestsTimeout)*time.Millisecond)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
impInfo, errs := parseImpInfo(requestJson)
if len(errs) > 0 {
return nil, nil, nil, nil, nil, nil, errs
}
storedBidRequestId, hasStoredBidRequest, storedRequests, storedImps, errs := deps.getStoredRequests(ctx, requestJson, impInfo)
if len(errs) > 0 {
return
}
accountId, isAppReq, isDOOHReq, errs := getAccountIdFromRawRequest(hasStoredBidRequest, storedRequests[storedBidRequestId], requestJson)
// fill labels here in order to pass correct metrics in case of errors
if isAppReq {
labels.Source = metrics.DemandApp
labels.RType = metrics.ReqTypeORTB2App
labels.PubID = accountId
} else if isDOOHReq {
labels.Source = metrics.DemandDOOH
labels.RType = metrics.ReqTypeORTB2DOOH
labels.PubID = accountId
} else { // is Site request
labels.Source = metrics.DemandWeb
labels.PubID = accountId
}
if errs != nil {
return
}
// Look up account
account, errs = accountService.GetAccount(ctx, deps.cfg, deps.accounts, accountId, deps.metricsEngine)
if len(errs) > 0 {
return
}
hookExecutor.SetAccount(account)
requestJson, rejectErr = hookExecutor.ExecuteRawAuctionStage(requestJson)
if rejectErr != nil {
errs = []error{rejectErr}
if err = jsonutil.UnmarshalValid(requestJson, req.BidRequest); err != nil {
glog.Errorf("Failed to unmarshal BidRequest during raw auction stage rejection: %s", err)
}
return
}
// retrieve storedRequests and storedImps once more in case stored data was changed by the raw auction hook
if hasPayloadUpdatesAt(hooks.StageRawAuctionRequest.String(), hookExecutor.GetOutcomes()) {
impInfo, errs = parseImpInfo(requestJson)
if len(errs) > 0 {
return nil, nil, nil, nil, nil, nil, errs
}
storedBidRequestId, hasStoredBidRequest, storedRequests, storedImps, errs = deps.getStoredRequests(ctx, requestJson, impInfo)
if len(errs) > 0 {
return
}
}
// Fetch the Stored Request data and merge it into the HTTP request.
if requestJson, impExtInfoMap, errs = deps.processStoredRequests(requestJson, impInfo, storedRequests, storedImps, storedBidRequestId, hasStoredBidRequest); len(errs) > 0 {
return
}
if err := jsonutil.UnmarshalValid(requestJson, req.BidRequest); err != nil {
errs = []error{err}
return
}
// normalize to openrtb 2.6
if err := openrtb_ext.ConvertUpTo26(req); err != nil {
errs = []error{err}
return
}
if err := mergeBidderParams(req); err != nil {
errs = []error{err}
return
}
// Populate any "missing" OpenRTB fields with info from other sources, (e.g. HTTP request headers).
if errsL := deps.setFieldsImplicitly(httpRequest, req, account); len(errsL) > 0 {
errs = append(errs, errsL...)
}
if err := ortb.SetDefaults(req); err != nil {
errs = []error{err}
return
}
if err := processInterstitials(req); err != nil {
errs = []error{err}
return
}
lmt.ModifyForIOS(req.BidRequest)
//Stored auction responses should be processed after stored requests due to possible impression modification
storedAuctionResponses, storedBidResponses, bidderImpReplaceImpId, errL = stored_responses.ProcessStoredResponses(ctx, req, deps.storedRespFetcher)
if len(errL) > 0 {
errs = append(errs, errL...)
return nil, nil, nil, nil, nil, nil, errs
}
hasStoredAuctionResponses := len(storedAuctionResponses) > 0
errL = deps.validateRequest(account, httpRequest, req, false, hasStoredAuctionResponses, storedBidResponses, hasStoredBidRequest)
if len(errL) > 0 {
errs = append(errs, errL...)
}
return
}
func getCompressionEnabledReader(body io.ReadCloser, contentEncoding httputil.ContentEncoding) (io.ReadCloser, error) {
switch contentEncoding {
case httputil.ContentEncodingGZIP:
return gzip.NewReader(body)
default:
return nil, fmt.Errorf("unsupported compression type '%s'", contentEncoding)
}
}
// hasPayloadUpdatesAt checks if there are any successful payload updates at given stage
func hasPayloadUpdatesAt(stageName string, outcomes []hookexecution.StageOutcome) bool {
for _, outcome := range outcomes {
if stageName != outcome.Stage {
continue
}
for _, group := range outcome.Groups {
for _, invocationResult := range group.InvocationResults {
if invocationResult.Status == hookexecution.StatusSuccess &&
invocationResult.Action == hookexecution.ActionUpdate {
return true
}
}
}
}
return false
}
// parseTimeout returns parses tmax from the requestJson, or returns the default if it doesn't exist.
//
// requestJson should be the content of the POST body.
//
// If the request defines tmax explicitly, then this will return that duration in milliseconds.
// If not, it will return the default timeout.
func parseTimeout(requestJson []byte, defaultTimeout time.Duration) time.Duration {
if tmax, dataType, _, err := jsonparser.Get(requestJson, "tmax"); dataType != jsonparser.NotExist && err == nil {
if tmaxInt, err := strconv.Atoi(string(tmax)); err == nil && tmaxInt > 0 {
return time.Duration(tmaxInt) * time.Millisecond
}
}
return defaultTimeout
}
// mergeBidderParams merges bidder parameters in req.ext down to the imp[].ext level, with
// priority given to imp[].ext in case of a conflict. No validation of bidder parameters or
// of the ext json is performed. Unmarshal errors are not expected since the ext json was
// validated during the bid request unmarshal.
func mergeBidderParams(req *openrtb_ext.RequestWrapper) error {
reqExt, err := req.GetRequestExt()
if err != nil {
return nil
}
prebid := reqExt.GetPrebid()
if prebid == nil {
return nil
}
bidderParamsJson := prebid.BidderParams
if len(bidderParamsJson) == 0 {
return nil
}
bidderParams := map[string]map[string]json.RawMessage{}
if err := jsonutil.Unmarshal(bidderParamsJson, &bidderParams); err != nil {
return nil
}
for i, imp := range req.GetImp() {
impExt, err := imp.GetImpExt()
if err != nil {
continue
}
// merges bidder parameters passed at req.ext level with imp[].ext.BIDDER level
if err := mergeBidderParamsImpExt(impExt, bidderParams); err != nil {
return fmt.Errorf("error processing bidder parameters for imp[%d]: %s", i, err.Error())
}
// merges bidder parameters passed at req.ext level with imp[].ext.prebid.bidder.BIDDER level
if err := mergeBidderParamsImpExtPrebid(impExt, bidderParams); err != nil {
return fmt.Errorf("error processing bidder parameters for imp[%d]: %s", i, err.Error())
}
}
return nil
}
// mergeBidderParamsImpExt merges bidder parameters in req.ext down to the imp[].ext.BIDDER
// level, giving priority to imp[].ext.BIDDER in case of a conflict. Unmarshal errors are not
// expected since the ext json was validated during the bid request unmarshal.
func mergeBidderParamsImpExt(impExt *openrtb_ext.ImpExt, reqExtParams map[string]map[string]json.RawMessage) error {
extMap := impExt.GetExt()
extMapModified := false
for bidder, params := range reqExtParams {
if !openrtb_ext.IsPotentialBidder(bidder) {
continue
}
impExtBidder, impExtBidderExists := extMap[bidder]
if !impExtBidderExists || impExtBidder == nil {
continue
}
impExtBidderMap := map[string]json.RawMessage{}
if len(impExtBidder) > 0 {
if err := jsonutil.Unmarshal(impExtBidder, &impExtBidderMap); err != nil {
continue
}
}
modified := false
for key, value := range params {
if _, present := impExtBidderMap[key]; !present {
impExtBidderMap[key] = value
modified = true
}
}
if modified {
impExtBidderJson, err := jsonutil.Marshal(impExtBidderMap)
if err != nil {
return fmt.Errorf("error marshalling ext.BIDDER: %s", err.Error())
}
extMap[bidder] = impExtBidderJson
extMapModified = true
}
}
if extMapModified {
impExt.SetExt(extMap)
}
return nil
}
// mergeBidderParamsImpExtPrebid merges bidder parameters in req.ext down to the imp[].ext.prebid.bidder.BIDDER
// level, giving priority to imp[].ext.prebid.bidder.BIDDER in case of a conflict.
func mergeBidderParamsImpExtPrebid(impExt *openrtb_ext.ImpExt, reqExtParams map[string]map[string]json.RawMessage) error {
prebid := impExt.GetPrebid()
prebidModified := false
if prebid == nil || len(prebid.Bidder) == 0 {
return nil
}
for bidder, params := range reqExtParams {
impExtPrebidBidder, impExtPrebidBidderExists := prebid.Bidder[bidder]
if !impExtPrebidBidderExists || impExtPrebidBidder == nil {
continue
}
impExtPrebidBidderMap := map[string]json.RawMessage{}
if len(impExtPrebidBidder) > 0 {
if err := jsonutil.Unmarshal(impExtPrebidBidder, &impExtPrebidBidderMap); err != nil {
continue
}
}
modified := false
for key, value := range params {
if _, present := impExtPrebidBidderMap[key]; !present {
impExtPrebidBidderMap[key] = value
modified = true
}
}
if modified {
impExtPrebidBidderJson, err := jsonutil.Marshal(impExtPrebidBidderMap)
if err != nil {
return fmt.Errorf("error marshalling ext.prebid.bidder.BIDDER: %s", err.Error())
}
prebid.Bidder[bidder] = impExtPrebidBidderJson
prebidModified = true
}
}
if prebidModified {
impExt.SetPrebid(prebid)
}
return nil
}
func (deps *endpointDeps) validateRequest(account *config.Account, httpReq *http.Request, req *openrtb_ext.RequestWrapper, isAmp bool, hasStoredAuctionResponses bool, storedBidResp stored_responses.ImpBidderStoredResp, hasStoredBidRequest bool) []error {
errL := []error{}
if req.ID == "" {
return []error{errors.New("request missing required field: \"id\"")}
}
if req.TMax < 0 {
return []error{fmt.Errorf("request.tmax must be nonnegative. Got %d", req.TMax)}
}
if req.LenImp() < 1 {
return []error{errors.New("request.imp must contain at least one element.")}
}
if len(req.Cur) > 1 {
req.Cur = req.Cur[0:1]
errL = append(errL, &errortypes.Warning{Message: fmt.Sprintf("A prebid request can only process one currency. Taking the first currency in the list, %s, as the active currency", req.Cur[0])})
}
// If automatically filling source TID is enabled then validate that
// source.TID exists and If it doesn't, fill it with a randomly generated UUID
if deps.cfg.AutoGenSourceTID {
if err := validateAndFillSourceTID(req, deps.cfg.GenerateRequestID, hasStoredBidRequest, isAmp); err != nil {
return []error{err}
}
}
var requestAliases map[string]string
reqExt, err := req.GetRequestExt()
if err != nil {
return []error{fmt.Errorf("request.ext is invalid: %v", err)}
}
reqPrebid := reqExt.GetPrebid()
if err := deps.parseBidExt(req); err != nil {
return []error{err}
}
if reqPrebid != nil {
requestAliases = reqPrebid.Aliases
if err := deps.validateAliases(requestAliases); err != nil {
return []error{err}
}
if err := deps.validateAliasesGVLIDs(reqPrebid.AliasGVLIDs, requestAliases); err != nil {
return []error{err}
}
if err := deps.validateBidAdjustmentFactors(reqPrebid.BidAdjustmentFactors, requestAliases); err != nil {
return []error{err}
}
if err := validateSChains(reqPrebid.SChains); err != nil {
return []error{err}
}
if err := deps.validateEidPermissions(reqPrebid.Data, requestAliases); err != nil {
return []error{err}
}
if err := currency.ValidateCustomRates(reqPrebid.CurrencyConversions); err != nil {
return []error{err}
}
}
if err := validateOrFillChannel(req, isAmp); err != nil {
return []error{err}
}
if err := validateExactlyOneInventoryType(req); err != nil {
return []error{err}
}
if errs := validateRequestExt(req); len(errs) != 0 {
if errortypes.ContainsFatalError(errs) {
return append(errL, errs...)
}
errL = append(errL, errs...)
}
if err := deps.validateSite(req); err != nil {
return append(errL, err)
}
if err := deps.validateApp(req); err != nil {
return append(errL, err)
}
if err := deps.validateDOOH(req); err != nil {
return append(errL, err)
}
var gpp gpplib.GppContainer
if req.BidRequest.Regs != nil && len(req.BidRequest.Regs.GPP) > 0 {
var errs []error
gpp, errs = gpplib.Parse(req.BidRequest.Regs.GPP)
if len(errs) > 0 {
errL = append(errL, &errortypes.Warning{
Message: fmt.Sprintf("GPP consent string is invalid and will be ignored. (%v)", errs[0]),
WarningCode: errortypes.InvalidPrivacyConsentWarningCode})
}
}
if errs := deps.validateUser(req, requestAliases, gpp); errs != nil {
if len(errs) > 0 {
errL = append(errL, errs...)
}
if errortypes.ContainsFatalError(errs) {
return errL
}
}
if errs := validateRegs(req, gpp); errs != nil {
if len(errs) > 0 {
errL = append(errL, errs...)
}
if errortypes.ContainsFatalError(errs) {
return errL
}
}
if err := validateDevice(req.Device); err != nil {
return append(errL, err)
}
if err := validateOrFillCookieDeprecation(httpReq, req, account); err != nil {
errL = append(errL, err)
}
if ccpaPolicy, err := ccpa.ReadFromRequestWrapper(req, gpp); err != nil {
errL = append(errL, err)
if errortypes.ContainsFatalError([]error{err}) {
return errL
}
} else if _, err := ccpaPolicy.Parse(exchange.GetValidBidders(requestAliases)); err != nil {
if _, invalidConsent := err.(*errortypes.Warning); invalidConsent {
errL = append(errL, &errortypes.Warning{
Message: fmt.Sprintf("CCPA consent is invalid and will be ignored. (%v)", err),
WarningCode: errortypes.InvalidPrivacyConsentWarningCode})
regsExt, err := req.GetRegExt()
if err != nil {
return append(errL, err)
}
regsExt.SetUSPrivacy("")
} else {
return append(errL, err)
}
}
impIDs := make(map[string]int, req.LenImp())
for i, imp := range req.GetImp() {
// check for unique imp id
if firstIndex, ok := impIDs[imp.ID]; ok {
errL = append(errL, fmt.Errorf(`request.imp[%d].id and request.imp[%d].id are both "%s". Imp IDs must be unique.`, firstIndex, i, imp.ID))
}
impIDs[imp.ID] = i
errs := deps.requestValidator.ValidateImp(imp, ortb.ValidationConfig{}, i, requestAliases, hasStoredAuctionResponses, storedBidResp)
if len(errs) > 0 {
errL = append(errL, errs...)
}
if errortypes.ContainsFatalError(errs) {
return errL
}
}
return errL
}
func validateAndFillSourceTID(req *openrtb_ext.RequestWrapper, generateRequestID bool, hasStoredBidRequest bool, isAmp bool) error {
if req.Source == nil {
req.Source = &openrtb2.Source{}
}
if req.Source.TID == "" || req.Source.TID == "{{UUID}}" || (generateRequestID && (isAmp || hasStoredBidRequest)) {
rawUUID, err := uuid.NewV4()
if err != nil {
return errors.New("error creating a random UUID for source.tid")
}
req.Source.TID = rawUUID.String()
}
for _, impWrapper := range req.GetImp() {
ie, _ := impWrapper.GetImpExt()
if ie.GetTid() == "" || ie.GetTid() == "{{UUID}}" || (generateRequestID && (isAmp || hasStoredBidRequest)) {
rawUUID, err := uuid.NewV4()
if err != nil {
return errors.New("imp.ext.tid missing in the imp and error creating a random UID")
}
ie.SetTid(rawUUID.String())
impWrapper.RebuildImp()
}
}
return nil
}
func (deps *endpointDeps) validateBidAdjustmentFactors(adjustmentFactors map[string]float64, aliases map[string]string) error {
uniqueBidders := make(map[string]struct{})
for bidderToAdjust, adjustmentFactor := range adjustmentFactors {
if adjustmentFactor <= 0 {
return fmt.Errorf("request.ext.prebid.bidadjustmentfactors.%s must be a positive number. Got %f", bidderToAdjust, adjustmentFactor)
}
bidderName := bidderToAdjust
normalizedCoreBidder, ok := openrtb_ext.NormalizeBidderName(bidderToAdjust)
if ok {
bidderName = normalizedCoreBidder.String()
}
if _, exists := uniqueBidders[bidderName]; exists {
return fmt.Errorf("cannot have multiple bidders that differ only in case style")
} else {
uniqueBidders[bidderName] = struct{}{}
}
if _, isBidder := deps.bidderMap[bidderName]; !isBidder {
if _, isAlias := aliases[bidderToAdjust]; !isAlias {
return fmt.Errorf("request.ext.prebid.bidadjustmentfactors.%s is not a known bidder or alias", bidderToAdjust)
}
}
}
return nil
}
func validateSChains(sChains []*openrtb_ext.ExtRequestPrebidSChain) error {
_, err := schain.BidderToPrebidSChains(sChains)
return err
}
func (deps *endpointDeps) validateEidPermissions(prebid *openrtb_ext.ExtRequestPrebidData, requestAliases map[string]string) error {
if prebid == nil {
return nil
}