-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathmain.rs
More file actions
290 lines (258 loc) · 10.6 KB
/
main.rs
File metadata and controls
290 lines (258 loc) · 10.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
use error_stack::Report;
use fastly::http::Method;
use fastly::{Error, Request, Response};
use log_fastly::Logger;
use trusted_server_core::auction::endpoints::handle_auction;
use trusted_server_core::auction::{build_orchestrator, AuctionOrchestrator};
use trusted_server_core::auth::enforce_basic_auth;
use trusted_server_core::constants::{
ENV_FASTLY_IS_STAGING, ENV_FASTLY_SERVICE_VERSION, HEADER_X_GEO_INFO_AVAILABLE,
HEADER_X_TS_ENV, HEADER_X_TS_VERSION,
};
use trusted_server_core::error::TrustedServerError;
use trusted_server_core::geo::GeoInfo;
use trusted_server_core::http_util::sanitize_forwarded_headers;
use trusted_server_core::integrations::IntegrationRegistry;
use trusted_server_core::platform::RuntimeServices;
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::{handle_publisher_request, handle_tsjs_dynamic};
use trusted_server_core::request_signing::{
handle_deactivate_key, handle_rotate_key, handle_trusted_server_discovery,
handle_verify_signature,
};
use trusted_server_core::settings::Settings;
use trusted_server_core::settings_data::get_settings;
mod error;
mod platform;
#[cfg(test)]
mod route_tests;
use crate::error::to_error_response;
use crate::platform::{build_runtime_services, open_kv_store, UnavailableKvStore};
#[fastly::main]
fn main(req: Request) -> Result<Response, Error> {
init_logger();
// Keep the health probe independent from settings loading and routing so
// readiness checks still get a cheap liveness response during startup.
if req.get_method() == Method::GET && req.get_path() == "/health" {
return Ok(Response::from_status(200).with_body_text_plain("ok"));
}
let settings = match get_settings() {
Ok(s) => s,
Err(e) => {
log::error!("Failed to load settings: {:?}", e);
return Ok(to_error_response(&e));
}
};
log::debug!("Settings {settings:?}");
// Build the auction orchestrator once at startup
let orchestrator = match build_orchestrator(&settings) {
Ok(orchestrator) => orchestrator,
Err(e) => {
log::error!("Failed to build auction orchestrator: {:?}", e);
return Ok(to_error_response(&e));
}
};
let integration_registry = match IntegrationRegistry::new(&settings) {
Ok(r) => r,
Err(e) => {
log::error!("Failed to create integration registry: {:?}", e);
return Ok(to_error_response(&e));
}
};
// Start with an unavailable KV slot. Consent-dependent routes lazily
// replace it with the configured store at dispatch time so unrelated
// routes stay available when consent persistence is misconfigured.
let kv_store = std::sync::Arc::new(UnavailableKvStore)
as std::sync::Arc<dyn trusted_server_core::platform::PlatformKvStore>;
let runtime_services = build_runtime_services(&req, kv_store);
futures::executor::block_on(route_request(
&settings,
&orchestrator,
&integration_registry,
&runtime_services,
req,
))
}
async fn route_request(
settings: &Settings,
orchestrator: &AuctionOrchestrator,
integration_registry: &IntegrationRegistry,
runtime_services: &RuntimeServices,
mut req: Request,
) -> Result<Response, Error> {
// Strip client-spoofable forwarded headers at the edge.
// On Fastly this service IS the first proxy — these headers from
// clients are untrusted and can hijack URL rewriting (see #409).
sanitize_forwarded_headers(&mut req);
// Look up geo info via the platform abstraction using the client IP
// already captured in RuntimeServices at the entry point.
let geo_info = runtime_services
.geo()
.lookup(runtime_services.client_info().client_ip)
.unwrap_or_else(|e| {
log::warn!("geo lookup failed: {e}");
None
});
// `get_settings()` should already have rejected invalid handler regexes.
// Keep this fallback so manually-constructed or otherwise unprepared
// settings still become an error response instead of panicking.
match enforce_basic_auth(settings, &req) {
Ok(Some(mut response)) => {
finalize_response(settings, geo_info.as_ref(), &mut response);
return Ok(response);
}
Ok(None) => {}
Err(e) => {
log::error!("Failed to evaluate basic auth: {:?}", e);
let mut response = to_error_response(&e);
finalize_response(settings, geo_info.as_ref(), &mut response);
return Ok(response);
}
}
// Get path and method for routing
let path = req.get_path().to_string();
let method = req.get_method().clone();
// Match known routes and handle them
let result = match (method, path.as_str()) {
// Serve the tsjs library
(Method::GET, path) if path.starts_with("/static/tsjs=") => {
handle_tsjs_dynamic(&req, integration_registry)
}
// Discovery endpoint for trusted-server capabilities and JWKS
(Method::GET, "/.well-known/trusted-server.json") => {
handle_trusted_server_discovery(settings, runtime_services, req)
}
// Signature verification endpoint
(Method::POST, "/verify-signature") => handle_verify_signature(settings, req),
// Key rotation admin endpoints
// Keep in sync with Settings::ADMIN_ENDPOINTS in crates/trusted-server-core/src/settings.rs
(Method::POST, "/admin/keys/rotate") => handle_rotate_key(settings, req),
(Method::POST, "/admin/keys/deactivate") => handle_deactivate_key(settings, req),
// Unified auction endpoint (returns creative HTML inline)
(Method::POST, "/auction") => {
match runtime_services_for_consent_route(settings, runtime_services) {
Ok(auction_services) => {
handle_auction(settings, orchestrator, &auction_services, req).await
}
Err(e) => Err(e),
}
}
// tsjs endpoints
(Method::GET, "/first-party/proxy") => {
handle_first_party_proxy(settings, runtime_services, req).await
}
(Method::GET, "/first-party/click") => {
handle_first_party_click(settings, runtime_services, req).await
}
(Method::GET, "/first-party/sign") | (Method::POST, "/first-party/sign") => {
handle_first_party_proxy_sign(settings, runtime_services, req).await
}
(Method::POST, "/first-party/proxy-rebuild") => {
handle_first_party_proxy_rebuild(settings, runtime_services, req).await
}
(m, path) if integration_registry.has_route(&m, path) => integration_registry
.handle_proxy(&m, path, settings, runtime_services, req)
.await
.unwrap_or_else(|| {
Err(Report::new(TrustedServerError::BadRequest {
message: format!("Unknown integration route: {path}"),
}))
}),
// No known route matched, proxy to publisher origin as fallback
_ => {
log::info!(
"No known route matched for path: {}, proxying to publisher origin",
path
);
match runtime_services_for_consent_route(settings, runtime_services) {
Ok(publisher_services) => {
match handle_publisher_request(
settings,
integration_registry,
&publisher_services,
req,
) {
Ok(response) => Ok(response),
Err(e) => {
log::error!("Failed to proxy to publisher origin: {:?}", e);
Err(e)
}
}
}
Err(e) => Err(e),
}
}
};
// Convert any errors to HTTP error responses
let mut response = result.unwrap_or_else(|e| to_error_response(&e));
finalize_response(settings, geo_info.as_ref(), &mut response);
Ok(response)
}
fn runtime_services_for_consent_route(
settings: &Settings,
runtime_services: &RuntimeServices,
) -> Result<RuntimeServices, Report<TrustedServerError>> {
let Some(store_name) = settings.consent.consent_store.as_deref() else {
return Ok(runtime_services.clone());
};
open_kv_store(store_name)
.map(|store| runtime_services.clone().with_kv_store(store))
.map_err(|e| {
Report::new(TrustedServerError::KvStore {
store_name: store_name.to_string(),
message: e.to_string(),
})
})
}
/// Applies all standard response headers: geo, version, staging, and configured headers.
///
/// Called from every response path (including auth early-returns) so that all
/// outgoing responses carry a consistent set of Trusted Server headers.
///
/// Header precedence (last write wins): geo headers are set first, then
/// version/staging, then operator-configured `settings.response_headers`.
/// This means operators can intentionally override any managed header.
fn finalize_response(settings: &Settings, geo_info: Option<&GeoInfo>, response: &mut Response) {
if let Some(geo) = geo_info {
geo.set_response_headers(response);
} else {
response.set_header(HEADER_X_GEO_INFO_AVAILABLE, "false");
}
if let Ok(v) = ::std::env::var(ENV_FASTLY_SERVICE_VERSION) {
response.set_header(HEADER_X_TS_VERSION, v);
}
if ::std::env::var(ENV_FASTLY_IS_STAGING).as_deref() == Ok("1") {
response.set_header(HEADER_X_TS_ENV, "staging");
}
for (key, value) in &settings.response_headers {
response.set_header(key, value);
}
}
fn init_logger() {
let logger = Logger::builder()
.default_endpoint("tslog")
.echo_stdout(true)
.max_level(log::LevelFilter::Info)
.build()
.expect("should build Logger");
fern::Dispatch::new()
.format(|out, message, record| {
out.finish(format_args!(
"{} {} [{}] {}",
chrono::Local::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
record.level(),
record
.target()
.split("::")
.last()
.unwrap_or(record.target()),
message
))
})
.chain(Box::new(logger) as Box<dyn log::Log>)
.apply()
.expect("should initialize logger");
}