Your Provider Payload Is Clean. Your Logs Aren't: 5 Redaction Mistakes in .NET LLM Pipelines
Most teams test PII redaction in an LLM app the same way: send a prompt with a card number, look at what the provider received, see [CARD], ship it. That check is real, but it only covers one of the places the prompt go
Most teams test PII redaction in an LLM app the same way: send a prompt with a card number, look at what the provider received, see [CARD], ship it.
That check is real, but it only covers one of the places the prompt goes. Before the request leaves your process it also passes your logging, your telemetry, and sometimes an error path that echoes it back. I built a small canary harness that plants fake card numbers, emails, IBANs and API keys in eight scenarios and then reads four sinks: the provider payload, ILogger output, OpenTelemetry spans and the error body. Of six pipeline variants, one came back clean everywhere.
This post is the five mistakes the other five variants made, not the full harness.
Tech Skill Builder is $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10. Join Tech Skill Builder. The complete, tested canary-test project behind this post is in there.
Need the masking side in production? My LLM Data Firewall for .NET 10 is
IChatClientmiddleware that redacts or blocks sensitive values before the request leaves your process and audits counts only.
Mistake 1: Only checking what the provider received
This is the one that fools people, because the check passes. In my run, the variant with the redactor sitting right next to the provider had a clean provider payload in 8 of 8 scenarios. The logs and the spans still held the raw card in 8 of 8.
Nothing was broken in the redactor. The logging and telemetry clients simply saw the request before it was masked.
Fix: treat "what the model saw" as one sink of several. Your test should read every place a prompt can be written down, not just the wire.
Mistake 2: Adding the redactor last in ChatClientBuilder
ChatClientBuilder applies its middleware in reverse: the first thing you add is the outermost client. So the intuitive "add redaction at the end, right before the provider" puts it inside logging and OpenTelemetry.
The shape that came out clean looks like this:
// First added = outermost. Redaction must wrap everything that records the request.
var client = new ChatClientBuilder(provider)
.Use(inner => new RedactingChatClient(inner, options)) // 1. mask first
.UseOpenTelemetry(loggerFactory, sourceName) // 2. spans see masked text
.UseLogging(loggerFactory) // 3. logs see masked text
.Build();
// RedactingChatClient : DelegatingChatClient
// - copies the messages (never mutates the caller's list)
// - masks text and tool content, then calls base.GetResponseAsync(...)
// full implementation in the complete project
Bonus trap: the "debug" switches. LoggingChatClient only logs message content at Trace, and OpenTelemetry content capture is off unless EnableSensitiveData is set (or the OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT env var is true). With both turned on and no redaction in front, the card showed up in the payload, logs and spans in every single scenario. Turning them on "just to debug one prompt" changes what every downstream system stores.
Mistake 3: Testing with canaries your redactor is right to ignore
A good redactor doesn't mask every 16-digit number, or it would eat order ids too. It finds candidates with a pattern and then validates them (Luhn for cards, mod-97 for IBANs). So if your test plants 1234567812345678, a correct redactor leaves it alone and your test tells you nothing.
The canary has to pass the same checks production code runs:
public sealed record Canary(string Id, CanaryKind Kind, string Value)
{
// A logged canary prints its id and kind, never the value.
public override string ToString() => $"{Kind}:{Id}";
}
public static class CanaryFactory
{
// Seeded, so a failing run can be replayed exactly.
public static Canary Card(Random rng) =>
/* 15 random digits starting with 4, then Luhn.CheckDigit(...) */
throw new NotImplementedException(); // full implementation in the complete project
public static Canary Iban(Random rng) => /* passes ISO 13616 mod-97 */ throw new NotImplementedException();
public static Canary Email(Random rng) => /* canary.<id>@example.test */ throw new NotImplementedException();
}
And scan for more than the exact string. Values get reformatted on the way to a log, so my scanner also looks for the grouped (4111 1111 ...), dashed, percent-encoded, Base64 and upper-case forms of each canary.
Mistake 4: Masking only TextContent
One variant had the redactor in the right place but only masked plain text. Seven of eight scenarios were clean. The eighth was a tool call that returned a customer record, and the email and card inside the FunctionResultContent reached the provider, the logs and the spans.
In an agent loop that's not an edge case. A lookup tool returns a customer, and that record goes back to the model on the next round.
private AIContent RedactContent(AIContent content) => content switch
{
TextContent t => /* mask t.Text */ ...,
FunctionResultContent r when _options.ScanToolContent => /* mask r.Result */ ...,
FunctionCallContent c when _options.ScanToolContent => /* mask each argument */ ...,
_ => content,
};
// "..." parts omitted; full implementation in the complete project
Mistake 5: Logging the raw request in your own handler
The last variant had a perfect pipeline and one extra line in the endpoint:
logger.LogInformation("Chat request: {Text}", text); // the leak
Provider payload, spans and error body: clean. Application logs: the card in 8 of 8 scenarios. Middleware can't mask a line it never sees. The fix belongs in the handler (log a length or a request id), and a wire-only check will never find this one.
Same family: the error path. My fake provider rejects one request with an error that echoes the input (a simulation of providers that quote offending text in a 4xx, not a claim about any vendor). With no redaction, that message landed in the logs via LogError(ex, ...) and in the error body. When the provider only ever sees masked text, even its echo is masked.
How to know your test isn't lying
A clean matrix is only worth something if the test could fail. Two cheap checks:
- Mutate it. I switched the tool-result guard off; 12 tests failed. Restored it, green again.
- Prove capture happened. Assert that every sink actually recorded characters in every scenario, so "0 leaks" can't mean "0 bytes captured".
And be honest about scope: a clean run proves these planted values, in these shapes, didn't reach these sinks through this pipeline. Regex detectors won't find names or street addresses, images and files pass through untouched, and the model's reply and streamed chunks are a separate problem.
Checklist
- [ ] Redactor added first in
ChatClientBuilder - [ ] Test reads provider payload, logs, spans and error body
- [ ] Canaries pass Luhn / mod-97, generated from a seed, never real data
- [ ] Scanner checks grouped, dashed, encoded and upper-case forms
- [ ] Tool calls and tool results are scanned
- [ ] No raw prompt in your own log lines
- [ ]
Tracecontent logging andEnableSensitiveDataoff outside local debugging - [ ] Mutation check + "sink captured something" assertion
- [ ] Runs offline in CI on every build
All numbers are from a local, offline run (seed 1) with a fake provider on my machine.
Get the complete project
The snippets above are the skeleton. The full, tested .NET 10 project is in Tech Skill Builder: the canary harness with eight scenarios, six pipeline variants and four sinks, the validating redactor, a CI command that fails the build on a leak, 133 passing tests, and a long PDF walkthrough with architecture and request-flow diagrams. It's $5/month for a very limited time only (normally $10). Grab it now before it goes back to $10.
Want the production masking layer instead of building it? The LLM Data Firewall for .NET 10 redacts or blocks sensitive values in an IChatClient middleware and keeps count-only audit logs.
Where would a planted card number show up in your app today?
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.