diff --git a/bottlecap/Cargo.lock b/bottlecap/Cargo.lock index ec4e7af11..9947fd1f8 100644 --- a/bottlecap/Cargo.lock +++ b/bottlecap/Cargo.lock @@ -458,6 +458,7 @@ dependencies = [ "hmac", "httpmock", "hyper 0.14.30", + "lazy_static", "log", "proptest", "protobuf", @@ -469,6 +470,7 @@ dependencies = [ "serde_json", "serial_test", "sha2", + "thiserror", "tokio", "tokio-util", "tracing", @@ -2834,18 +2836,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c0342370b38b6a11b6cc11d6a805569958d54cfa061a29969c3b5ce2ea405724" +checksum = "d50af8abc119fb8bb6dbabcfa89656f46f84aa0ac7688088608076ad2b459a84" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.63" +version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a4558b58466b9ad7ca0f102865eccc95938dca1a74a856f2b57b6629050da261" +checksum = "08904e7672f5eb876eaaf87e0ce17857500934f4981c4a0ab2b4aa98baac7fc3" dependencies = [ "proc-macro2", "quote", diff --git a/bottlecap/Cargo.toml b/bottlecap/Cargo.toml index 2403dc991..c14f36a88 100644 --- a/bottlecap/Cargo.toml +++ b/bottlecap/Cargo.toml @@ -18,12 +18,14 @@ datadog-trace-obfuscation = { version = "12.0.0", git = "https://github.com/Data dogstatsd = { git = "https://github.com/DataDog/libdatadog", branch = "main" } figment = { version = "0.10", default-features = false, features = ["yaml", "env"] } hyper = { version = "0.14", default-features = false, features = ["server"] } +lazy_static = { version = "1.5", default-features = false } log = { version = "0.4", default-features = false } protobuf = { version = "3.5", default-features = false } regex = { version = "1.10", default-features = false } reqwest = { version = "0.12", features = ["json", "http2", "rustls-tls"], default-features = false } serde = { version = "1.0", default-features = false, features = ["derive"] } serde_json = { version = "1.0", default-features = false, features = ["alloc"] } +thiserror = { version = "1.0", default-features = false} tokio = { version = "1.37", default-features = false, features = ["macros", "rt-multi-thread"] } tokio-util = { version = "0.7", default-features = false } tracing = { version = "0.1", default-features = false } diff --git a/bottlecap/LICENSE-3rdparty.yml b/bottlecap/LICENSE-3rdparty.yml index 105a5435f..ea6bad0a0 100644 --- a/bottlecap/LICENSE-3rdparty.yml +++ b/bottlecap/LICENSE-3rdparty.yml @@ -17240,7 +17240,7 @@ third_party_libraries: - license: Apache-2.0 text: " Apache License\n Version 2.0, January 2004\n http://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n \"License\" shall mean the terms and conditions for use, reproduction,\n and distribution as defined by Sections 1 through 9 of this document.\n\n \"Licensor\" shall mean the copyright owner or entity authorized by\n the copyright owner that is granting the License.\n\n \"Legal Entity\" shall mean the union of the acting entity and all\n other entities that control, are controlled by, or are under common\n control with that entity. For the purposes of this definition,\n \"control\" means (i) the power, direct or indirect, to cause the\n direction or management of such entity, whether by contract or\n otherwise, or (ii) ownership of fifty percent (50%) or more of the\n outstanding shares, or (iii) beneficial ownership of such entity.\n\n \"You\" (or \"Your\") shall mean an individual or Legal Entity\n exercising permissions granted by this License.\n\n \"Source\" form shall mean the preferred form for making modifications,\n including but not limited to software source code, documentation\n source, and configuration files.\n\n \"Object\" form shall mean any form resulting from mechanical\n transformation or translation of a Source form, including but\n not limited to compiled object code, generated documentation,\n and conversions to other media types.\n\n \"Work\" shall mean the work of authorship, whether in Source or\n Object form, made available under the License, as indicated by a\n copyright notice that is included in or attached to the work\n (an example is provided in the Appendix below).\n\n \"Derivative Works\" shall mean any work, whether in Source or Object\n form, that is based on (or derived from) the Work and for which the\n editorial revisions, annotations, elaborations, or other modifications\n represent, as a whole, an original work of authorship. For the purposes\n of this License, Derivative Works shall not include works that remain\n separable from, or merely link (or bind by name) to the interfaces of,\n the Work and Derivative Works thereof.\n\n \"Contribution\" shall mean any work of authorship, including\n the original version of the Work and any modifications or additions\n to that Work or Derivative Works thereof, that is intentionally\n submitted to Licensor for inclusion in the Work by the copyright owner\n or by an individual or Legal Entity authorized to submit on behalf of\n the copyright owner. For the purposes of this definition, \"submitted\"\n means any form of electronic, verbal, or written communication sent\n to the Licensor or its representatives, including but not limited to\n communication on electronic mailing lists, source code control systems,\n and issue tracking systems that are managed by, or on behalf of, the\n Licensor for the purpose of discussing and improving the Work, but\n excluding communication that is conspicuously marked or otherwise\n designated in writing by the copyright owner as \"Not a Contribution.\"\n\n \"Contributor\" shall mean Licensor and any individual or Legal Entity\n on behalf of whom a Contribution has been received by Licensor and\n subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n copyright license to reproduce, prepare Derivative Works of,\n publicly display, publicly perform, sublicense, and distribute the\n Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of\n this License, each Contributor hereby grants to You a perpetual,\n worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n (except as stated in this section) patent license to make, have made,\n use, offer to sell, sell, import, and otherwise transfer the Work,\n where such license applies only to those patent claims licensable\n by such Contributor that are necessarily infringed by their\n Contribution(s) alone or by combination of their Contribution(s)\n with the Work to which such Contribution(s) was submitted. If You\n institute patent litigation against any entity (including a\n cross-claim or counterclaim in a lawsuit) alleging that the Work\n or a Contribution incorporated within the Work constitutes direct\n or contributory patent infringement, then any patent licenses\n granted to You under this License for that Work shall terminate\n as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the\n Work or Derivative Works thereof in any medium, with or without\n modifications, and in Source or Object form, provided that You\n meet the following conditions:\n\n (a) You must give any other recipients of the Work or\n Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices\n stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works\n that You distribute, all copyright, patent, trademark, and\n attribution notices from the Source form of the Work,\n excluding those notices that do not pertain to any part of\n the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its\n distribution, then any Derivative Works that You distribute must\n include a readable copy of the attribution notices contained\n within such NOTICE file, excluding those notices that do not\n pertain to any part of the Derivative Works, in at least one\n of the following places: within a NOTICE text file distributed\n as part of the Derivative Works; within the Source form or\n documentation, if provided along with the Derivative Works; or,\n within a display generated by the Derivative Works, if and\n wherever such third-party notices normally appear. The contents\n of the NOTICE file are for informational purposes only and\n do not modify the License. You may add Your own attribution\n notices within Derivative Works that You distribute, alongside\n or as an addendum to the NOTICE text from the Work, provided\n that such additional attribution notices cannot be construed\n as modifying the License.\n\n You may add Your own copyright statement to Your modifications and\n may provide additional or different license terms and conditions\n for use, reproduction, or distribution of Your modifications, or\n for any such Derivative Works as a whole, provided Your use,\n reproduction, and distribution of the Work otherwise complies with\n the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise,\n any Contribution intentionally submitted for inclusion in the Work\n by You to the Licensor shall be under the terms and conditions of\n this License, without any additional terms or conditions.\n Notwithstanding the above, nothing herein shall supersede or modify\n the terms of any separate license agreement you may have executed\n with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade\n names, trademarks, service marks, or product names of the Licensor,\n except as required for reasonable and customary use in describing the\n origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or\n agreed to in writing, Licensor provides the Work (and each\n Contributor provides its Contributions) on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n implied, including, without limitation, any warranties or conditions\n of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n PARTICULAR PURPOSE. You are solely responsible for determining the\n appropriateness of using or redistributing the Work and assume any\n risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory,\n whether in tort (including negligence), contract, or otherwise,\n unless required by applicable law (such as deliberate and grossly\n negligent acts) or agreed to in writing, shall any Contributor be\n liable to You for damages, including any direct, indirect, special,\n incidental, or consequential damages of any character arising as a\n result of this License or out of the use or inability to use the\n Work (including but not limited to damages for loss of goodwill,\n work stoppage, computer failure or malfunction, or any and all\n other commercial damages or losses), even if such Contributor\n has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing\n the Work or Derivative Works thereof, You may choose to offer,\n and charge a fee for, acceptance of support, warranty, indemnity,\n or other liability obligations and/or rights consistent with this\n License. However, in accepting such obligations, You may act only\n on Your own behalf and on Your sole responsibility, not on behalf\n of any other Contributor, and only if You agree to indemnify,\n defend, and hold each Contributor harmless for any liability\n incurred by, or claims asserted against, such Contributor by reason\n of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\n To apply the Apache License to your work, attach the following\n boilerplate notice, with the fields enclosed by brackets \"[]\"\n replaced with your own identifying information. (Don't include\n the brackets!) The text should be enclosed in the appropriate\n comment syntax for the file format. We also recommend that a\n file or class name and description of purpose be included on the\n same \"printed page\" as the copyright notice for easier\n identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n\thttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n" - package_name: thiserror - package_version: 1.0.63 + package_version: 1.0.64 repository: https://github.com/dtolnay/thiserror license: MIT OR Apache-2.0 licenses: @@ -17448,7 +17448,7 @@ third_party_libraries: END OF TERMS AND CONDITIONS - package_name: thiserror-impl - package_version: 1.0.63 + package_version: 1.0.64 repository: https://github.com/dtolnay/thiserror license: MIT OR Apache-2.0 licenses: diff --git a/bottlecap/src/traces/context.rs b/bottlecap/src/traces/context.rs new file mode 100644 index 000000000..35e9921ee --- /dev/null +++ b/bottlecap/src/traces/context.rs @@ -0,0 +1,17 @@ +use std::collections::HashMap; + +#[derive(Copy, Clone, Default, Debug)] +pub struct Sampling { + pub priority: Option, + pub mechanism: Option, +} + +#[derive(Clone, Default, Debug)] +#[allow(clippy::module_name_repetitions)] +pub struct SpanContext { + pub trace_id: u64, + pub span_id: u64, + pub sampling: Option, + pub origin: Option, + pub tags: HashMap, +} diff --git a/bottlecap/src/traces/mod.rs b/bottlecap/src/traces/mod.rs index 8545fbe40..d8facd07c 100644 --- a/bottlecap/src/traces/mod.rs +++ b/bottlecap/src/traces/mod.rs @@ -1,6 +1,8 @@ // Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/ // SPDX-License-Identifier: Apache-2.0 +pub mod context; +pub mod propagation; pub mod stats_flusher; pub mod stats_processor; pub mod trace_agent; diff --git a/bottlecap/src/traces/propagation/carrier.rs b/bottlecap/src/traces/propagation/carrier.rs new file mode 100644 index 000000000..fc5ef9dbb --- /dev/null +++ b/bottlecap/src/traces/propagation/carrier.rs @@ -0,0 +1,68 @@ +/// Code inspired, and copied, by OpenTelemetry Rust project. +/// +/// +use std::collections::HashMap; + +/// Injector provides an interface for a carrier to be used +/// with a Propagator to inject a Context into the carrier. +/// +pub trait Injector { + /// Set a value in the carrier. + fn set(&mut self, key: &str, value: String); +} + +pub trait Extractor { + /// Get a value from the carrier. + fn get(&self, key: &str) -> Option<&str>; + + /// Get all keys from the carrier. + fn keys(&self) -> Vec<&str>; +} + +impl Injector for HashMap { + /// Set a key and value in the `HashMap`. + fn set(&mut self, key: &str, value: String) { + self.insert(key.to_lowercase(), value); + } +} + +impl Extractor for HashMap { + /// Get a value for a key from the `HashMap`. + fn get(&self, key: &str) -> Option<&str> { + self.get(&key.to_lowercase()).map(String::as_str) + } + + /// Collect all the keys from the `HashMap`. + fn keys(&self) -> Vec<&str> { + self.keys().map(String::as_str).collect::>() + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn hash_map_get() { + let mut carrier = HashMap::new(); + carrier.set("headerName", "value".to_string()); + + assert_eq!( + Extractor::get(&carrier, "HEADERNAME"), + Some("value"), + "case insensitive extraction" + ); + } + + #[test] + fn hash_map_keys() { + let mut carrier = HashMap::new(); + carrier.set("headerName1", "value1".to_string()); + carrier.set("headerName2", "value2".to_string()); + + let got = Extractor::keys(&carrier); + assert_eq!(got.len(), 2); + assert!(got.contains(&"headername1")); + assert!(got.contains(&"headername2")); + } +} diff --git a/bottlecap/src/traces/propagation/error.rs b/bottlecap/src/traces/propagation/error.rs new file mode 100644 index 000000000..af7a37d9b --- /dev/null +++ b/bottlecap/src/traces/propagation/error.rs @@ -0,0 +1,33 @@ +use thiserror::Error; + +#[derive(Error, Debug, Copy, Clone)] +#[error("Cannot {} from {}, {}", operation, message, propagator_name)] +pub struct Error { + message: &'static str, + // which propagator this error comes from + propagator_name: &'static str, + // what operation was attempted + operation: &'static str, +} + +impl Error { + /// Error when extracting a value from a carrier + #[must_use] + pub fn extract(message: &'static str, propagator_name: &'static str) -> Self { + Self { + message, + propagator_name, + operation: "extract", + } + } + + /// Error when injecting a value into a carrier + #[allow(clippy::must_use_candidate)] + pub fn inject(message: &'static str, propagator_name: &'static str) -> Self { + Self { + message, + propagator_name, + operation: "inject", + } + } +} diff --git a/bottlecap/src/traces/propagation/mod.rs b/bottlecap/src/traces/propagation/mod.rs new file mode 100644 index 000000000..ef268ef61 --- /dev/null +++ b/bottlecap/src/traces/propagation/mod.rs @@ -0,0 +1,3 @@ +pub mod carrier; +pub mod error; +pub mod text_map_propagator; diff --git a/bottlecap/src/traces/propagation/text_map_propagator.rs b/bottlecap/src/traces/propagation/text_map_propagator.rs new file mode 100644 index 000000000..ce3f5abd1 --- /dev/null +++ b/bottlecap/src/traces/propagation/text_map_propagator.rs @@ -0,0 +1,508 @@ +use std::collections::HashMap; + +use lazy_static::lazy_static; +use log::warn; +use regex::Regex; +use tracing::{debug, error}; + +use super::{ + carrier::{Extractor, Injector}, + error::Error, +}; + +use crate::traces::context::{Sampling, SpanContext}; + +// Datadog Keys +const DATADOG_TRACE_ID_KEY: &str = "x-datadog-trace-id"; +const DATADOG_PARENT_ID_KEY: &str = "x-datadog-parent-id"; +const DATADOG_SAMPLING_PRIORITY_KEY: &str = "x-datadog-sampling-priority"; +const DATADOG_ORIGIN_KEY: &str = "x-datadog-origin"; +const DATADOG_TAGS_KEY: &str = "x-datadog-tags"; + +const DATADOG_HIGHER_ORDER_TRACE_ID_BITS_KEY: &str = "_dd.p.tid"; +const DATADOG_PROPAGATION_ERROR_KEY: &str = "_dd.propagation_error"; +const DATADOG_LAST_PARENT_ID_KEY: &str = "_dd.parent_id"; +const DATADOG_SAMPLING_DECISION_KEY: &str = "_dd.p.dm"; + +// Traceparent Keys +const TRACEPARENT_KEY: &str = "traceparent"; +const TRACESTATE_KEY: &str = "tracestate"; + +lazy_static! { + static ref TRACEPARENT_REGEX: Regex = + Regex::new(r"(?i)^([a-f0-9]{2})-([a-f0-9]{32})-([a-f0-9]{16})-([a-f0-9]{2})(-.*)?$") + .expect("failed creating regex"); + static ref INVALID_SEGMENT_REGEX: Regex = Regex::new(r"^0+$").expect("failed creating regex"); + static ref VALID_TAG_KEY_REGEX: Regex = + Regex::new(r"^_dd\.p\.[\x21-\x2b\x2d-\x7e]+$").expect("failed creating regex"); + static ref VALID_TAG_VALUE_REGEX: Regex = + Regex::new(r"^[\x20-\x2b\x2d-\x7e]*$").expect("failed creating regex"); + static ref INVALID_ASCII_CHARACTERS_REGEX: Regex = + Regex::new(r"[^\x20-\x7E]+").expect("failed creating regex"); + static ref VALID_SAMPLING_DECISION_REGEX: Regex = + Regex::new(r"^-([0-9])$").expect("failed creating regex"); +} + +pub trait TextMapPropagator { + fn extract(&self, carrier: &dyn Extractor) -> SpanContext; + fn inject(&self, context: SpanContext, carrier: &mut dyn Injector); +} + +#[derive(Clone, Copy)] +pub struct DatadogPropagator; + +impl TextMapPropagator for DatadogPropagator { + fn extract(&self, carrier: &dyn Extractor) -> SpanContext { + Self::extract_context(carrier).unwrap_or_default() + } + + fn inject(&self, _context: SpanContext, _carrier: &mut dyn Injector) { + todo!(); + } +} + +impl DatadogPropagator { + fn extract_context(carrier: &dyn Extractor) -> Option { + if let Some(trace_id) = Self::extract_trace_id(carrier) { + let parent_id = Self::extract_parent_id(carrier).unwrap_or(0); + let origin = Self::extract_origin(carrier); + let mut tags = Self::extract_tags(carrier); + let sampling_priority = Self::extract_sampling_priority(carrier).unwrap_or(2); + + Self::validate_sampling_decision(&mut tags); + + return Some(SpanContext { + trace_id, + span_id: parent_id, + sampling: Some(Sampling { + priority: Some(sampling_priority), + mechanism: None, + }), + origin, + tags, + }); + } + + None + } + + fn validate_sampling_decision(tags: &mut HashMap) { + let should_remove = + tags.get(DATADOG_SAMPLING_DECISION_KEY) + .map_or(false, |sampling_decision| { + let is_invalid = !VALID_SAMPLING_DECISION_REGEX.is_match(sampling_decision); + if is_invalid { + warn!("Failed to decode `_dd.p.dm`: {}", sampling_decision); + } + is_invalid + }); + + if should_remove { + tags.remove(DATADOG_SAMPLING_DECISION_KEY); + tags.insert( + DATADOG_PROPAGATION_ERROR_KEY.to_string(), + "decoding_error".to_string(), + ); + } + + // todo: appsec standalone + } + + fn extract_trace_id(carrier: &dyn Extractor) -> Option { + let trace_id = carrier.get(DATADOG_TRACE_ID_KEY)?; + + if INVALID_SEGMENT_REGEX.is_match(trace_id) { + return None; + } + + trace_id.parse::().ok() + } + + fn extract_parent_id(carrier: &dyn Extractor) -> Option { + let parent_id = carrier.get(DATADOG_PARENT_ID_KEY)?; + + parent_id.parse::().ok() + } + + fn extract_sampling_priority(carrier: &dyn Extractor) -> Option { + let sampling_priority = carrier.get(DATADOG_SAMPLING_PRIORITY_KEY)?; + + sampling_priority.parse::().ok() + } + + fn extract_origin(carrier: &dyn Extractor) -> Option { + let origin = carrier.get(DATADOG_ORIGIN_KEY)?; + Some(origin.to_string()) + } + + fn extract_tags(carrier: &dyn Extractor) -> HashMap { + let carrier_tags = carrier.get(DATADOG_TAGS_KEY).unwrap_or_default(); + let mut tags: HashMap = HashMap::new(); + + // todo: + // - trace propagation disabled + // - trace propagation max lenght + + let pairs = carrier_tags.split(','); + for pair in pairs { + if let Some((k, v)) = pair.split_once('=') { + // todo: reject key on tags extract reject + if k.starts_with("_dd.p") { + tags.insert(k.to_string(), v.to_string()); + } + } + } + + // Handle 128bit trace ID + if !tags.is_empty() { + if let Some(trace_id_higher_order_bits) = + carrier.get(DATADOG_HIGHER_ORDER_TRACE_ID_BITS_KEY) + { + if !Self::higher_order_bits_valid(trace_id_higher_order_bits) { + warn!("Malformed Trace ID: {trace_id_higher_order_bits} Failed to decode trace ID from carrier."); + tags.insert( + DATADOG_PROPAGATION_ERROR_KEY.to_string(), + format!("malformed tid {trace_id_higher_order_bits}"), + ); + tags.remove(DATADOG_HIGHER_ORDER_TRACE_ID_BITS_KEY); + } + } + } + + if !tags.contains_key(DATADOG_SAMPLING_DECISION_KEY) { + tags.insert(DATADOG_SAMPLING_DECISION_KEY.to_string(), "-3".to_string()); + } + + tags + } + + fn higher_order_bits_valid(trace_id_higher_order_bits: &str) -> bool { + if trace_id_higher_order_bits.len() != 16 { + return false; + } + + match u64::from_str_radix(trace_id_higher_order_bits, 16) { + Ok(_) => {} + Err(_) => return false, + } + + true + } +} + +struct Traceparent { + sampling_priority: i8, + trace_id: u128, + span_id: u64, +} + +struct Tracestate { + sampling_priority: Option, + origin: Option, + lower_order_trace_id: Option, +} + +#[derive(Clone, Copy)] +pub struct TraceparentPropagator; + +impl TextMapPropagator for TraceparentPropagator { + fn extract(&self, carrier: &dyn Extractor) -> SpanContext { + Self::extract_context(carrier).unwrap_or_default() + } + + fn inject(&self, _context: SpanContext, _carrier: &mut dyn Injector) { + todo!() + } +} + +impl TraceparentPropagator { + fn extract_context(carrier: &dyn Extractor) -> Option { + let tp = carrier.get(TRACEPARENT_KEY)?.trim(); + + match Self::extract_traceparent(tp) { + Ok(traceparent) => { + let mut tags = HashMap::new(); + tags.insert(TRACEPARENT_KEY.to_string(), tp.to_string()); + + let mut origin = None; + let mut sampling_priority = traceparent.sampling_priority; + if let Some(ts) = carrier.get(TRACESTATE_KEY) { + if let Some(tracestate) = Self::extract_tracestate(ts, &mut tags) { + if let Some(lpid) = tracestate.lower_order_trace_id { + tags.insert(DATADOG_LAST_PARENT_ID_KEY.to_string(), lpid); + } + + origin = tracestate.origin; + + sampling_priority = Self::define_sampling_priority( + traceparent.sampling_priority, + tracestate.sampling_priority, + ); + } + } else { + debug!("No `dd` value found in tracestate"); + } + + let (trace_id_higher_order_bits, trace_id_lower_order_bits) = + Self::split_trace_id(traceparent.trace_id); + tags.insert( + DATADOG_HIGHER_ORDER_TRACE_ID_BITS_KEY.to_string(), + trace_id_higher_order_bits.to_string(), + ); + + Some(SpanContext { + trace_id: trace_id_lower_order_bits, + span_id: traceparent.span_id, + sampling: Some(Sampling { + priority: Some(sampling_priority), + mechanism: None, + }), + origin, + tags, + }) + } + Err(e) => { + error!("Failed to extract traceparent: {e}"); + None + } + } + } + + fn extract_tracestate( + tracestate: &str, + tags: &mut HashMap, + ) -> Option { + let ts_v = tracestate.split(',').map(str::trim); + let ts = ts_v.clone().collect::>().join(","); + + if INVALID_ASCII_CHARACTERS_REGEX.is_match(&ts) { + debug!("Received invalid tracestate header {tracestate}"); + return None; + } + + tags.insert(TRACESTATE_KEY.to_string(), ts.to_string()); + + let mut dd: Option> = None; + for v in ts_v.clone() { + if let Some(stripped) = v.strip_prefix("dd=") { + dd = Some( + stripped + .split(';') + .filter_map(|item| { + let mut parts = item.splitn(2, ':'); + Some((parts.next()?.to_string(), parts.next()?.to_string())) + }) + .collect(), + ); + } + } + + if let Some(dd) = dd { + let mut tracestate = Tracestate { + sampling_priority: None, + origin: None, + lower_order_trace_id: None, + }; + + if let Some(ts_sp) = dd.get("s") { + if let Ok(p_sp) = ts_sp.parse::() { + tracestate.sampling_priority = Some(p_sp); + } + } + + if let Some(o) = dd.get("o") { + tracestate.origin = Some(Self::decode_tag_value(o)); + } + + if let Some(lo_tid) = dd.get("p") { + tracestate.lower_order_trace_id = Some(lo_tid.to_string()); + } + + for (k, v) in &dd { + if k.starts_with("t.") { + let nk = format!("_dd.p.{k}"); + tags.insert(nk, Self::decode_tag_value(v)); + } + } + + return Some(tracestate); + } + + None + } + + fn decode_tag_value(value: &str) -> String { + value.replace('~', "=") + } + + fn define_sampling_priority( + traceparent_sampling_priority: i8, + tracestate_sampling_priority: Option, + ) -> i8 { + if let Some(ts_sp) = tracestate_sampling_priority { + if (traceparent_sampling_priority == 1 && ts_sp > 0) + || (traceparent_sampling_priority == 0 && ts_sp < 0) + { + return ts_sp; + } + } + + traceparent_sampling_priority + } + + fn extract_traceparent(traceparent: &str) -> Result { + let captures = TRACEPARENT_REGEX + .captures(traceparent) + .ok_or_else(|| Error::extract("invalid traceparent", "traceparent"))?; + + let version = &captures[1]; + let trace_id = &captures[2]; + let span_id = &captures[3]; + let flags = &captures[4]; + let tail = captures.get(5).map_or("", |m| m.as_str()); + + Self::extract_version(version, tail)?; + + let trace_id = Self::extract_trace_id(trace_id)?; + let span_id = Self::extract_span_id(span_id)?; + + let trace_flags = Self::extract_trace_flags(flags)?; + let sampling_priority = i8::from(trace_flags & 0x1 != 0); + + Ok(Traceparent { + sampling_priority, + trace_id, + span_id, + }) + } + + fn extract_version(version: &str, tail: &str) -> Result<(), Error> { + match version { + "ff" => { + return Err(Error::extract( + "`ff` is an invalid traceparent version", + "traceparent", + )) + } + "00" => { + if !tail.is_empty() { + return Err(Error::extract("Traceparent with version `00` should contain only 4 values delimited by `-`", "traceparent")); + } + } + _ => { + warn!("Unsupported traceparent version {version}, still atempenting to parse"); + } + } + + Ok(()) + } + + fn extract_trace_id(trace_id: &str) -> Result { + if INVALID_SEGMENT_REGEX.is_match(trace_id) { + return Err(Error::extract( + "`0` value for trace_id is invalid", + "traceparent", + )); + } + + u128::from_str_radix(trace_id, 16) + .map_err(|_| Error::extract("Failed to decode trace_id", "traceparent")) + } + + #[allow(clippy::cast_possible_truncation)] + fn split_trace_id(trace_id: u128) -> (u64, u64) { + let trace_id_lower_order_bits = trace_id as u64; + let trace_id_higher_order_bits = (trace_id >> 64) as u64; + + (trace_id_higher_order_bits, trace_id_lower_order_bits) + } + + fn extract_span_id(span_id: &str) -> Result { + if INVALID_SEGMENT_REGEX.is_match(span_id) { + return Err(Error::extract( + "`0` value for span_id is invalid", + "traceparent", + )); + } + + u64::from_str_radix(span_id, 16) + .map_err(|_| Error::extract("Failed to decode span_id", "traceparent")) + } + + fn extract_trace_flags(flags: &str) -> Result { + if flags.len() != 2 { + return Err(Error::extract("Invalid trace flags length", "traceparent")); + } + + u8::from_str_radix(flags, 16) + .map_err(|_| Error::extract("Failed to decode trace_flags", "traceparent")) + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_extract_datadog_propagator() { + let mut headers = HashMap::new(); + headers.insert("x-datadog-trace-id".to_string(), "1234".to_string()); + headers.insert("x-datadog-parent-id".to_string(), "5678".to_string()); + headers.insert("x-datadog-sampling-priority".to_string(), "1".to_string()); + headers.insert("x-datadog-origin".to_string(), "synthetics".to_string()); + headers.insert( + "x-datadog-tags".to_string(), + "_dd.p.test=value,_dd.p.tid=4321,any=tag".to_string(), + ); + + let propagator = DatadogPropagator; + + let context = propagator.extract(&headers); + + assert_eq!(context.trace_id, 1234); + assert_eq!(context.span_id, 5678); + assert_eq!(context.sampling.unwrap().priority, Some(1)); + assert_eq!(context.origin, Some("synthetics".to_string())); + println!("{:?}", context.tags); + assert_eq!(context.tags.get("_dd.p.test").unwrap(), "value"); + assert_eq!(context.tags.get("_dd.p.tid").unwrap(), "4321"); + assert_eq!(context.tags.get("_dd.p.dm").unwrap(), "-3"); + } + + #[test] + fn test_extract_traceparent_propagator() { + let mut headers = HashMap::new(); + headers.insert( + "traceparent".to_string(), + "00-80f198ee56343ba864fe8b2a57d3eff7-00f067aa0ba902b7-01".to_string(), + ); + headers.insert( + "tracestate".to_string(), + "dd=p:00f067aa0ba902b7;s:2;o:rum".to_string(), + ); + + let propagator = TraceparentPropagator; + let context = propagator.extract(&headers); + + assert_eq!(context.trace_id, 7277407061855694839); + assert_eq!(context.span_id, 67667974448284343); + assert_eq!(context.sampling.unwrap().priority, Some(2)); + assert_eq!(context.origin, Some("rum".to_string())); + assert_eq!( + context.tags.get("traceparent").unwrap(), + "00-80f198ee56343ba864fe8b2a57d3eff7-00f067aa0ba902b7-01" + ); + assert_eq!( + context.tags.get("tracestate").unwrap(), + "dd=p:00f067aa0ba902b7;s:2;o:rum" + ); + assert_eq!( + context.tags.get("_dd.p.tid").unwrap(), + "9291375655657946024" + ); + assert_eq!( + context.tags.get("_dd.parent_id").unwrap(), + "00f067aa0ba902b7" + ); + } +}