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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use std::borrow::Cow;
use std::fmt;

use http_02x::header::{HeaderName, HeaderValue, InvalidHeaderValue, USER_AGENT};

use aws_smithy_runtime::client::sdk_feature::SmithySdkFeature;
use aws_smithy_runtime_api::box_error::BoxError;
use aws_smithy_runtime_api::client::http::HttpClient;
use aws_smithy_runtime_api::client::interceptors::context::{
    BeforeTransmitInterceptorContextMut, BeforeTransmitInterceptorContextRef,
};
use aws_smithy_runtime_api::client::interceptors::Intercept;
use aws_smithy_runtime_api::client::runtime_components::RuntimeComponents;
use aws_smithy_types::config_bag::ConfigBag;
use aws_types::app_name::AppName;
use aws_types::os_shim_internal::Env;

use crate::user_agent::metrics::ProvideBusinessMetric;
use crate::user_agent::{AdditionalMetadata, ApiMetadata, AwsUserAgent, InvalidMetadataValue};

#[allow(clippy::declare_interior_mutable_const)] // we will never mutate this
const X_AMZ_USER_AGENT: HeaderName = HeaderName::from_static("x-amz-user-agent");

#[derive(Debug)]
enum UserAgentInterceptorError {
    MissingApiMetadata,
    InvalidHeaderValue(InvalidHeaderValue),
    InvalidMetadataValue(InvalidMetadataValue),
}

impl std::error::Error for UserAgentInterceptorError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidHeaderValue(source) => Some(source),
            Self::InvalidMetadataValue(source) => Some(source),
            Self::MissingApiMetadata => None,
        }
    }
}

impl fmt::Display for UserAgentInterceptorError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidHeaderValue(_) => "AwsUserAgent generated an invalid HTTP header value. This is a bug. Please file an issue.",
            Self::InvalidMetadataValue(_) => "AwsUserAgent generated an invalid metadata value. This is a bug. Please file an issue.",
            Self::MissingApiMetadata => "The UserAgentInterceptor requires ApiMetadata to be set before the request is made. This is a bug. Please file an issue.",
        })
    }
}

impl From<InvalidHeaderValue> for UserAgentInterceptorError {
    fn from(err: InvalidHeaderValue) -> Self {
        UserAgentInterceptorError::InvalidHeaderValue(err)
    }
}

impl From<InvalidMetadataValue> for UserAgentInterceptorError {
    fn from(err: InvalidMetadataValue) -> Self {
        UserAgentInterceptorError::InvalidMetadataValue(err)
    }
}

/// Generates and attaches the AWS SDK's user agent to a HTTP request
#[non_exhaustive]
#[derive(Debug, Default)]
pub struct UserAgentInterceptor;

impl UserAgentInterceptor {
    /// Creates a new `UserAgentInterceptor`
    pub fn new() -> Self {
        UserAgentInterceptor
    }
}

