aws_runtime/
recursion_detection.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6use aws_smithy_runtime_api::box_error::BoxError;
7use aws_smithy_runtime_api::client::interceptors::context::BeforeTransmitInterceptorContextMut;
8use aws_smithy_runtime_api::client::interceptors::Intercept;
9use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
10use aws_smithy_types::config_bag::ConfigBag;
11use aws_types::os_shim_internal::Env;
12use http_02x::HeaderValue;
13use percent_encoding::{percent_encode, CONTROLS};
14use std::borrow::Cow;
15
16const TRACE_ID_HEADER: &str = "x-amzn-trace-id";
17
18mod env {
19    pub(super) const LAMBDA_FUNCTION_NAME: &str = "AWS_LAMBDA_FUNCTION_NAME";
20    pub(super) const TRACE_ID: &str = "_X_AMZN_TRACE_ID";
21}
22
23/// Recursion Detection Interceptor
24///
25/// This interceptor inspects the value of the `AWS_LAMBDA_FUNCTION_NAME` and `_X_AMZN_TRACE_ID` environment
26/// variables to detect if the request is being invoked in a Lambda function. If it is, the `X-Amzn-Trace-Id` header
27/// will be set. This enables downstream services to prevent accidentally infinitely recursive invocations spawned
28/// from Lambda.
29#[non_exhaustive]
30#[derive(Debug, Default)]
31pub struct RecursionDetectionInterceptor {
32    env: Env,
33}
34
35impl RecursionDetectionInterceptor {
36    /// Creates a new `RecursionDetectionInterceptor`
37    pub fn new() -> Self {
38        Self::default()
39    }
40}
41
42impl Intercept for RecursionDetectionInterceptor {
43    fn name(&self) -> &'static str {
44        "RecursionDetectionInterceptor"
45    }
46
47    fn modify_before_signing(
48        &self,
49        context: &mut BeforeTransmitInterceptorContextMut<'_>,
50        _runtime_components: &RuntimeComponents,
51        _cfg: &mut ConfigBag,
52    ) -> Result<(), BoxError> {
53        let request = context.request_mut();
54        if request.headers().contains_key(TRACE_ID_HEADER) {
55            return Ok(());
56        }
57
58        if let (Ok(_function_name), Ok(trace_id)) = (
59            self.env.get(env::LAMBDA_FUNCTION_NAME),
60            self.env.get(env::TRACE_ID),
61        ) {
62            request
63                .headers_mut()
64                .insert(TRACE_ID_HEADER, encode_header(trace_id.as_bytes()));
65        }
66        Ok(())
67    }
68}
69
70/// Encodes a byte slice as a header.
71///
72/// ASCII control characters are percent encoded which ensures that all byte sequences are valid headers
73fn encode_header(value: &[u8]) -> HeaderValue {
74    let value: Cow<'_, str> = percent_encode(value, CONTROLS).into();
75    HeaderValue::from_bytes(value.as_bytes()).expect("header is encoded, header must be valid")
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use aws_smithy_protocol_test::{assert_ok, validate_headers};
82    use aws_smithy_runtime_api::client::interceptors::context::{Input, InterceptorContext};
83    use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
84    use aws_smithy_types::body::SdkBody;
85    use aws_types::os_shim_internal::Env;
86    use http_02x::HeaderValue;
87    use proptest::{prelude::*, proptest};
88    use serde::Deserialize;
89    use std::collections::HashMap;
90
91    proptest! {
92        #[test]
93        fn header_encoding_never_panics(s in any::<Vec<u8>>()) {
94            encode_header(&s);
95        }
96    }
97
98    #[test]
99    fn every_char() {
100        let buff = (0..=255).collect::<Vec<u8>>();
101        assert_eq!(
102            encode_header(&buff),
103            HeaderValue::from_static(
104                r##"%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF"##
105            )
106        );
107    }
108
109    #[test]
110    fn run_tests() {
111        let test_cases: Vec<TestCase> =
112            serde_json::from_str(include_str!("../test-data/recursion-detection.json"))
113                .expect("invalid test case");
114        for test_case in test_cases {
115            check(test_case)
116        }
117    }
118
119    #[derive(Deserialize)]
120    #[serde(rename_all = "camelCase")]
121    struct TestCase {
122        env: HashMap<String, String>,
123        request_headers_before: Vec<String>,
124        request_headers_after: Vec<String>,
125    }
126
127    impl TestCase {
128        fn env(&self) -> Env {
129            Env::from(self.env.clone())
130        }
131
132        /// Headers on the input request
133        fn request_headers_before(&self) -> impl Iterator<Item = (&str, &str)> {
134            Self::split_headers(&self.request_headers_before)
135        }
136
137        /// Headers on the output request
138        fn request_headers_after(&self) -> impl Iterator<Item = (&str, &str)> {
139            Self::split_headers(&self.request_headers_after)
140        }
141
142        /// Split text headers on `: `
143        fn split_headers(headers: &[String]) -> impl Iterator<Item = (&str, &str)> {
144            headers
145                .iter()
146                .map(|header| header.split_once(": ").expect("header must contain :"))
147        }
148    }
149
150    fn check(test_case: TestCase) {
151        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
152        let env = test_case.env();
153        let mut request = http_02x::Request::builder();
154        for (name, value) in test_case.request_headers_before() {
155            request = request.header(name, value);
156        }
157        let request = request
158            .body(SdkBody::empty())
159            .expect("must be valid")
160            .try_into()
161            .unwrap();
162        let mut context = InterceptorContext::new(Input::doesnt_matter());
163        context.enter_serialization_phase();
164        context.set_request(request);
165        let _ = context.take_input();
166        context.enter_before_transmit_phase();
167        let mut config = ConfigBag::base();
168
169        let mut ctx = Into::into(&mut context);
170        RecursionDetectionInterceptor { env }
171            .modify_before_signing(&mut ctx, &rc, &mut config)
172            .expect("interceptor must succeed");
173        let mutated_request = context.request().expect("request is set");
174        for (name, _) in mutated_request.headers() {
175            assert_eq!(
176                mutated_request.headers().get_all(name).count(),
177                1,
178                "No duplicated headers"
179            )
180        }
181        assert_ok(validate_headers(
182            mutated_request.headers(),
183            test_case.request_headers_after(),
184        ))
185    }
186}