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
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

//! RuntimePlugin to ensure that the amount of data received matches the `Content-Length` header

use aws_smithy_runtime_api::box_error::BoxError;
use aws_smithy_runtime_api::client::interceptors::context::BeforeDeserializationInterceptorContextMut;
use aws_smithy_runtime_api::client::interceptors::Intercept;
use aws_smithy_runtime_api::client::runtime_components::{
    RuntimeComponents, RuntimeComponentsBuilder,
};
use aws_smithy_runtime_api::client::runtime_plugin::RuntimePlugin;
use aws_smithy_runtime_api::http::Response;
use aws_smithy_types::body::SdkBody;
use aws_smithy_types::config_bag::ConfigBag;
use bytes::Buf;
use http_body_1::{Frame, SizeHint};
use pin_project_lite::pin_project;
use std::borrow::Cow;
use std::error::Error;
use std::fmt::{Display, Formatter};
use std::pin::Pin;
use std::task::{ready, Context, Poll};
pin_project! {
    /// A body-wrapper that will calculate the `InnerBody`'s checksum and emit it as a trailer.
    struct ContentLengthEnforcingBody<InnerBody> {
            #[pin]
            body: InnerBody,
            expected_length: u64,
            bytes_received: u64,
    }
}

/// An error returned when a body did not have the expected content length
#[derive(Debug)]
pub struct ContentLengthError {
    expected: u64,
    received: u64,
}

impl Error for ContentLengthError {}

impl Display for ContentLengthError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Invalid Content-Length: Expected {} bytes but {} bytes were received",
            self.expected, self.received
        )
    }
}

impl ContentLengthEnforcingBody<SdkBody> {
    /// Wraps an existing [`SdkBody`] in a content-length enforcement layer
    fn wrap(body: SdkBody, content_length: u64) -> SdkBody {
        body.map_preserve_contents(move |b| {
            SdkBody::from_body_1_x(ContentLengthEnforcingBody {
                body: b,
                expected_length: content_length,
                bytes_received: 0,
            })
        })
    }
}

impl<
        E: Into<aws_smithy_types::body::Error>,
        Data: Buf,
        InnerBody: http_body_1::Body<Error = E, Data = Data>,
    > http_body_1::Body for ContentLengthEnforcingBody<InnerBody>
{
    type Data = Data;
    type Error = aws_smithy_types::body::Error;

    fn poll_frame(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
        let this = self.as_mut().project();
        match ready!(this.body.poll_frame(cx)) {
            None => {
                if *this.expected_length == *this.bytes_received {
                    Poll::Ready(None)
                } else {
                    Poll::Ready(Some(Err(ContentLengthError {
                        expected: *this.expected_length,
                        received: *this.bytes_received,
                    }
                    .into())))
                }
            }
            Some(Err(e)) => Poll::Ready(Some(Err(e.into()))),
            Some(Ok(frame)) => {
                if let Some(data) = frame.data_ref() {
                    *this.bytes_received += data.remaining() as u64;
                }
                Poll::Ready(Some(Ok(frame)))
            }
        }
    }

    fn is_end_stream(&self) -> bool {
        self.body.is_end_stream()
    }

    fn size_hint(&self) -> SizeHint {
        self.body.size_hint()
    }
}

#[derive(Debug, Default)]
struct EnforceContentLengthInterceptor {}

impl Intercept for EnforceContentLengthInterceptor {
    fn name(&self) -> &'static str {
        "EnforceContentLength"
    }

    fn modify_before_deserialization(
        &self,
        context: &mut BeforeDeserializationInterceptorContextMut<'_>,
        _runtime_components: &RuntimeComponents,
        _cfg: &mut ConfigBag,
    ) -> Result<(), BoxError> {
        let content_length = match extract_content_length(context.response()) {
            Err(err) => {
                tracing::warn!(err = ?err, "could not parse content length from content-length header. This header will be ignored");
                return Ok(());
            }
            Ok(Some(content_length)) => content_length,
            Ok(None) => return Ok(()),
        };

        tracing::trace!(
            expected_length = content_length,
            "Wrapping response body in content-length enforcement."
        );

        let body = context.response_mut().take_body();
        let wrapped = body.map_preserve_contents(move |body| {
            ContentLengthEnforcingBody::wrap(body, content_length)
        });
        *context.response_mut().body_mut() = wrapped;
        Ok(())
    }
}

fn extract_content_length<B>(response: &Response<B>) -> Result<Option<u64>, BoxError> {
    let Some(content_length) = response.headers().get("content-length") else {
        tracing::trace!("No content length header was set. Will not validate content length");
        return Ok(None);
    };
    if response.headers().get_all("content-length").count() != 1 {
        return Err("Found multiple content length headers. This is invalid".into());
    }

    Ok(Some(content_length.parse::<u64>()?))
}

