diff --git a/crates/trusted-server-adapter-axum/src/app.rs b/crates/trusted-server-adapter-axum/src/app.rs index 463c0d544..5ae2f1b0a 100644 --- a/crates/trusted-server-adapter-axum/src/app.rs +++ b/crates/trusted-server-adapter-axum/src/app.rs @@ -657,7 +657,8 @@ fn named_route_handler( handle_first_party_proxy(&state.settings, &services, &ec.context, req).await } NamedRouteHandler::FirstPartyClick => { - handle_first_party_click(&state.settings, &services, req).await + let ec = state.identity.read_request(&services, &req)?; + handle_first_party_click(&state.settings, &services, &ec.context, req).await } NamedRouteHandler::FirstPartySign => { handle_first_party_proxy_sign(&state.settings, &services, req).await diff --git a/crates/trusted-server-adapter-cloudflare/src/app.rs b/crates/trusted-server-adapter-cloudflare/src/app.rs index 205947e58..de3a2672a 100644 --- a/crates/trusted-server-adapter-cloudflare/src/app.rs +++ b/crates/trusted-server-adapter-cloudflare/src/app.rs @@ -682,7 +682,8 @@ fn router_builder(state: &Arc) -> RouterBuilder { .get( "/first-party/click", make_handler(Arc::clone(&state), |s, services, req| async move { - handle_first_party_click(&s.settings, &services, req).await + let ec_context = build_ec_context(&s.settings, &services, &req); + handle_first_party_click(&s.settings, &services, &ec_context, req).await }), ) .get( diff --git a/crates/trusted-server-adapter-fastly/src/app.rs b/crates/trusted-server-adapter-fastly/src/app.rs index e2b5cbb34..4e6dbc824 100644 --- a/crates/trusted-server-adapter-fastly/src/app.rs +++ b/crates/trusted-server-adapter-fastly/src/app.rs @@ -768,7 +768,7 @@ async fn run_named_route( handle_first_party_proxy(&state.settings, services, &ec.ec_context, req).await } NamedRouteHandler::FirstPartyClick => { - handle_first_party_click(&state.settings, services, req).await + handle_first_party_click(&state.settings, services, &ec.ec_context, req).await } NamedRouteHandler::FirstPartySign => { handle_first_party_proxy_sign(&state.settings, services, req).await diff --git a/crates/trusted-server-adapter-spin/src/app.rs b/crates/trusted-server-adapter-spin/src/app.rs index 3d4a2157b..071b85d54 100644 --- a/crates/trusted-server-adapter-spin/src/app.rs +++ b/crates/trusted-server-adapter-spin/src/app.rs @@ -726,8 +726,9 @@ fn router_builder(state: &Arc) -> RouterBuilder { async move { let services = s.services_for_request(&ctx)?; let req = ctx.into_request()?; + let ec_context = build_ec_context(&s.settings, &services, &req); Ok::( - handle_first_party_click(&s.settings, &services, req) + handle_first_party_click(&s.settings, &services, &ec_context, req) .await .unwrap_or_else(|e| http_error(&e)), ) diff --git a/crates/trusted-server-core/src/consent/mod.rs b/crates/trusted-server-core/src/consent/mod.rs index d1a917245..5993546b6 100644 --- a/crates/trusted-server-core/src/consent/mod.rs +++ b/crates/trusted-server-core/src/consent/mod.rs @@ -517,7 +517,11 @@ pub(crate) fn allows_eid_persistence(ctx: &ConsentContext) -> bool { } } -/// Decide whether current-request consent permits creative proxy EC disclosure. +/// Decide whether current-request consent permits disclosing the EC ID to a third party. +/// +/// Used by creative proxy fetches and first-party click redirects. Requires +/// unexpired consent, no GPC signal in any jurisdiction, EC creation consent +/// and EID persistence consent, including TCF Purposes 1 and 4 where applicable. #[must_use] pub(crate) fn allows_proxy_ec_disclosure(ctx: &ConsentContext) -> bool { !ctx.expired && !ctx.gpc && allows_ec_creation(ctx) && allows_eid_persistence(ctx) diff --git a/crates/trusted-server-core/src/proxy.rs b/crates/trusted-server-core/src/proxy.rs index cb7e5261b..3e83386fc 100644 --- a/crates/trusted-server-core/src/proxy.rs +++ b/crates/trusted-server-core/src/proxy.rs @@ -24,12 +24,13 @@ use crate::cache_policy::{ apply_no_store_private_to_headers, cache_control_headers_are_private_or_no_store, remove_edge_cache_headers, }; +use crate::consent::allows_proxy_ec_disclosure; use crate::constants::{ HEADER_ACCEPT, HEADER_ACCEPT_ENCODING, HEADER_ACCEPT_LANGUAGE, HEADER_REFERER, HEADER_USER_AGENT, HEADER_X_FORWARDED_FOR, }; use crate::creative::{CreativeCssProcessor, CreativeHtmlProcessor, first_party_url}; -use crate::ec::EcContext; +use crate::ec::{EcContext, log_id}; use crate::edge_cookie::get_ec_id; use crate::error::TrustedServerError; use crate::outbound::{ @@ -1681,7 +1682,9 @@ fn auction_clicks_switch(settings: &Settings) -> &'static str { /// Accepts the same parameters as the proxy scheme, but instead of proxying the /// content, it validates the URL and issues a 302 redirect to the reconstructed /// target URL. This avoids parsing/downloading the content and lets the browser -/// navigate directly to the destination under first-party control. +/// navigate directly to the destination under first-party control. The request +/// consent context gates EC disclosure; denied consent leaves the validated +/// target unchanged. /// /// Answers the turned-off `404` from [`endpoint_turned_off_response`] while /// click wrapping is off: `[auction] rewrite_clicks`, or `rewrite_creatives` @@ -1695,6 +1698,7 @@ fn auction_clicks_switch(settings: &Settings) -> &'static str { pub async fn handle_first_party_click( settings: &Settings, _services: &RuntimeServices, + ec: &EcContext, req: Request, ) -> Result, Report> { if !settings.auction.rewrites_auction_clicks() { @@ -1706,8 +1710,8 @@ pub async fn handle_first_party_click( let SignedTarget { target_url: full_for_token, - tsurl, had_params, + .. } = reconstruct_and_validate_signed_target(settings, &req.uri().to_string())?; let ec_id = match get_ec_id(&req) { @@ -1719,12 +1723,14 @@ pub async fn handle_first_party_click( }; let mut redirect_target = full_for_token.clone(); - if let Some(ref ec_id_value) = ec_id { + if allows_proxy_ec_disclosure(ec.consent()) + && let Some(ref ec_id_value) = ec_id + { match url::Url::parse(&redirect_target) { Ok(mut url) => { upsert_ec_query_param(&mut url, ec_id_value); redirect_target = url.to_string(); - log::debug!("forwarding EC ID to target url {}", redirect_target); + log::debug!("forwards EC ID to click target: {}", log_id(ec_id_value)); } Err(e) => { log::warn!("failed to parse target url for EC ID forwarding: {:?}", e); @@ -1732,25 +1738,10 @@ pub async fn handle_first_party_click( } } - // Log click metadata for observability - let ua = req - .headers() - .get(HEADER_USER_AGENT) - .and_then(|h| h.to_str().ok()) - .unwrap_or(""); - let referer = req - .headers() - .get(HEADER_REFERER) - .and_then(|h| h.to_str().ok()) - .unwrap_or(""); log::info!( - "redirect tsurl={} params_present={} target={} referer={} ua={} ec_id={}", - tsurl, + "redirect params_present={} ec_id={}", had_params, - redirect_target, - referer, - ua, - ec_id.as_deref().unwrap_or("") + ec_id.as_deref().map(log_id).unwrap_or_default() ); // 302 redirect to target URL @@ -2205,7 +2196,6 @@ pub async fn handle_first_party_proxy_rebuild( #[derive(Debug)] struct SignedTarget { target_url: String, - tsurl: String, had_params: bool, } @@ -2254,8 +2244,8 @@ fn parse_request_target(req_url: &str) -> Result = - handle_first_party_click(&settings, &noop_services(), req) + handle_first_party_click(&settings, &noop_services(), &EcContext::default(), req) .await .expect_err("expected error"); assert_eq!(err.current_context().status_code(), StatusCode::BAD_GATEWAY); @@ -3713,9 +3706,10 @@ mod tests { sig ), ); - let resp = handle_first_party_click(&settings, &noop_services(), req) - .await - .expect("should redirect"); + let resp = + handle_first_party_click(&settings, &noop_services(), &EcContext::default(), req) + .await + .expect("should redirect"); assert_eq!(resp.status(), StatusCode::FOUND); let loc = resp .headers() @@ -3748,7 +3742,14 @@ mod tests { HeaderValue::from_static("ec-123"), ); - let resp = handle_first_party_click(&settings, &noop_services(), req) + let ec = EcContext::new_for_test( + None, + crate::consent::ConsentContext { + jurisdiction: crate::consent::jurisdiction::Jurisdiction::NonRegulated, + ..crate::consent::ConsentContext::default() + }, + ); + let resp = handle_first_party_click(&settings, &noop_services(), &ec, req) .await .expect("should redirect"); @@ -3768,6 +3769,224 @@ mod tests { }); } + fn click_tc_string(purpose_four: bool) -> String { + let mut bytes = [0_u8; 29]; + bytes[0] = 2 << 2; + // Grant all purposes except Purpose 4 in the refusal control. + bytes[19..22].fill(0xff); + if !purpose_four { + bytes[19] &= !(1 << 4); + } + URL_SAFE_NO_PAD.encode(bytes) + } + + async fn click_with_consent( + cookie: &str, + gpc: bool, + geo: &GeoInfo, + target: &str, + ) -> Response { + let mut settings = create_test_settings(); + // Synthetic TC strings use a fixed epoch so these tests do not age out. + settings.consent.check_expiration = false; + let signed = creative::build_click_url( + &settings, + target, + &settings.publisher.effective_public_origin(), + ); + let mut req = build_http_request(Method::GET, signed); + req.headers_mut().insert( + header::COOKIE, + HeaderValue::from_str(&format!("ts-ec=fictional-click-ec-1234567890; {cookie}")) + .expect("should build consent cookie"), + ); + if gpc { + req.headers_mut() + .insert("sec-gpc", HeaderValue::from_static("1")); + } + let services = noop_services(); + let ec_context = + EcContext::read_from_request_with_geo(&settings, &req, &services, Some(geo)) + .expect("should read click consent"); + if cookie.starts_with("euconsent-v2=") { + assert!( + ec_context.consent().tcf.is_some(), + "should decode the TC cookie before exercising the click handler" + ); + } + handle_first_party_click(&settings, &services, &ec_context, req) + .await + .expect("should redirect signed click") + } + + fn click_geo(country: &str, region: Option<&str>) -> GeoInfo { + GeoInfo::country_region(country, region.map(str::to_owned)) + } + + #[test] + fn click_consent_purpose_four_controls_ec_disclosure() { + futures::executor::block_on(async { + let target = "https://example.com/landing?campaign=fake"; + for purpose_four in [false, true] { + let cookie = format!("euconsent-v2={}", click_tc_string(purpose_four)); + let response = + click_with_consent(&cookie, false, &click_geo("DE", None), target).await; + assert_eq!( + response.status(), + StatusCode::FOUND, + "should redirect in both consent states" + ); + let location = + response_header(&response, header::LOCATION).expect("should return Location"); + if purpose_four { + let parsed = url::Url::parse(location).expect("should parse Location"); + assert!( + parsed.query_pairs().any(|(key, value)| key == "ts-ec" + && value == "fictional-click-ec-1234567890"), + "should disclose EC with full consent" + ); + } else { + assert_eq!( + location, target, + "should preserve target exactly when Purpose 4 is refused" + ); + } + } + }); + } + + #[test] + fn click_disclosure_applies_current_context_with_an_available_ec() { + futures::executor::block_on(async { + // Arrange: every case carries an EC; only consent differs. + let settings = create_test_settings(); + let target = "https://example.com/landing?campaign=fake"; + let ec_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.FAKE01"; + let allowed = ConsentContext { + jurisdiction: Jurisdiction::NonRegulated, + ..ConsentContext::default() + }; + for (name, consent, disclose) in [ + ("allowed", allowed.clone(), true), + ("unknown jurisdiction", ConsentContext::default(), false), + ( + "expired consent", + ConsentContext { + expired: true, + ..allowed.clone() + }, + false, + ), + ( + "non-US GPC", + ConsentContext { + gpc: true, + ..allowed.clone() + }, + false, + ), + ] { + let signed = creative::build_click_url( + &settings, + target, + &settings.publisher.effective_public_origin(), + ); + let mut request = build_http_request(Method::GET, signed); + request.headers_mut().insert( + header::COOKIE, + HeaderValue::from_str(&format!("ts-ec={ec_id}")) + .expect("should build EC cookie"), + ); + assert_eq!( + get_ec_id(&request) + .expect("should read request EC") + .as_deref(), + Some(ec_id), + "should make an EC available to the click handler for {name}" + ); + let context = EcContext::new_for_test(Some(ec_id.to_owned()), consent); + + // Act + let response = + handle_first_party_click(&settings, &noop_services(), &context, request) + .await + .expect("should redirect a signed click"); + + // Assert + assert_eq!( + response.status(), + StatusCode::FOUND, + "should preserve navigation for {name}" + ); + let expected = if disclose { + format!("{target}&ts-ec={ec_id}") + } else { + target.to_owned() + }; + assert_eq!( + response_header(&response, header::LOCATION), + Some(expected.as_str()), + "should apply current-request disclosure consent for {name}" + ); + } + }); + } + + #[test] + fn click_decoded_non_us_gpc_withholds_ec() { + futures::executor::block_on(async { + let target = "https://example.com/landing?campaign=fake"; + let cookie = format!("euconsent-v2={}", click_tc_string(true)); + for gpc in [false, true] { + let response = + click_with_consent(&cookie, gpc, &click_geo("DE", None), target).await; + let location = + response_header(&response, header::LOCATION).expect("should return Location"); + if gpc { + assert_eq!( + location, target, + "should withhold an available EC for GPC outside the US" + ); + } else { + assert!( + location.ends_with("&ts-ec=fictional-click-ec-1234567890"), + "should deliver the EC for the otherwise identical decoded consent" + ); + } + } + }); + } + + #[test] + fn click_consent_refusal_preserves_existing_signed_query() { + futures::executor::block_on(async { + let target = "https://example.com/landing?campaign=fake&ts-ec=signed-example-value"; + let cookie = format!("euconsent-v2={}", click_tc_string(false)); + let response = click_with_consent(&cookie, false, &click_geo("DE", None), target).await; + assert_eq!( + response_header(&response, header::LOCATION), + Some(target), + "should preserve the signed target without replacing its existing query" + ); + }); + } + + #[test] + fn click_consent_us_opt_out_and_gpc_withhold_ec() { + futures::executor::block_on(async { + let target = "https://example.com/landing?campaign=fake"; + for (cookie, gpc) in [("us_privacy=1YYY", false), ("us_privacy=1YNN", true)] { + let response = + click_with_consent(cookie, gpc, &click_geo("US", Some("CA")), target).await; + assert_eq!( + response_header(&response, header::LOCATION), + Some(target), + "should leave the target unchanged after a US opt-out or GPC" + ); + } + }); + } + #[test] fn proxy_rebuild_adds_and_removes_params() { futures::executor::block_on(async { @@ -3936,7 +4155,9 @@ mod tests { handle_first_party_proxy(settings, &services, &EcContext::default(), req).await } "/first-party/sign" => handle_first_party_proxy_sign(settings, &services, req).await, - "/first-party/click" => handle_first_party_click(settings, &services, req).await, + "/first-party/click" => { + handle_first_party_click(settings, &services, &EcContext::default(), req).await + } "/first-party/proxy-rebuild" => { handle_first_party_proxy_rebuild(settings, &services, req).await } @@ -4294,9 +4515,10 @@ mod tests { .body(EdgeBody::empty()) .expect("should build origin-form click request"); - let resp = handle_first_party_click(&settings, &noop_services(), req) - .await - .expect("origin-form click should succeed"); + let resp = + handle_first_party_click(&settings, &noop_services(), &EcContext::default(), req) + .await + .expect("origin-form click should succeed"); assert_eq!( resp.status(), @@ -4635,7 +4857,6 @@ mod tests { ); let st = reconstruct_and_validate_signed_target(&settings, &first_party) .expect("reconstruct ok"); - assert_eq!(st.tsurl, "https://cdn.example/asset.js"); assert!(st.had_params); assert_eq!(st.target_url, canonical_clear_url(clear)); } @@ -4651,7 +4872,6 @@ mod tests { ); let st = reconstruct_and_validate_signed_target(&settings, &first_party) .expect("reconstruct ok"); - assert_eq!(st.tsurl, clear); assert!(!st.had_params); assert_eq!(st.target_url, clear); } @@ -4710,9 +4930,10 @@ mod tests { &settings.publisher.effective_public_origin(), ); let req = build_http_request(Method::GET, first_party); - let resp = handle_first_party_click(&settings, &noop_services(), req) - .await - .expect("should redirect"); + let resp = + handle_first_party_click(&settings, &noop_services(), &EcContext::default(), req) + .await + .expect("should redirect"); assert_eq!(resp.status(), StatusCode::FOUND); let cc = response_header(&resp, header::CACHE_CONTROL).unwrap_or(""); assert!(cc.contains("no-store")); diff --git a/docs/guide/api-reference.md b/docs/guide/api-reference.md index 6d1da739c..abadb3956 100644 --- a/docs/guide/api-reference.md +++ b/docs/guide/api-reference.md @@ -621,13 +621,16 @@ Click tracking redirect endpoint. **Response:** - **Status:** `302 Found` -- **Location:** Reconstructed target URL with EC ID injected +- **Location:** Reconstructed target URL, with an available EC ID injected only + when current-request consent permits disclosure **Behavior:** - Validates `tstoken` against reconstructed URL -- Injects `ts-ec` query parameter -- Logs click metadata (tsurl, referer, user agent) +- Injects `ts-ec` only when current-request consent permits both EC use and EID + disclosure; denial preserves the validated target and its existing query +- Logs parameter presence and a redacted EC ID, omitting target URLs, referer + and user agent - Does not proxy content (redirect only) **Contract:** Auth: signed query token. A valid request returns `302` with diff --git a/docs/guide/creative-processing.md b/docs/guide/creative-processing.md index e63af6e8d..11c371491 100644 --- a/docs/guide/creative-processing.md +++ b/docs/guide/creative-processing.md @@ -137,16 +137,18 @@ guard installs its listeners but never acts, because no link carries `data-tsclick`. Both switches also decide where the visitor's EC ID goes. `/first-party/click` -retains its existing behavior: it appends the request's `ts-ec` value to the -landing URL and logs the click with it. The `/first-party/proxy` asset path instead +appends an available request EC ID to the landing URL only when current-request +consent permits EC use and EID disclosure. Its logs use a redacted EC prefix and +omit the target URL, Referer and User-Agent. The `/first-party/proxy` asset path instead uses the [creative disclosure policy](/guide/first-party-proxy#ec-id-disclosure): only a valid canonical cookie EC, affirmative current-request consent and an explicit HTTPS recipient grant permit disclosure. By default, proxied assets receive no EC. With `rewrite_clicks = false`, creative links stop forwarding EC through click rewriting; with `rewrite_clicks = true` and `rewrite_creatives = false`, landing pages can receive it while assets load direct. -The rewrite switches are not consent controls; the proxy policy evaluates consent -again at disclosure, while the click contract remains separate. +The rewrite switches are not consent controls. Both disclosure paths evaluate +current-request consent; creative proxy fetches also require the endpoint grants +above. The same switches decide which creative endpoints answer. `/first-party/proxy` and `/first-party/sign` answer only while diff --git a/docs/guide/first-party-proxy.md b/docs/guide/first-party-proxy.md index 9a96b04ae..0d1faed4d 100644 --- a/docs/guide/first-party-proxy.md +++ b/docs/guide/first-party-proxy.md @@ -129,14 +129,10 @@ GET /first-party/click?tsurl=https://advertiser.example.com/landing&tstoken=sign **Behavior**: 1. **Validates** the `tstoken` signature -2. **Appends** the existing EC ID as `ts-ec` when available +2. **Appends** an available `ts-ec` only when current-request consent permits disclosure 3. **Issues** 302 redirect to target (browser navigates directly) -4. **Logs** click metadata: - - Target URL base (`tsurl`) - - Whether parameters were present - - Full reconstructed URL - - Referer, User-Agent - - EC ID (if available) +4. **Logs** whether parameters were present and a redacted EC ID (if available), + without target URLs, Referer or User-Agent **Example**: @@ -153,7 +149,7 @@ Click URL in creative: ``` -User clicks → Server responds: +With an existing EC and current-request disclosure consent, the server responds: ``` HTTP/1.1 302 Found @@ -482,11 +478,44 @@ retaining forbidden EC is not a compatibility workaround. ### Click ID forwarding -`/first-party/click` and click rebuild retain their existing identity, signing, -navigation, and no-store behavior. Endpoint grants affect creative fetches only; +`/first-party/click` and click rebuild retain their existing signing, navigation, +and no-store behavior. Endpoint grants affect creative fetches only; they do not enable query EC on managed integration assets or change intentional identity in integration payloads. +Click redirects forward an existing EC ID when current-request consent permits +disclosure: + +```html + +``` + +With disclosure consent, the redirect includes the ID: + +``` +302 Found +Location: https://advertiser.example.com?ts-ec=user123 +``` + +::: tip Forwarding Conditions +Click redirects forward EC IDs only when an ID exists in the request and the +current request permits both EC use and EID disclosure. TCF requires Purposes 1 +and 4 where applicable; expired consent, GPC, applicable US opt-outs and unknown +jurisdiction block disclosure. Consent at the time the EC was issued is not +sufficient. + +US opt-outs here apply under the same jurisdiction and consent rules as EC +creation; see the [Consent Model](/guide/edge-cookies#consent-model). + +When disclosure is denied, the redirect preserves the validated signed target +and its existing query without appending an EC ID. A `ts-ec` value already +embedded in that signed target is preserved too; this click gate controls +insertion of the request's EC, not arbitrary tracking parameters supplied by the +creative. Creative fetches follow the endpoint grants above instead. +::: + ## Configuration ### Publisher Settings @@ -817,6 +846,8 @@ Creative policy diagnostics use endpoint ID, normalized origin/path, and decisio reason. They omit EC, cookies, query strings, and complete final URLs. This is a creative-route logging boundary, not repository-wide log redaction. +The click redirect log omits target URLs, Referer, User-Agent and the full EC ID. + ### Diagnostic Headers Add custom headers for debugging: