-
Notifications
You must be signed in to change notification settings - Fork 729
/
Redactor.cs
300 lines (266 loc) · 12.5 KB
/
Redactor.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
#if !NETCOREAPP3_1_OR_GREATER
using System.Buffers;
#endif
namespace Microsoft.Extensions.Compliance.Redaction;
/// <summary>
/// Enables the redaction of potentially sensitive data.
/// </summary>
public abstract class Redactor
{
#if NET6_0_OR_GREATER
private const int MaximumStackAllocation = 256;
#endif
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <param name="source">Value to redact.</param>
/// <returns>Redacted value.</returns>
public string Redact(ReadOnlySpan<char> source)
{
if (source.IsEmpty)
{
return string.Empty;
}
int length = GetRedactedLength(source);
#if NETCOREAPP3_1_OR_GREATER
unsafe
{
#pragma warning disable 8500
return string.Create(
length,
(this, (IntPtr)(&source)),
static (destination, state) => state.Item1.Redact(*(ReadOnlySpan<char>*)state.Item2, destination));
#pragma warning restore 8500
}
#else
var buffer = ArrayPool<char>.Shared.Rent(length);
try
{
var charsWritten = Redact(source, buffer);
var redactedString = new string(buffer, 0, charsWritten);
return redactedString;
}
finally
{
ArrayPool<char>.Shared.Return(buffer);
}
#endif
}
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <param name="source">Value to redact.</param>
/// <param name="destination">Buffer to store redacted value.</param>
/// <returns>Number of characters produced when redacting the given source input.</returns>
/// <exception cref="ArgumentException"><paramref name="destination"/> is too small.</exception>
public abstract int Redact(ReadOnlySpan<char> source, Span<char> destination);
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <param name="source">Value to redact.</param>
/// <param name="destination">Buffer to redact into.</param>
/// <remarks>
/// Returns 0 when <paramref name="source"/> is <see langword="null"/>.
/// </remarks>
/// <returns>Number of characters written to the buffer.</returns>
/// <exception cref="ArgumentException"><paramref name="destination"/> is too small.</exception>
public int Redact(string? source, Span<char> destination) => Redact(source.AsSpan(), destination);
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <param name="source">Value to redact.</param>
/// <returns>Redacted value.</returns>
/// <remarks>
/// Returns an empty string when <paramref name="source"/> is <see langword="null"/>.
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is <see langword="null"/>.</exception>
public virtual string Redact(string? source) => Redact(source.AsSpan());
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <typeparam name="T">Type of value to redact.</typeparam>
/// <param name="value">Value to redact.</param>
/// <param name="format">
/// The optional format that selects the specific formatting operation performed. Refer to the
/// documentation of the type being formatted to understand the values you can supply here.
/// </param>
/// <param name="provider">Format provider used to produce a string representing the value.</param>
/// <returns>Redacted value.</returns>
[SkipLocalsInit]
[SuppressMessage("Minor Code Smell", "S3247:Duplicate casts should not be made", Justification = "Avoid pattern matching to improve jitted code")]
public string Redact<T>(T value, string? format = null, IFormatProvider? provider = null)
{
#if NET6_0_OR_GREATER
if (value is ISpanFormattable)
{
Span<char> buffer = stackalloc char[MaximumStackAllocation];
// Stryker disable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
// Null forgiving operator: The null case is checked with default equality comparer, but compiler doesn't understand it.
if (((ISpanFormattable)value).TryFormat(buffer, out int written, format.AsSpan(), provider))
{
// Stryker enable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
var formatted = buffer.Slice(0, written);
int length = GetRedactedLength(formatted);
unsafe
{
#pragma warning disable 8500
return string.Create(
length,
(this, (IntPtr)(&formatted)),
static (destination, state) => state.Item1.Redact(*(ReadOnlySpan<char>*)state.Item2, destination));
#pragma warning restore 8500
}
}
}
#endif
if (value is IFormattable)
{
return Redact(((IFormattable)value).ToString(format, provider));
}
if (value is char[])
{
// An attempt to call value.ToString() on a char[] will produce a string "System.Char[]" and all redaction will be attempted on it,
// instead of the provided array. This will lead to incorrectly allocated buffers.
//
// NB: not using pattern matching as it is recognized by the JIT and since this is a generic type, the JIT ends up generating code
// without any of those conditional statements being present. But this only happens when not using pattern matching.
return Redact(((char[])(object)value).AsSpan());
}
return Redact(value?.ToString());
}
/// <summary>
/// Redacts potentially sensitive data.
/// </summary>
/// <typeparam name="T">Type of value to redact.</typeparam>
/// <param name="value">Value to redact.</param>
/// <param name="destination">Buffer to redact into.</param>
/// <param name="format">
/// The optional format string that selects the specific formatting operation performed. Refer to the
/// documentation of the type being formatted to understand the values you can supply here.
/// </param>
/// <param name="provider">Format provider used to produce a string representing the value.</param>
/// <returns>Number of characters written to the buffer.</returns>
/// <exception cref="ArgumentException"><paramref name="destination"/> is too small.</exception>
[SkipLocalsInit]
[SuppressMessage("Minor Code Smell", "S3247:Duplicate casts should not be made", Justification = "Avoid pattern matching to improve jitted code")]
public int Redact<T>(T value, Span<char> destination, string? format = null, IFormatProvider? provider = null)
{
#if NET6_0_OR_GREATER
if (value is ISpanFormattable)
{
Span<char> buffer = stackalloc char[MaximumStackAllocation];
// Stryker disable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
if (((ISpanFormattable)value).TryFormat(buffer, out int written, format.AsSpan(), provider))
{
// Stryker enable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
var formatted = buffer.Slice(0, written);
return Redact(formatted, destination);
}
}
#endif
if (value is IFormattable)
{
return Redact(((IFormattable)value).ToString(format, provider), destination);
}
if (value is char[])
{
// An attempt to call value.ToString() on a char[] will produce a string "System.Char[]" and all redaction will be attempted on it,
// instead of the provided array. This will lead to incorrectly allocated buffers.
//
// NB: not using pattern matching as it is recognized by the JIT and since this is a generic type, the JIT ends up generating code
// without any of those conditional statements being present. But this only happens when not using pattern matching.
return Redact(((char[])(object)value).AsSpan(), destination);
}
return Redact(value?.ToString(), destination);
}
/// <summary>
/// Tries to redact potentially sensitive data.
/// </summary>
/// <typeparam name="T">The type of value to redact.</typeparam>
/// <param name="value">The value to redact.</param>
/// <param name="destination">The buffer to redact into.</param>
/// <param name="charsWritten">When this method returns, contains the number of redacted characters that were written to the destination buffer.</param>
/// <param name="format">
/// The format string that selects the specific formatting operation performed. Refer to the
/// documentation of the type being formatted to understand the values you can supply here.
/// </param>
/// <param name="provider">The format provider used to produce a string representing the value.</param>
/// <returns><see langword="true"/> if the destination buffer was large enough, otherwise <see langword="false"/>.</returns>
[SkipLocalsInit]
[SuppressMessage("Minor Code Smell", "S3247:Duplicate casts should not be made", Justification = "Avoid pattern matching to improve jitted code")]
public bool TryRedact<T>(T value, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format, IFormatProvider? provider = null)
{
#if NET6_0_OR_GREATER
if (value is ISpanFormattable)
{
Span<char> buffer = stackalloc char[MaximumStackAllocation];
// Stryker disable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
if (((ISpanFormattable)value).TryFormat(buffer, out int written, format, provider))
{
// Stryker enable all : Cannot kill the mutant because the only difference is allocating buffer on stack or renting it.
var formatted = buffer.Slice(0, written);
int rlen = GetRedactedLength(formatted);
if (rlen > destination.Length)
{
charsWritten = 0;
return false;
}
charsWritten = Redact(formatted, destination);
return true;
}
}
#endif
ReadOnlySpan<char> ros = default;
if (value is IFormattable)
{
var fmt = format.Length > 0 ? format.ToString() : string.Empty;
var str = ((IFormattable)value).ToString(fmt, provider);
if (str != null)
{
ros = str.AsSpan();
}
}
else if (value is char[])
{
// An attempt to call value.ToString() on a char[] will produce the string "System.Char[]" and redaction will be attempted on it,
// instead of the provided array.
//
// Not using pattern matching as it is recognized by the JIT and since this is a generic type, the JIT ends up generating code
// without any of those conditional statements being present. But this only happens when not using pattern matching.
ros = ((char[])(object)value).AsSpan();
}
else
{
var str = value?.ToString();
if (str != null)
{
ros = str.AsSpan();
}
}
int len = GetRedactedLength(ros);
if (len > destination.Length)
{
charsWritten = 0;
return false;
}
charsWritten = Redact(ros, destination);
return true;
}
/// <summary>
/// Gets the number of characters produced by redacting the input.
/// </summary>
/// <param name="input">Value to be redacted.</param>
/// <returns>The number of characters produced by redacting the input.</returns>
public abstract int GetRedactedLength(ReadOnlySpan<char> input);
/// <summary>
/// Gets the number of characters produced by redacting the input.
/// </summary>
/// <param name="input">Value to be redacted.</param>
/// <returns>Minimum buffer size.</returns>
public int GetRedactedLength(string? input) => GetRedactedLength(input.AsSpan());
}