/// Runtime plugin that enforces response bodies match their expected content length
#[derive(Debug, Default)]
pub struct EnforceContentLengthRuntimePlugin {}

impl EnforceContentLengthRuntimePlugin {
    /// Creates a runtime plugin which installs Content-Length enforcement middleware for response bodies
    pub fn new() -> Self {
        Self {}
    }
}

impl RuntimePlugin for EnforceContentLengthRuntimePlugin {
    fn runtime_components(
        &self,
        _current_components: &RuntimeComponentsBuilder,
    ) -> Cow<'_, RuntimeComponentsBuilder> {
        Cow::Owned(
            RuntimeComponentsBuilder::new("EnforceContentLength")
                .with_interceptor(EnforceContentLengthInterceptor {}),
        )
    }
}

#[cfg(all(feature = "test-util", test))]
mod test {
    use crate::assert_str_contains;
    use crate::client::http::body::content_length_enforcement::{
        extract_content_length, ContentLengthEnforcingBody,
    };
    use aws_smithy_runtime_api::http::Response;
    use aws_smithy_types::body::SdkBody;
    use aws_smithy_types::byte_stream::ByteStream;
    use aws_smithy_types::error::display::DisplayErrorContext;
    use bytes::Bytes;
    use http::header::CONTENT_LENGTH;
    use http_body_0_4::Body;
    use http_body_1::Frame;
    use std::error::Error;
    use std::pin::Pin;
    use std::task::{Context, Poll};

    /// Body for tests so we ensure our code works on a body split across multiple frames
    struct ManyFrameBody {
        data: Vec<u8>,
    }

    impl ManyFrameBody {
        fn new(input: impl Into<String>) -> SdkBody {
            let mut data = input.into().as_bytes().to_vec();
            data.reverse();
            SdkBody::from_body_1_x(Self { data })
        }
    }

    impl http_body_1::Body for ManyFrameBody {
        type Data = Bytes;
        type Error = <SdkBody as Body>::Error;

        fn poll_frame(
            mut self: Pin<&mut Self>,
            _cx: &mut Context<'_>,
        ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
            match self.data.pop() {
                Some(next) => Poll::Ready(Some(Ok(Frame::data(Bytes::from(vec![next]))))),
                None => Poll::Ready(None),
            }
        }
    }

    #[tokio::test]
    async fn stream_too_short() {
        let body = ManyFrameBody::new("123");
        let enforced = ContentLengthEnforcingBody::wrap(body, 10);
        let err = expect_body_error(enforced).await;
        assert_str_contains!(
            format!("{}", DisplayErrorContext(err)),
            "Expected 10 bytes but 3 bytes were received"
        );
    }

    #[tokio::test]
    async fn stream_too_long() {
        let body = ManyFrameBody::new("abcdefghijk");
        let enforced = ContentLengthEnforcingBody::wrap(body, 5);
        let err = expect_body_error(enforced).await;
        assert_str_contains!(
            format!("{}", DisplayErrorContext(err)),
            "Expected 5 bytes but 11 bytes were received"
        );
    }

    #[tokio::test]
    async fn stream_just_right() {
        let body = ManyFrameBody::new("abcdefghijk");
        let enforced = ContentLengthEnforcingBody::wrap(body, 11);
        let data = enforced.collect().await.unwrap().to_bytes();
        assert_eq!(b"abcdefghijk", data.as_ref());
    }

    async fn expect_body_error(body: SdkBody) -> impl Error {
        ByteStream::new(body)
            .collect()
            .await
            .expect_err("body should have failed")
    }

    #[test]
    fn extract_header() {
        let mut resp1 = Response::new(200.try_into().unwrap(), ());
        resp1.headers_mut().insert(CONTENT_LENGTH, "123");
        assert_eq!(extract_content_length(&resp1).unwrap(), Some(123));
        resp1.headers_mut().append(CONTENT_LENGTH, "124");
        // duplicate content length header
        extract_content_length(&resp1).expect_err("duplicate headers");

        // not an integer
        resp1.headers_mut().insert(CONTENT_LENGTH, "-123.5");
        extract_content_length(&resp1).expect_err("not an integer");

        // not an integer
        resp1.headers_mut().insert(CONTENT_LENGTH, "");
        extract_content_length(&resp1).expect_err("empty");

        resp1.headers_mut().remove(CONTENT_LENGTH);
        assert_eq!(extract_content_length(&resp1).unwrap(), None);
    }
}