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

//! A wrapper around a path [`&str`](str) to allow for sensitivity.

use std::fmt::{Debug, Display, Error, Formatter};

use crate::instrumentation::{sensitivity::Sensitive, MakeFmt};

/// A wrapper around a path [`&str`](str) which modifies the behavior of [`Display`]. Specific path segments are marked
/// as sensitive by providing predicate over the segment index. This accommodates the [httpLabel trait] with
/// non-greedy labels.
///
/// The [`Display`] implementation will respect the `unredacted-logging` flag.
///
/// # Example
///
/// ```
/// # use aws_smithy_http_server::instrumentation::sensitivity::uri::Label;
/// # use http::Uri;
/// # let path = "";
/// // Path segment 2 is redacted and a trailing greedy label
/// let uri = Label::new(&path, |x| x == 2, None);
/// println!("{uri}");
/// ```
///
/// [httpLabel trait]: https://smithy.io/2.0/spec/http-bindings.html#httplabel-trait
#[allow(missing_debug_implementations)]
#[derive(Clone)]
pub struct Label<'a, F> {
    path: &'a str,
    label_marker: F,
    greedy_label: Option<GreedyLabel>,
}

/// Marks a segment as a greedy label up until a char offset from the end.
///
/// # Example
///
/// The pattern, `/alpha/beta/{greedy+}/trail`, has segment index 2 and offset from the end of 6.
///
/// ```rust
/// # use aws_smithy_http_server::instrumentation::sensitivity::uri::GreedyLabel;
/// let greedy_label = GreedyLabel::new(2, 6);
/// ```
#[derive(Clone, Debug)]
pub struct GreedyLabel {
    segment_index: usize,
    end_offset: usize,
}

impl GreedyLabel {
    /// Constructs a new [`GreedyLabel`] from a segment index and an offset from the end of the URI.
    pub fn new(segment_index: usize, end_offset: usize) -> Self {
        Self {
            segment_index,
            end_offset,
        }
    }
}

impl<'a, F> Label<'a, F> {
    /// Constructs a new [`Label`].
    pub fn new(path: &'a str, label_marker: F, greedy_label: Option<GreedyLabel>) -> Self {
        Self {
            path,
            label_marker,
            greedy_label,
        }
    }
}

impl<'a, F> Display for Label<'a, F>
where
    F: Fn(usize) -> bool,
{
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        if let Some(greedy_label) = &self.greedy_label {
            // Calculate the byte index of the start of the greedy label and whether it was reached while writing the
            // normal labels.
            // TODO(clippy): Switch from fold to try_fold
            #[allow(clippy::manual_try_fold)]
            let (greedy_start, greedy_hit) = self
                .path
                .split('/')
                // Skip the first segment which will always be empty.
                .skip(1)
                // Iterate up to the segment index given in the `GreedyLabel`.
                .take(greedy_label.segment_index + 1)
                .enumerate()
                .fold(Ok((0, false)), |acc, (index, segment)| {
                    acc.and_then(|(greedy_start, _)| {
                        if index == greedy_label.segment_index {
                            // We've hit the greedy label, set `hit_greedy` to `true`.
                            Ok((greedy_start, true))
                        } else {
                            // Prior to greedy segment, use `label_marker` to redact segments.
                            if (self.label_marker)(index) {
                                write!(f, "/{}", Sensitive(segment))?;
                            } else {
                                write!(f, "/{}", segment)?;
                            }
                            // Add the segment length and the separator to the `greedy_start`.
                            let greedy_start = greedy_start + segment.len() + 1;
                            Ok((greedy_start, false))
                        }
                    })
                })?;

            // If we reached the greedy label segment then use the `end_offset` to redact the interval
            // and print the remainder.
            if greedy_hit {
                if let Some(end_index) = self.path.len().checked_sub(greedy_label.end_offset) {
                    if greedy_start < end_index {
                        // [greedy_start + 1 .. end_index] is a non-empty slice - redact it.
                        let greedy_redaction = Sensitive(&self.path[greedy_start + 1..end_index]);
                        let remainder = &self.path[end_index..];
                        write!(f, "/{greedy_redaction}{remainder}")?;
                    } else {
                        // [greedy_start + 1 .. end_index] is an empty slice - don't redact it.
                        // NOTE: This is unreachable if the greedy label is valid.
                        write!(f, "{}", &self.path[greedy_start..])?;
                    }
                }
            } else {
                // NOTE: This is unreachable if the greedy label is valid.
            }
        } else {
            // Use `label_marker` to redact segments.
            for (index, segment) in self
                .path
                .split('/')
                // Skip the first segment which will always be empty.
                .skip(1)
                .enumerate()
            {
                if (self.label_marker)(index) {
                    write!(f, "/{}", Sensitive(segment))?;
                } else {
                    write!(f, "/{}", segment)?;
                }
            }
        }

        Ok(())
    }
}

/// A [`MakeFmt`] producing [`Label`].
#[derive(Clone)]
pub struct MakeLabel<F> {
    pub(crate) label_marker: F,
    pub(crate) greedy_label: Option<GreedyLabel>,
}

impl<F> Debug for MakeLabel<F> {
    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
        f.debug_struct("MakeLabel")
            .field("greedy_label", &self.greedy_label)
            .finish_non_exhaustive()
    }
}

