aws_sdk_secretsmanager/
json_errors.rs

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
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/*
 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
 * SPDX-License-Identifier: Apache-2.0
 */

use aws_smithy_json::deserialize::token::skip_value;
use aws_smithy_json::deserialize::{error::DeserializeError, json_token_iter, Token};
use aws_smithy_runtime_api::http::Headers;
use aws_smithy_types::error::metadata::{Builder as ErrorMetadataBuilder, ErrorMetadata};
use std::borrow::Cow;

// currently only used by AwsJson
#[allow(unused)]
pub fn is_error<B>(response: &http::Response<B>) -> bool {
    !response.status().is_success()
}

fn sanitize_error_code(error_code: &str) -> &str {
    // Trim a trailing URL from the error code, beginning with a `:`
    let error_code = match error_code.find(':') {
        Some(idx) => &error_code[..idx],
        None => error_code,
    };

    // Trim a prefixing namespace from the error code, beginning with a `#`
    match error_code.find('#') {
        Some(idx) => &error_code[idx + 1..],
        None => error_code,
    }
}

struct ErrorBody<'a> {
    code: Option<Cow<'a, str>>,
    message: Option<Cow<'a, str>>,
}

fn parse_error_body(bytes: &[u8]) -> Result<ErrorBody, DeserializeError> {
    let mut tokens = json_token_iter(bytes).peekable();
    let (mut typ, mut code, mut message) = (None, None, None);
    if let Some(Token::StartObject { .. }) = tokens.next().transpose()? {
        loop {
            match tokens.next().transpose()? {
                Some(Token::EndObject { .. }) => break,
                Some(Token::ObjectKey { key, .. }) => {
                    if let Some(Ok(Token::ValueString { value, .. })) = tokens.peek() {
                        match key.as_escaped_str() {
                            "code" => code = Some(value.to_unescaped()?),
                            "__type" => typ = Some(value.to_unescaped()?),
                            "message" | "Message" | "errorMessage" => message = Some(value.to_unescaped()?),
                            _ => {}
                        }
                    }
                    skip_value(&mut tokens)?;
                }
                _ => return Err(DeserializeError::custom("expected object key or end object")),
            }
        }
        if tokens.next().is_some() {
            return Err(DeserializeError::custom("found more JSON tokens after completing parsing"));
        }
    }
    Ok(ErrorBody { code: code.or(typ), message })
}

pub fn parse_error_metadata(payload: &[u8], headers: &Headers) -> Result<ErrorMetadataBuilder, DeserializeError> {
    let ErrorBody { code, message } = parse_error_body(payload)?;

    let mut err_builder = ErrorMetadata::builder();
    if let Some(code) = headers.get("x-amzn-errortype").or(code.as_deref()).map(sanitize_error_code) {
        err_builder = err_builder.code(code);
    }
    if let Some(message) = message {
        err_builder = err_builder.message(message);
    }
    Ok(err_builder)
}

#[cfg(test)]
mod test {
    use crate::json_errors::{parse_error_body, parse_error_metadata, sanitize_error_code};
    use aws_smithy_runtime_api::client::orchestrator::HttpResponse;
    use aws_smithy_types::{body::SdkBody, error::ErrorMetadata};
    use std::borrow::Cow;

    #[test]
    fn error_metadata() {
        let response = HttpResponse::try_from(
            http::Response::builder()
                .body(SdkBody::from(r#"{ "__type": "FooError", "message": "Go to foo" }"#))
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            parse_error_metadata(response.body().bytes().unwrap(), response.headers())
                .unwrap()
                .build(),
            ErrorMetadata::builder().code("FooError").message("Go to foo").build()
        )
    }

    #[test]
    fn error_type() {
        assert_eq!(
            Some(Cow::Borrowed("FooError")),
            parse_error_body(br#"{ "__type": "FooError" }"#).unwrap().code
        );
    }

    #[test]
    fn code_takes_priority() {
        assert_eq!(
            Some(Cow::Borrowed("BarError")),
            parse_error_body(br#"{ "code": "BarError", "__type": "FooError" }"#).unwrap().code
        );
    }

    #[test]
    fn ignore_unrecognized_fields() {
        assert_eq!(
            Some(Cow::Borrowed("FooError")),
            parse_error_body(br#"{ "__type": "FooError", "asdf": 5, "fdsa": {}, "foo": "1" }"#)
                .unwrap()
                .code
        );
    }

    #[test]
    fn sanitize_namespace_and_url() {
        assert_eq!(
            sanitize_error_code("aws.protocoltests.restjson#FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/"),
            "FooError"
        );
    }

    #[test]
    fn sanitize_noop() {
        assert_eq!(sanitize_error_code("FooError"), "FooError");
    }

    #[test]
    fn sanitize_url() {
        assert_eq!(
            sanitize_error_code("FooError:http://internal.amazon.com/coral/com.amazon.coral.validate/"),
            "FooError"
        );
    }

    #[test]
    fn sanitize_namespace() {
        assert_eq!(sanitize_error_code("aws.protocoltests.restjson#FooError"), "FooError");
    }

    // services like lambda use an alternate `Message` instead of `message`
    #[test]
    fn alternative_error_message_names() {
        let response = HttpResponse::try_from(
            http::Response::builder()
                .header("x-amzn-errortype", "ResourceNotFoundException")
                .body(SdkBody::from(
                    r#"{
                    "Type": "User",
                    "Message": "Functions from 'us-west-2' are not reachable from us-east-1"
                }"#,
                ))
                .unwrap(),
        )
        .unwrap();
        assert_eq!(
            parse_error_metadata(response.body().bytes().unwrap(), response.headers())
                .unwrap()
                .build(),
            ErrorMetadata::builder()
                .code("ResourceNotFoundException")
                .message("Functions from 'us-west-2' are not reachable from us-east-1")
                .build()
        );
    }
}