fn header_values(
    ua: &AwsUserAgent,
) -> Result<(HeaderValue, HeaderValue), UserAgentInterceptorError> {
    // Pay attention to the extremely subtle difference between ua_header and aws_ua_header below...
    Ok((
        HeaderValue::try_from(ua.ua_header())?,
        HeaderValue::try_from(ua.aws_ua_header())?,
    ))
}

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

    fn read_after_serialization(
        &self,
        _context: &BeforeTransmitInterceptorContextRef<'_>,
        _runtime_components: &RuntimeComponents,
        cfg: &mut ConfigBag,
    ) -> Result<(), BoxError> {
        // Allow for overriding the user agent by an earlier interceptor (so, for example,
        // tests can use `AwsUserAgent::for_tests()`) by attempting to grab one out of the
        // config bag before creating one.
        if cfg.load::<AwsUserAgent>().is_some() {
            return Ok(());
        }

        let api_metadata = cfg
            .load::<ApiMetadata>()
            .ok_or(UserAgentInterceptorError::MissingApiMetadata)?;
        let mut ua = AwsUserAgent::new_from_environment(Env::real(), api_metadata.clone());

        let maybe_app_name = cfg.load::<AppName>();
        if let Some(app_name) = maybe_app_name {
            ua.set_app_name(app_name.clone());
        }

        cfg.interceptor_state().store_put(ua);

        Ok(())
    }

    fn modify_before_signing(
        &self,
        context: &mut BeforeTransmitInterceptorContextMut<'_>,
        runtime_components: &RuntimeComponents,
        cfg: &mut ConfigBag,
    ) -> Result<(), BoxError> {
        let mut ua = cfg
            .load::<AwsUserAgent>()
            .expect("`AwsUserAgent should have been created in `read_before_execution`")
            .clone();

        let smithy_sdk_features = cfg.load::<SmithySdkFeature>();
        for smithy_sdk_feature in smithy_sdk_features {
            smithy_sdk_feature
                .provide_business_metric()
                .map(|m| ua.add_business_metric(m));
        }

        let maybe_connector_metadata = runtime_components
            .http_client()
            .and_then(|c| c.connector_metadata());
        if let Some(connector_metadata) = maybe_connector_metadata {
            let am = AdditionalMetadata::new(Cow::Owned(connector_metadata.to_string()))?;
            ua.add_additional_metadata(am);
        }

        let headers = context.request_mut().headers_mut();
        let (user_agent, x_amz_user_agent) = header_values(&ua)?;
        headers.append(USER_AGENT, user_agent);
        headers.append(X_AMZ_USER_AGENT, x_amz_user_agent);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use aws_smithy_runtime_api::client::interceptors::context::{Input, InterceptorContext};
    use aws_smithy_runtime_api::client::interceptors::Intercept;
    use aws_smithy_runtime_api::client::orchestrator::HttpRequest;
    use aws_smithy_runtime_api::client::runtime_components::RuntimeComponentsBuilder;
    use aws_smithy_types::config_bag::{ConfigBag, Layer};
    use aws_smithy_types::error::display::DisplayErrorContext;

    fn expect_header<'a>(context: &'a InterceptorContext, header_name: &str) -> &'a str {
        context
            .request()
            .expect("request is set")
            .headers()
            .get(header_name)
            .unwrap()
    }

    fn context() -> InterceptorContext {
        let mut context = InterceptorContext::new(Input::doesnt_matter());
        context.enter_serialization_phase();
        context.set_request(HttpRequest::empty());
        let _ = context.take_input();
        context.enter_before_transmit_phase();
        context
    }

    #[test]
    fn test_overridden_ua() {
        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = context();

        let mut layer = Layer::new("test");
        layer.store_put(AwsUserAgent::for_tests());
        layer.store_put(ApiMetadata::new("unused", "unused"));
        let mut cfg = ConfigBag::of_layers(vec![layer]);

        let interceptor = UserAgentInterceptor::new();
        let mut ctx = Into::into(&mut context);
        interceptor
            .modify_before_signing(&mut ctx, &rc, &mut cfg)
            .unwrap();

        let header = expect_header(&context, "user-agent");
        assert_eq!(AwsUserAgent::for_tests().ua_header(), header);
        assert!(!header.contains("unused"));

        assert_eq!(
            AwsUserAgent::for_tests().aws_ua_header(),
            expect_header(&context, "x-amz-user-agent")
        );
    }

    #[test]
    fn test_default_ua() {
        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = context();

        let api_metadata = ApiMetadata::new("some-service", "some-version");
        let mut layer = Layer::new("test");
        layer.store_put(api_metadata.clone());
        let mut config = ConfigBag::of_layers(vec![layer]);

        let interceptor = UserAgentInterceptor::new();
        let ctx = Into::into(&context);
        interceptor
            .read_after_serialization(&ctx, &rc, &mut config)
            .unwrap();
        let mut ctx = Into::into(&mut context);
        interceptor
            .modify_before_signing(&mut ctx, &rc, &mut config)
            .unwrap();

        let expected_ua = AwsUserAgent::new_from_environment(Env::real(), api_metadata);
        assert!(
            expected_ua.aws_ua_header().contains("some-service"),
            "precondition"
        );
        assert_eq!(
            expected_ua.ua_header(),
            expect_header(&context, "user-agent")
        );
        assert_eq!(
            expected_ua.aws_ua_header(),
            expect_header(&context, "x-amz-user-agent")
        );
    }

    #[test]
    fn test_app_name() {
        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = context();

        let api_metadata = ApiMetadata::new("some-service", "some-version");
        let mut layer = Layer::new("test");
        layer.store_put(api_metadata);
        layer.store_put(AppName::new("my_awesome_app").unwrap());
        let mut config = ConfigBag::of_layers(vec![layer]);

        let interceptor = UserAgentInterceptor::new();
        let ctx = Into::into(&context);
        interceptor
            .read_after_serialization(&ctx, &rc, &mut config)
            .unwrap();
        let mut ctx = Into::into(&mut context);
        interceptor
            .modify_before_signing(&mut ctx, &rc, &mut config)
            .unwrap();

        let app_value = "app/my_awesome_app";
        let header = expect_header(&context, "user-agent");
        assert!(
            !header.contains(app_value),
            "expected `{header}` to not contain `{app_value}`"
        );

        let header = expect_header(&context, "x-amz-user-agent");
        assert!(
            header.contains(app_value),
            "expected `{header}` to contain `{app_value}`"
        );
    }

    #[test]
    fn test_api_metadata_missing() {
        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let context = context();
        let mut config = ConfigBag::base();

        let interceptor = UserAgentInterceptor::new();
        let ctx = Into::into(&context);

        let error = format!(
            "{}",
            DisplayErrorContext(
                &*interceptor
                    .read_after_serialization(&ctx, &rc, &mut config)
                    .expect_err("it should error")
            )
        );
        assert!(
            error.contains("This is a bug"),
            "`{error}` should contain message `This is a bug`"
        );
    }

    #[test]
    fn test_api_metadata_missing_with_ua_override() {
        let rc = RuntimeComponentsBuilder::for_tests().build().unwrap();
        let mut context = context();

        let mut layer = Layer::new("test");
        layer.store_put(AwsUserAgent::for_tests());
        let mut config = ConfigBag::of_layers(vec![layer]);

        let interceptor = UserAgentInterceptor::new();
        let mut ctx = Into::into(&mut context);

        interceptor
            .modify_before_signing(&mut ctx, &rc, &mut config)
            .expect("it should succeed");

        let header = expect_header(&context, "user-agent");
        assert_eq!(AwsUserAgent::for_tests().ua_header(), header);
        assert!(!header.contains("unused"));

        assert_eq!(
            AwsUserAgent::for_tests().aws_ua_header(),
            expect_header(&context, "x-amz-user-agent")
        );
    }
}