impl<'a, F> MakeFmt<&'a str> for MakeLabel<F>
where
    F: Clone,
{
    type Target = Label<'a, F>;

    fn make(&self, path: &'a str) -> Self::Target {
        Label::new(path, self.label_marker.clone(), self.greedy_label.clone())
    }
}

#[cfg(test)]
mod tests {
    use http::Uri;

    use crate::instrumentation::sensitivity::uri::{tests::EXAMPLES, GreedyLabel};

    use super::Label;

    #[test]
    fn mark_none() {
        let originals = EXAMPLES.into_iter().map(Uri::from_static);
        for original in originals {
            let expected = original.path().to_string();
            let output = Label::new(original.path(), |_| false, None).to_string();
            assert_eq!(output, expected, "original = {original}");
        }
    }

    #[cfg(not(feature = "unredacted-logging"))]
    const ALL_EXAMPLES: [&str; 19] = [
        "g:h",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}",
        "http://a/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}",
        "http://a/{redacted}/{redacted}",
        "http://a/{redacted}",
    ];

    #[cfg(feature = "unredacted-logging")]
    pub const ALL_EXAMPLES: [&str; 19] = EXAMPLES;

    #[test]
    fn mark_all() {
        let originals = EXAMPLES.into_iter().map(Uri::from_static);
        let expecteds = ALL_EXAMPLES.into_iter().map(Uri::from_static);
        for (original, expected) in originals.zip(expecteds) {
            let output = Label::new(original.path(), |_| true, None).to_string();
            assert_eq!(output, expected.path(), "original = {original}");
        }
    }

    #[cfg(not(feature = "unredacted-logging"))]
    pub const GREEDY_EXAMPLES: [&str; 19] = [
        "g:h",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}",
        "http://a/g",
        "http://g",
        "http://a/b/{redacted}?y",
        "http://a/b/{redacted}?y",
        "http://a/b/{redacted}?q#s",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}?y#s",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}?y#s",
        "http://a/b/{redacted}?q",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}",
        "http://a/b/{redacted}",
        "http://a/",
    ];

    #[cfg(feature = "unredacted-logging")]
    pub const GREEDY_EXAMPLES: [&str; 19] = EXAMPLES;

    #[test]
    fn greedy() {
        let originals = EXAMPLES.into_iter().map(Uri::from_static);
        let expecteds = GREEDY_EXAMPLES.into_iter().map(Uri::from_static);
        for (original, expected) in originals.zip(expecteds) {
            let output = Label::new(original.path(), |_| false, Some(GreedyLabel::new(1, 0))).to_string();
            assert_eq!(output, expected.path(), "original = {original}");
        }
    }

    #[cfg(not(feature = "unredacted-logging"))]
    pub const GREEDY_EXAMPLES_OFFSET: [&str; 19] = [
        "g:h",
        "http://a/b/{redacted}g",
        "http://a/b/{redacted}/",
        "http://a/g",
        "http://g",
        "http://a/b/{redacted}p?y",
        "http://a/b/{redacted}g?y",
        "http://a/b/{redacted}p?q#s",
        "http://a/b/{redacted}g",
        "http://a/b/{redacted}g?y#s",
        "http://a/b/{redacted}x",
        "http://a/b/{redacted}x",
        "http://a/b/{redacted}x?y#s",
        "http://a/b/{redacted}p?q",
        "http://a/b/{redacted}/",
        "http://a/b/{redacted}/",
        "http://a/b/",
        "http://a/b/{redacted}g",
        "http://a/",
    ];

    #[cfg(feature = "unredacted-logging")]
    pub const GREEDY_EXAMPLES_OFFSET: [&str; 19] = EXAMPLES;

    #[test]
    fn greedy_offset_a() {
        let originals = EXAMPLES.into_iter().map(Uri::from_static);
        let expecteds = GREEDY_EXAMPLES_OFFSET.into_iter().map(Uri::from_static);
        for (original, expected) in originals.zip(expecteds) {
            let output = Label::new(original.path(), |_| false, Some(GreedyLabel::new(1, 1))).to_string();
            assert_eq!(output, expected.path(), "original = {original}");
        }
    }

    const EXTRA_EXAMPLES_UNREDACTED: [&str; 4] = [
        "http://base/a/b/hello_world",
        "http://base/a/b/c/hello_world",
        "http://base/a",
        "http://base/a/b/c",
    ];

    #[cfg(feature = "unredacted-logging")]
    const EXTRA_EXAMPLES_REDACTED: [&str; 4] = EXTRA_EXAMPLES_UNREDACTED;
    #[cfg(not(feature = "unredacted-logging"))]
    const EXTRA_EXAMPLES_REDACTED: [&str; 4] = [
        "http://base/a/b/{redacted}world",
        "http://base/a/b/{redacted}world",
        "http://base/a",
        "http://base/a/b/c",
    ];

    #[test]
    fn greedy_offset_b() {
        let originals = EXTRA_EXAMPLES_UNREDACTED.into_iter().map(Uri::from_static);
        let expecteds = EXTRA_EXAMPLES_REDACTED.into_iter().map(Uri::from_static);
        for (original, expected) in originals.zip(expecteds) {
            let output = Label::new(original.path(), |_| false, Some(GreedyLabel::new(2, 5))).to_string();
            assert_eq!(output, expected.path(), "original = {original}");
        }
    }
}