-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathapp.rs
More file actions
578 lines (533 loc) · 21.6 KB
/
Copy pathapp.rs
File metadata and controls
578 lines (533 loc) · 21.6 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
use core::future::Future;
use std::sync::Arc;
use edgezero_core::app::Hooks;
use edgezero_core::context::RequestContext;
use edgezero_core::error::EdgeError;
use edgezero_core::http::{
HandlerFuture, HeaderValue, Method, Request, Response, StatusCode, header,
};
use edgezero_core::router::RouterService;
use error_stack::Report;
use trusted_server_core::auction::endpoints::handle_auction;
use trusted_server_core::auction::{AuctionOrchestrator, build_orchestrator};
use trusted_server_core::cache_policy::EdgeCacheHeader;
use trusted_server_core::ec::EcContext;
use trusted_server_core::error::{IntoHttpResponse as _, TrustedServerError};
use trusted_server_core::integrations::{IntegrationRegistry, ProxyDispatchInput};
use trusted_server_core::proxy::{
handle_first_party_click, handle_first_party_proxy, handle_first_party_proxy_rebuild,
handle_first_party_proxy_sign,
};
use trusted_server_core::publisher::{
AuctionDispatch, buffer_publisher_response_async, handle_page_bids, handle_publisher_request,
handle_tsjs_dynamic, page_bids_preflight_denied,
};
use trusted_server_core::request_signing::{
handle_trusted_server_discovery, handle_verify_signature,
};
use trusted_server_core::settings::Settings;
use trusted_server_core::settings_data::{
default_config_key, default_config_store_name, get_settings_from_config_store,
};
use trusted_server_core::platform::RuntimeServices;
use crate::middleware::{AuthMiddleware, FinalizeResponseMiddleware};
use crate::platform::{AxumPlatformConfigStore, build_runtime_services};
// ---------------------------------------------------------------------------
// AppState
// ---------------------------------------------------------------------------
/// Application state built once at startup and shared across all requests.
pub struct AppState {
settings: Arc<Settings>,
orchestrator: Arc<AuctionOrchestrator>,
registry: Arc<IntegrationRegistry>,
}
/// Build the application state, loading settings and constructing all per-application components.
///
/// # Errors
///
/// Returns an error when settings, the auction orchestrator, or the integration
/// registry fail to initialise.
fn build_state() -> Result<Arc<AppState>, Report<TrustedServerError>> {
let store_name = default_config_store_name();
let config_key = default_config_key();
let settings =
get_settings_from_config_store(&AxumPlatformConfigStore, &store_name, &config_key)?;
build_state_with_settings(settings)
}
/// Build the application state from explicit settings.
///
/// # Errors
///
/// Returns an error when the auction orchestrator or the integration
/// registry fail to initialise.
fn build_state_with_settings(
settings: Settings,
) -> Result<Arc<AppState>, Report<TrustedServerError>> {
let orchestrator = build_orchestrator(&settings)?;
let registry = IntegrationRegistry::new(&settings)?;
Ok(Arc::new(AppState {
settings: Arc::new(settings),
orchestrator: Arc::new(orchestrator),
registry: Arc::new(registry),
}))
}
// ---------------------------------------------------------------------------
// Error helper
// ---------------------------------------------------------------------------
/// Convert a [`Report<TrustedServerError>`] into an HTTP [`Response`].
pub(crate) fn http_error(report: &Report<TrustedServerError>) -> Response {
let root_error = report.current_context();
log::error!("Error occurred: {:?}", report);
let body = edgezero_core::body::Body::from(format!("{}\n", root_error.user_message()));
let mut response = Response::new(body);
*response.status_mut() = root_error.status_code();
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
response
}
/// Builds the local `404 Not Found` returned for legacy `/admin/keys/*`
/// aliases on the Axum dev server.
///
/// These non-`/_ts` aliases are not matched by the `^/_ts/admin` basic-auth
/// handler, so they fail closed locally rather than fall through to the
/// publisher fallback — which would forward the caller's `Authorization` header
/// and key-management payload to the origin, leaking admin credentials.
fn legacy_admin_alias_denied() -> Response {
let mut response = Response::new(edgezero_core::body::Body::from("Not found\n"));
*response.status_mut() = StatusCode::NOT_FOUND;
response.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
response
}
// ---------------------------------------------------------------------------
// Shared handler executor
// ---------------------------------------------------------------------------
async fn execute_handler<F, Fut>(
state: Arc<AppState>,
ctx: RequestContext,
handler: F,
) -> Result<Response, EdgeError>
where
F: FnOnce(Arc<AppState>, RuntimeServices, Request) -> Fut,
Fut: Future<Output = Result<Response, Report<TrustedServerError>>>,
{
let services = build_runtime_services(&ctx);
let req = ctx.into_request();
Ok(handler(state, services, req)
.await
.unwrap_or_else(|e| http_error(&e)))
}
// ---------------------------------------------------------------------------
// EC context
// ---------------------------------------------------------------------------
/// Builds the geo-aware [`EcContext`] for consent-gated endpoints (`/auction`,
/// `/__ts/page-bids`, and the publisher fallback).
///
/// Mirrors the Fastly entry point: `EcContext::default()` leaves jurisdiction
/// Unknown, which fails the auction consent gate closed even for consented
/// users. Geo comes from the platform (a no-op on the local Axum dev server, so
/// jurisdiction stays Unknown there unless the request carries TCF consent). A
/// malformed consent string is logged and falls back to the default
/// (fail-closed) context rather than being silently swallowed.
fn build_ec_context(state: &AppState, services: &RuntimeServices, req: &Request) -> EcContext {
let geo_info = services
.geo()
.lookup(services.client_info().client_ip)
.unwrap_or_else(|e| {
log::warn!("geo lookup failed: {e}");
None
});
EcContext::read_from_request_with_geo(&state.settings, req, services, geo_info.as_ref())
.unwrap_or_else(|e| {
log::warn!("EC context read failed: {e:?}");
EcContext::default()
})
}
// ---------------------------------------------------------------------------
// Fallback dispatcher (tsjs / integration proxy / publisher)
// ---------------------------------------------------------------------------
async fn dispatch_fallback(
state: &AppState,
services: &RuntimeServices,
req: Request,
) -> Result<Response, Report<TrustedServerError>> {
let path = req.uri().path().to_string();
let method = req.method().clone();
if method == Method::GET && path.starts_with("/static/tsjs=") {
return handle_tsjs_dynamic(&req, &state.registry, EdgeCacheHeader::SMaxageFallback);
}
if state.registry.has_route(&method, &path) {
let mut ec_context = EcContext::default();
return state
.registry
.handle_proxy(ProxyDispatchInput {
method: &method,
path: &path,
settings: &state.settings,
kv: None,
ec_context: &mut ec_context,
services,
req,
})
.await
.unwrap_or_else(|| {
Err(Report::new(TrustedServerError::BadRequest {
message: format!("Unknown integration route: {path}"),
}))
});
}
// Run the server-side auction with the configured creative-opportunity
// slots; `handle_publisher_request` matches them against the request path.
let mut ec_context = build_ec_context(state, services, &req);
let auction = AuctionDispatch {
orchestrator: &state.orchestrator,
slots: state.settings.creative_opportunity_slots(),
registry: None,
};
let publisher_response = handle_publisher_request(
&state.settings,
services,
None,
&mut ec_context,
auction,
req,
EdgeCacheHeader::SMaxageFallback,
)
.await?;
// Async finalize so the dispatched auction is collected and its bids are
// injected before `</body>` (the sync buffer path would drop them).
buffer_publisher_response_async(
publisher_response,
&method,
&state.settings,
&state.registry,
&state.orchestrator,
services,
)
.await
}
fn fallback_handler(
state: Arc<AppState>,
) -> impl Fn(RequestContext) -> HandlerFuture + Clone + Send + Sync + 'static {
move |ctx: RequestContext| {
let state = Arc::clone(&state);
Box::pin(execute_handler(
state,
ctx,
|state, services, req| async move { dispatch_fallback(&state, &services, req).await },
))
}
}
// ---------------------------------------------------------------------------
// Named route table
// ---------------------------------------------------------------------------
#[derive(Clone, Copy)]
enum NamedRouteHandler {
TrustedServerDiscovery,
VerifySignature,
AdminNotSupported,
/// Legacy `/admin/keys/*` aliases — denied locally with 404 so they never
/// reach the publisher fallback (which would leak admin credentials).
LegacyAdminDenied,
Auction,
PageBids,
FirstPartyProxy,
FirstPartyClick,
FirstPartySign,
FirstPartyProxyRebuild,
}
struct NamedRoute {
path: &'static str,
primary_methods: &'static [Method],
handler: NamedRouteHandler,
}
const LEGACY_ADMIN_DENY_METHODS: &[Method] = &[
Method::GET,
Method::POST,
Method::HEAD,
Method::OPTIONS,
Method::PUT,
Method::PATCH,
Method::DELETE,
];
fn named_routes() -> [NamedRoute; 12] {
[
NamedRoute {
path: "/.well-known/trusted-server.json",
primary_methods: &[Method::GET],
handler: NamedRouteHandler::TrustedServerDiscovery,
},
NamedRoute {
path: "/verify-signature",
primary_methods: &[Method::POST],
handler: NamedRouteHandler::VerifySignature,
},
// Canonical admin key routes. These match `Settings::ADMIN_ENDPOINTS`
// and the production basic-auth handler regex (`^/_ts/admin`), so they
// are auth-gated under a production-shaped config.
NamedRoute {
path: "/_ts/admin/keys/rotate",
primary_methods: &[Method::POST],
handler: NamedRouteHandler::AdminNotSupported,
},
NamedRoute {
path: "/_ts/admin/keys/deactivate",
primary_methods: &[Method::POST],
handler: NamedRouteHandler::AdminNotSupported,
},
// The legacy non-`/_ts` aliases (`/admin/keys/*`) are denied locally with
// a 404, matching the Fastly and Cloudflare adapters: the production
// basic-auth handler regex `^/_ts/admin` does not match them, and letting
// any publisher-fallback method fall through would forward the caller's
// `Authorization` header and key-management payload to the origin,
// leaking admin credentials.
NamedRoute {
path: "/admin/keys/rotate",
primary_methods: LEGACY_ADMIN_DENY_METHODS,
handler: NamedRouteHandler::LegacyAdminDenied,
},
NamedRoute {
path: "/admin/keys/deactivate",
primary_methods: LEGACY_ADMIN_DENY_METHODS,
handler: NamedRouteHandler::LegacyAdminDenied,
},
NamedRoute {
path: "/auction",
primary_methods: &[Method::POST],
handler: NamedRouteHandler::Auction,
},
// GET runs the SPA re-auction; OPTIONS is denied in-handler as a CORS
// preflight guard for this side-effecting endpoint.
NamedRoute {
path: "/__ts/page-bids",
primary_methods: &[Method::GET, Method::OPTIONS],
handler: NamedRouteHandler::PageBids,
},
NamedRoute {
path: "/first-party/proxy",
primary_methods: &[Method::GET],
handler: NamedRouteHandler::FirstPartyProxy,
},
NamedRoute {
path: "/first-party/click",
primary_methods: &[Method::GET],
handler: NamedRouteHandler::FirstPartyClick,
},
NamedRoute {
path: "/first-party/sign",
primary_methods: &[Method::GET, Method::POST],
handler: NamedRouteHandler::FirstPartySign,
},
NamedRoute {
path: "/first-party/proxy-rebuild",
primary_methods: &[Method::POST],
handler: NamedRouteHandler::FirstPartyProxyRebuild,
},
]
}
fn named_route_handler(
state: Arc<AppState>,
handler: NamedRouteHandler,
) -> impl Fn(RequestContext) -> HandlerFuture + Clone + Send + Sync + 'static {
move |ctx: RequestContext| {
let state = Arc::clone(&state);
Box::pin(execute_handler(
state,
ctx,
move |state, services, req| async move {
match handler {
NamedRouteHandler::TrustedServerDiscovery => {
handle_trusted_server_discovery(&state.settings, &services, req)
}
NamedRouteHandler::VerifySignature => {
handle_verify_signature(&state.settings, &services, req)
}
NamedRouteHandler::AdminNotSupported => {
// Config/secret-store writes are backed by read-only env vars on the
// Axum dev server. Returning 501 is clearer than failing on the first
// store write.
let body = edgezero_core::body::Body::from(
"Admin key management is not supported on the Axum dev server.\n\
Use the Fastly adapter (via Viceroy or deployed) to rotate or deactivate keys.\n",
);
let mut resp = Response::new(body);
*resp.status_mut() = StatusCode::NOT_IMPLEMENTED;
resp.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
Ok(resp)
}
NamedRouteHandler::LegacyAdminDenied => Ok(legacy_admin_alias_denied()),
NamedRouteHandler::Auction => {
// Build the geo-aware EC context so the auction consent
// gate sees the caller's jurisdiction — `EcContext::default()`
// fails it closed for consented users.
let ec_context = build_ec_context(&state, &services, &req);
handle_auction(
&state.settings,
&state.orchestrator,
None,
None,
&ec_context,
&services,
req,
)
.await
}
NamedRouteHandler::PageBids => {
// SPA re-auction endpoint. `OPTIONS` is a CORS preflight
// for this side-effecting GET and is always denied so the
// GET handler's `X-TSJS-Page-Bids` gate stays trustworthy.
if req.method() == Method::OPTIONS {
Ok(page_bids_preflight_denied())
} else {
let ec_context = build_ec_context(&state, &services, &req);
let auction = AuctionDispatch {
orchestrator: &state.orchestrator,
slots: state.settings.creative_opportunity_slots(),
registry: None,
};
handle_page_bids(
&state.settings,
&services,
None,
auction,
&ec_context,
req,
)
.await
}
}
NamedRouteHandler::FirstPartyProxy => {
handle_first_party_proxy(&state.settings, &services, req).await
}
NamedRouteHandler::FirstPartyClick => {
handle_first_party_click(&state.settings, &services, req).await
}
NamedRouteHandler::FirstPartySign => {
handle_first_party_proxy_sign(&state.settings, &services, req).await
}
NamedRouteHandler::FirstPartyProxyRebuild => {
handle_first_party_proxy_rebuild(&state.settings, &services, req).await
}
}
},
))
}
}
// ---------------------------------------------------------------------------
// Startup error fallback
// ---------------------------------------------------------------------------
fn publisher_fallback_methods() -> [Method; 7] {
[
Method::GET,
Method::POST,
Method::HEAD,
Method::OPTIONS,
Method::PUT,
Method::PATCH,
Method::DELETE,
]
}
/// Returns a [`RouterService`] that responds to every route with the startup error.
fn startup_error_router(e: &Report<TrustedServerError>) -> RouterService {
let message = Arc::new(format!("{}\n", e.current_context().user_message()));
let status = e.current_context().status_code();
let make_handler = |msg: Arc<String>| {
move |_ctx: RequestContext| {
let body = edgezero_core::body::Body::from((*msg).clone());
let mut resp = Response::new(body);
*resp.status_mut() = status;
resp.headers_mut().insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/plain; charset=utf-8"),
);
async move { Ok::<Response, EdgeError>(resp) }
}
};
let mut router = RouterService::builder().middleware(FinalizeResponseMiddleware::new(
Arc::new(Settings::default()),
));
for method in publisher_fallback_methods() {
router = router.route("/", method.clone(), make_handler(Arc::clone(&message)));
router = router.route("/{*rest}", method, make_handler(Arc::clone(&message)));
}
router.build()
}
// ---------------------------------------------------------------------------
// TrustedServerApp
// ---------------------------------------------------------------------------
/// `EdgeZero` [`Hooks`] implementation for the Trusted Server application.
pub struct TrustedServerApp;
impl Hooks for TrustedServerApp {
fn name() -> &'static str {
"TrustedServer"
}
fn routes() -> RouterService {
let state = match build_state() {
Ok(s) => s,
Err(ref e) => {
log::error!("failed to build application state: {:?}", e);
return startup_error_router(e);
}
};
build_router(&state)
}
}
impl TrustedServerApp {
/// Build the full application router from explicit settings.
///
/// Testing seam: integration tests use this to drive the router with
/// known-good settings instead of the baked `get_settings()` result,
/// whose embedded placeholder secrets fail validation by design.
///
/// # Errors
///
/// Returns an error when the auction orchestrator or the integration
/// registry fail to initialise.
pub fn routes_with_settings(
settings: Settings,
) -> Result<RouterService, Report<TrustedServerError>> {
let state = build_state_with_settings(settings)?;
Ok(build_router(&state))
}
}
fn build_router(state: &Arc<AppState>) -> RouterService {
let fallback = fallback_handler(Arc::clone(state));
let mut router = RouterService::builder()
.middleware(FinalizeResponseMiddleware::new(Arc::clone(&state.settings)))
.middleware(AuthMiddleware::new(Arc::clone(&state.settings)));
router = router.route("/health", Method::GET, |_ctx: RequestContext| async {
Ok::<Response, EdgeError>(
edgezero_core::http::response_builder()
.status(StatusCode::OK)
.header(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"))
.body(edgezero_core::body::Body::from("ok"))
.expect("should build health response"),
)
});
for route in named_routes() {
for method in route.primary_methods {
router = router.route(
route.path,
method.clone(),
named_route_handler(Arc::clone(state), route.handler),
);
}
for method in publisher_fallback_methods() {
if !route.primary_methods.contains(&method) {
router = router.route(route.path, method, fallback.clone());
}
}
}
for method in publisher_fallback_methods() {
router = router.route("/", method.clone(), fallback.clone());
router = router.route("/{*rest}", method, fallback.clone());
}
router.build()
}