Preventing data leakage in .NET AI features: data minimisation and redaction before prompts, tenant and ACL isolation in vector indexes, safe prompt and response logging with Microsoft.Extensions.Compliance.Redaction, provider data handling (Azure OpenAI residency, abuse-monitoring retention), output filtering, and Privacy Act 1988 obligations (APP 6, 8, 11, NDB, automated-decision transparency).
Treat every prompt, index and log as a copy of your data with its own access controls. Minimise and redact personal information before it goes into a prompt. In RAG, enforce tenant and permission filters inside the search query (or separate indexes); never trust the model to withhold something it was given. Logs and traces are the leak people forget: don't capture prompt content by default, and redact and limit retention when you do.
Know where the provider processes and stores data: deployment region, Global vs regional deployments, and abuse-monitoring retention. Map it to the Privacy Act: APP 6 purpose, APP 8 cross-border, APP 11 security, the NDB scheme, and automated-decision transparency from December 2026. The trade-off: more context improves answers but widens what can leak.
"I start from one rule: anything I put in a prompt, an index or a log is a new copy of the data and needs the same controls as the original. Then I look at four leak paths. First, the prompt: I send only what the task needs, and I redact or pseudonymise names, emails, phone numbers and identifiers like TFNs or Medicare numbers before they reach the model, mapping them back afterwards if the answer needs them. Second, retrieval: in a multi-tenant RAG system the tenant id and the user's groups are filters inside the vector query, applied before ranking, and when a user loses access or a document is deleted, the index catches up within minutes, not at the next full rebuild.
Third, telemetry. OpenTelemetry for generative AI can capture full prompts and responses, and that turns Application Insights into a database of customer conversations. For example, on [a customer-service assistant] we [found prompt content with customers' addresses in traces retained for 90 days]. I [turned content capture off by default, added redaction with Microsoft.Extensions.Compliance.Redaction for the sampled debug logs, and cut retention to 14 days], which removed [about 2 million] stored conversations from logs. Fourth, the provider: I pick a Standard deployment in Australia East where residency matters, confirm customer data isn't used for training, and account for abuse-monitoring retention in the privacy impact assessment.
The mistake I see is trusting the model to keep secrets: 'don't reveal other customers' data' in the system prompt. If the data is in the context, assume it can come out. Under the Privacy Act that's an APP 11 failure and possibly a notifiable breach. Keep data out of the context unless the user is entitled to see it, and the model can't leak it."
| Leak path | Example | Control |
|---|---|---|
| Prompt content | Full customer record pasted into context | Minimise fields; redact or pseudonymise |
| Retrieval | Other tenant's chunk retrieved | Filter in the query; per-tenant index for strict isolation |
| Stale permissions | Ex-employee's access still in the index | Sync ACLs and deletes; reconciliation job |
| Model output | Answer repeats PII from context or training data | Output PII scan; don't put unentitled data in context |
| Logs and traces | Prompt and response captured in telemetry | Content capture off by default; redaction; short retention |
| Caches | Cached answer served to another user | Cache key includes tenant and user scope |
| Provider | Processing outside Australia; retention for abuse monitoring | Region and deployment type; contract terms; PIA |
| Developer tools | Production data pasted into a coding assistant | AI usage policy; synthetic data |
| Obligation | What it means for an AI feature |
|---|---|
| APP 3 / APP 6 | Use personal information only for the purpose it was collected (or a related one the person would expect) |
| APP 8 | Disclosing to an overseas provider makes you accountable; know where processing happens |
| APP 11 | Reasonable security; destroy or de-identify when no longer needed (indexes, logs, caches too) |
| NDB scheme | Cross-tenant exposure likely to cause serious harm is an eligible data breach: assess within 30 days, notify the OAIC and individuals |
| APP 1 (from 10 Dec 2026) | Privacy policy must describe substantially automated decisions that use personal information and significantly affect individuals |
On [a multi-tenant B2B assistant with about 400 customer organisations], moving the tenant filter into the vector query, adding cross-tenant tests in CI and disabling prompt capture in traces took cross-tenant retrievals in our test suite from [3 of 500] to [0], and reduced the personal information held in logs by [over 95%].
Checks that the candidate sees every AI data copy as a leak path and knows the Australian legal context.
Green flags
Red flags
source systems ─► ingestion ─► vector index (copy #1)
│
user ─► API ─► prompt builder ─► model provider (copy #2: processing, abuse-monitoring retention)
│ │ │
│ └─► traces/logs (copy #3) └─► response ─► cache (copy #4) ─► UI
└─► conversation history store (copy #5)
Each copy needs access control, retention and deletion, and each can leak.
| Pattern | Isolation | Cost |
|---|---|---|
| Shared index + mandatory filter field | Logical; one missed filter leaks | Cheapest |
| Index (or collection) per tenant | Strong; mistakes fail closed | More indexes to manage |
| Separate service per tenant | Strongest | Highest |
With a shared index, enforce the filter in one repository method that every query must go through, and test it.
[EMAIL]). Safe, but the model loses the value.PERSON_1) and keep the mapping server-side; restore in the response. The model can still reason about "PERSON_1 emailed PERSON_2".Microsoft.Extensions.Compliance.Redaction classifies data with attributes and redacts it in logs ([PrivateData]-style taxonomies, ErasingRedactor, HmacRedactor).The OpenTelemetry GenAI semantic conventions define spans with model, token counts and optional message content. Microsoft.Extensions.AI's UseOpenTelemetry() has an EnableSensitiveData option that is off by default; keep it off in production. Capture content only in sampled, redacted, short-retention debug logs.
If a cross-tenant leak happens: contain (disable the feature), assess within 30 days whether serious harm is likely, notify the OAIC and affected individuals if it is an eligible data breach, and fix the root cause.
EnableSensitiveData in a dev environment and look at what lands in traces; then turn it off.Pseudonymise before the prompt, restore after, and keep content out of telemetry.
using System.Text.RegularExpressions;
using Microsoft.Extensions.AI;
namespace Assistant.Privacy;
// Replaces structured identifiers with stable tokens; the map never leaves the server.
public sealed partial class Pseudonymiser
{
private readonly Dictionary<string, string> _tokenToValue = [];
private readonly Dictionary<string, string> _valueToToken = [];
public string Mask(string text)
{
text = Email().Replace(text, m => Token("EMAIL", m.Value));
text = AuPhone().Replace(text, m => Token("PHONE", m.Value));
return text;
}
public string Unmask(string text) =>
TokenPattern().Replace(text, m => _tokenToValue.GetValueOrDefault(m.Value, m.Value));
private string Token(string kind, string value)
{
if (_valueToToken.TryGetValue(value, out var existing)) return existing;
var token = $"[{kind}_{_valueToToken.Count + 1}]";
_valueToToken[value] = token;
_tokenToValue[token] = value;
return token;
}
[GeneratedRegex(@"[\w.+-]+@[\w-]+(\.[\w-]+)+")] private static partial Regex Email();
[GeneratedRegex(@"(\+61|0)[2-478](\s?\d){8}")] private static partial Regex AuPhone();
[GeneratedRegex(@"\[(EMAIL|PHONE)_\d+\]")] private static partial Regex TokenPattern();
}
public sealed class TicketSummariser(IChatClient chat)
{
public async Task<string> SummariseAsync(string ticketText, CancellationToken ct)
{
var masker = new Pseudonymiser(); // per request: no cross-request mapping
var response = await chat.GetResponseAsync(
[
new(ChatRole.System, "Summarise the support ticket in three bullet points."),
new(ChatRole.User, masker.Mask(ticketText))
], new ChatOptions { MaxOutputTokens = 200 }, ct);
return masker.Unmask(response.Text); // restore only for the entitled caller
}
}
Tenant filter enforced in one place, and telemetry without content:
// Every vector query goes through this method; the tenant comes from the token, not the request body.
public IAsyncEnumerable<VectorSearchResult<PolicyChunk>> SearchAsync(
ReadOnlyMemory<float> query, ClaimsPrincipal user, CancellationToken ct)
{
var tenantId = user.FindFirstValue("tid") ?? throw new UnauthorizedAccessException();
var groups = user.FindAll("groups").Select(c => c.Value).ToList();
var options = new VectorSearchOptions<PolicyChunk>
{
Filter = c => c.TenantId == tenantId && groups.Contains(c.AllowedGroup)
};
return _collection.SearchAsync(query, top: 6, options, ct);
}
// Program.cs: spans with token counts, but no prompt or response text.
builder.Services.AddChatClient(innerClient)
.UseOpenTelemetry(configure: o => o.EnableSensitiveData = false);
The strongest control is architectural: if data never enters the context, the model can't leak it. Everything else (redaction, output scanning, prompt wording) reduces risk at the margins. For multi-tenant products with sensitive data, I lean towards per-tenant indexes because they fail closed: a bug returns nothing rather than another customer's data.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Shared index + enforced filter | Many small tenants, low sensitivity | Cheapest; one bug can leak | Health, financial or government data |
| Per-tenant index / collection | Sensitive data, contractual isolation | More resources and ops | Thousands of tiny tenants (consider partitioning) |
| Pseudonymisation before prompts | Model needs structure, not identities | Extra processing, mapping store | Task needs the real value (e.g. writing an address label) |
| Content capture in telemetry | Short, sampled debugging in non-prod | Privacy and retention risk | Production by default |
Put a privacy impact assessment in the definition of done for every AI feature, and measure: cross-tenant test results, PII detections in outputs and logs, and time for permission changes to reach the index.
Treat logs as a data store that attackers and too many staff can read. Never log secrets (passwords, tokens, Authorization headers, connection strings, card numbers) and keep personal information out: log identifiers like CustomerId, not names, emails or request bodies.
Enforce it in code rather than by memory: Microsoft.Extensions.Compliance.Redaction lets you classify fields with attributes, map classifications to redactors (erase, or HMAC for a stable pseudonym) with AddRedaction, and apply them to logs with EnableRedaction. Use header allowlists in HTTP logging.
In Australia, APP 11 requires reasonable steps to protect personal information and APP 11.2 requires destroying or de-identifying it when no longer needed, so retention matters, and a leaked log store can be a notifiable data breach. The trade-off: less detail in logs versus a smaller breach surface.
RAG is two pipelines. Ingestion (offline): extract text, chunk it on headings into a few hundred tokens, embed each chunk with IEmbeddingGenerator, and upsert it with metadata (source, heading, URL, permissions) into a vector store through Microsoft.Extensions.VectorData. Query (online): embed the question, run a hybrid, permission-filtered search for the top 5–8 chunks, then call the chat model with a grounding prompt: numbered sources, "answer only from these", "say you don't know", and cite [n].
You check the citations in code and show source links. You measure retrieval recall and answer groundedness on a labelled set. The trade-off: more chunks raise recall but add cost, latency and noise that can distract the model.
How to tell it (STAR)
**S:** A privacy review of our [claims assistant] found about [2 million] customer conversations with names and claim details sitting in Application Insights for [90 days]. **T:** As [the engineer who owned the assistant's telemetry], I had to remove the exposure and make sure it couldn't creep back. **A:** I traced it to sensitive-data capture left on from early debugging, turned it off that day, mapped every copy with its retention, purged the content with the privacy officer's sign-off, and replaced it with 1% sampled, redacted logs kept [14 days]. I added a build check that fails if capture is enabled outside dev. **R:** Personal information in logs fell by [over 95%], the assessment found [no unauthorised access], and the check has since [caught one regression in a pull request].
Last updated 23 Nov 2026.