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
//! What a probe keeps out of its answer: every value it starts a server
//! with, so a server that echoes one, in its standard error, an error, or
//! its name, version or tools, does not show it to the client.
use std::sync::{Arc, Mutex, PoisonError};
/// The values a probe started a server with, which it keeps out of what it
/// returns. Clones share them. Not `Debug`: it holds secret values.
#[derive(Clone, Default)]
pub(super) struct Served(Arc<Mutex<Vec<Hidden>>>);
/// Where a value a server is given comes from, which says how it is hidden.
#[derive(Clone, Copy)]
pub(super) enum Origin {
/// A stored or typed-in secret: hidden wherever it occurs.
Secret,
/// The server's config: its `env` or `headers`, or a variable its
/// `env_from_env` or `headers_from_env` reads. Hidden wherever it
/// occurs, unless shorter than [`SHORT_VALUE_BYTES`].
Config,
}
/// One value kept out of the answer, and where.
struct Hidden {
text: String,
reach: Reach,
}
/// Where a value is hidden in what a server writes.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Reach {
/// Every place it occurs.
Anywhere,
/// Only where it stands alone, not inside a longer token: a short
/// config value such as `DEBUG=1`, which hidden everywhere would hide
/// every `1` the server wrote.
Alone,
}
/// The shortest config value hidden everywhere, and the shortest word of a
/// value hidden on its own. Credentials are longer: an AWS access key id is
/// 20 bytes, a GitHub token 40, a Stripe secret key over 30, so a key never
/// falls under it, while flags, ports, levels and auth schemes (`1`,
/// `true`, `8080`, `debug`, `Bearer`) do.
const SHORT_VALUE_BYTES: usize = 8;
impl Served {
/// Keeps `value`, one the server is given, out of the answer as its
/// `origin` says. A value of several words, such as an `Authorization`
/// header's `Bearer <token>`, also has each word of at least
/// [`SHORT_VALUE_BYTES`] hidden wherever it occurs, since a server may
/// echo the token alone.
pub(super) fn hide(&self, value: &str, origin: Origin) {
if value.is_empty() {
return;
}
let reach = match origin {
Origin::Config if value.len() < SHORT_VALUE_BYTES => Reach::Alone,
Origin::Secret | Origin::Config => Reach::Anywhere,
};
let words = value.split_whitespace().collect::<Vec<_>>();
let long_words = words
.iter()
.filter(|word| words.len() > 1 && word.len() >= SHORT_VALUE_BYTES)
.map(|word| Hidden {
text: (*word).to_owned(),
reach: Reach::Anywhere,
});
let mut kept = self.lock();
kept.push(Hidden {
text: value.to_owned(),
reach,
});
kept.extend(long_words);
}
/// `tail`, the end of a server's standard error, as text a person may
/// see, redacted as [`Self::redact`] does. When it was `cut` from a
/// longer output, a start that is the end of a value hidden anywhere,
/// whose beginning the cut dropped, is redacted too.
pub(super) fn tail_text(&self, tail: &[u8], cut: bool) -> Option<String> {
let tail = self.covered(tail, cut);
let text = String::from_utf8_lossy(&tail);
let text = text.trim();
(!text.is_empty()).then(|| text.to_owned())
}
/// `text` with each value kept out replaced by `[redacted]`. Every
/// place a value occurs is found first, overlapping ones included, so
/// two values that share bytes are both hidden whole.
pub(super) fn redact(&self, text: &str) -> String {
String::from_utf8_lossy(&self.covered(text.as_bytes(), /*cut*/ false)).into_owned()
}
/// `bytes` with each run that is part of a value kept out replaced by
/// one `[redacted]`: every occurrence of a value, or, for a short config
/// value, every one that stands alone, and, when `cut`, the longest
/// start that is the end of a value hidden anywhere.
fn covered(&self, bytes: &[u8], cut: bool) -> Vec<u8> {
let values = self.lock();
let mut hidden = vec![false; bytes.len()];
for kept in values.iter() {
let value = kept.text.as_bytes();
for start in 0..bytes.len() {
let end = start + value.len();
let alone = || {
!joins(bytes, start.checked_sub(1), start.checked_sub(2))
&& !joins(bytes, Some(end), Some(end + 1))
};
if bytes[start..].starts_with(value) && (kept.reach == Reach::Anywhere || alone()) {
hidden[start..end].fill(true);
}
}
if cut && kept.reach == Reach::Anywhere {
let fragment = (1..value.len())
.map(|from| &value[from..])
.find(|end| bytes.starts_with(end));
if let Some(end) = fragment {
hidden[..end.len()].fill(true);
}
}
}
let mut out = Vec::with_capacity(bytes.len());
for (index, &byte) in bytes.iter().enumerate() {
match (hidden[index], index > 0 && hidden[index - 1]) {
(false, _) => out.push(byte),
(true, false) => out.extend_from_slice(b"[redacted]"),
(true, true) => {}
}
}
out
}
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<Hidden>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
/// Whether the byte at `at`, beside a short value, makes it part of a
/// longer token: a letter, a digit or `_`, or a `.` or `-` with a letter or
/// digit at `beyond`, as in `1.0.0`, `127.0.0.1` or `v-1`. A `.` that ends
/// a sentence does not.
fn joins(bytes: &[u8], at: Option<usize>, beyond: Option<usize>) -> bool {
let byte = |index: Option<usize>| index.and_then(|index| bytes.get(index)).copied();
let word = |byte: u8| byte.is_ascii_alphanumeric() || byte == b'_';
match byte(at) {
Some(b'.' | b'-') => byte(beyond).is_some_and(word),
Some(other) => word(other),
None => false,
}
}
#[cfg(test)]
#[path = "probe_redaction_tests.rs"]
mod tests;