📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you stop an AI feature leaking data? Talk me through personal information in prompts, tenant and permission isolation in RAG, logging prompts and responses safely, where the model provider processes and keeps data, and what the Privacy Act requires.

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).

Senior Security Advanced ai data-leakage privacy-act rag redaction security

🎯 Key points

  • Minimise: send only the fields the task needs; redact or pseudonymise personal information before the prompt (OWASP LLM02 Sensitive Information Disclosure)
  • Isolate in RAG: tenant and ACL filters inside every vector query, or separate indexes per tenant; never rely on the model to withhold data it was given
  • Permissions must stay in sync: removed access and deleted documents removed from the index promptly
  • Logs and traces are a second copy: keep UseOpenTelemetry EnableSensitiveData off, redact with Microsoft.Extensions.Compliance.Redaction classifications, restrict the Log Analytics workspace with RBAC, short retention
  • Provider handling: Standard deployment in Australia East (or a Data Zone) for residency, no training on customer data, abuse-monitoring retention (up to 30 days) and modified abuse monitoring
  • Azure configuration enforces it: Azure Policy allowed locations, disableLocalAuth (managed identity only), private endpoints with public network access off, customer-managed keys where required
  • Privacy Act: APP 6 (purpose), APP 8 (cross-border disclosure), APP 11 (security, destruction), NDB scheme; automated-decision transparency in privacy policies from 10 December 2026
  • Prove it: cross-tenant leakage tests in CI, output PII scanning, and a privacy impact assessment for each AI feature

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 paths and controls

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

Privacy Act mapping

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

Production example

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%].

🔍 What the interviewer is checking

Checks that the candidate sees every AI data copy as a leak path and knows the Australian legal context.

Green flags

  • Minimisation and redaction or pseudonymisation before prompts
  • Tenant and ACL filters inside the search, or per-tenant indexes
  • Treats logs, traces and caches as data stores with retention
  • Knows provider residency, deployment types and abuse-monitoring retention
  • Maps controls to APPs and the NDB scheme

Red flags

  • "The system prompt tells it not to share"
  • Logs full prompts in production without a second thought
  • Filters results in the UI
  • No idea where the model provider processes data

📚 Learn in depth

1. Where copies of data appear in an AI feature

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.

2. Tenant isolation options

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.

3. Redaction and pseudonymisation

  • Redaction: replace values with markers ([EMAIL]). Safe, but the model loses the value.
  • Pseudonymisation: replace with stable tokens (PERSON_1) and keep the mapping server-side; restore in the response. The model can still reason about "PERSON_1 emailed PERSON_2".
  • Detection: regexes for structured identifiers (email, phone, TFN, Medicare), plus an NER service (for example Azure AI Language PII detection) for names and addresses.
  • Microsoft.Extensions.Compliance.Redaction classifies data with attributes and redacts it in logs ([PrivateData]-style taxonomies, ErasingRedactor, HmacRedactor).

4. Telemetry for generative AI

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.

5. Provider data handling (Azure OpenAI / Foundry)

  • Prompts and completions are not used to train the models.
  • Deployment type determines processing location: Standard (regional) processes in the resource's region; Global may process in any region; Data Zone stays within a geography.
  • Abuse monitoring may store prompts and completions for up to 30 days for review; approved customers can apply for modified abuse monitoring.
  • Record all of this in the privacy impact assessment and the APP 8 analysis.

6. Breach handling

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.

Try it yourself

  1. Write an integration test that indexes chunks for two tenants and asserts tenant A's queries never return tenant B's chunks, including with injected text asking for them.
  2. Turn on EnableSensitiveData in a dev environment and look at what lands in traces; then turn it off.
  3. Run the pseudonymiser below on a sample support ticket and send it to a model; restore the names in the answer.
  4. Revoke a user's group membership and measure how long until the index stops returning those documents.
  5. Draft the data-flow section of a privacy impact assessment for one AI feature.

💻 Code

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);

⚠ Common mistakes

  • Mistake: Relying on the system prompt to withhold data ("don't reveal other customers' details"). Why it is wrong: data in the context can be extracted by injection or simple confusion. Instead: don't put data the user isn't entitled to into the context.
  • Mistake: Filtering RAG results after retrieval, or in the UI. Why it is wrong: unauthorised chunks still reach the prompt and can appear in the answer. Instead: filter inside the vector query, or use per-tenant indexes.
  • Mistake: Capturing full prompts and responses in Application Insights by default. Why it is wrong: logs become an unprotected copy of personal information with long retention. Instead: keep content capture off; redact sampled debug logs; short retention and restricted access.
  • Mistake: Sending whole records "for context". Why it is wrong: breaches data minimisation and increases breach impact. Instead: send only the fields the task needs; pseudonymise identifiers.
  • Mistake: Ignoring deployment type and region. Why it is wrong: Global deployments can process outside Australia, which affects APP 8 and customer contracts. Instead: choose Standard in Australia East (or a Data Zone) where residency matters and document it.
  • Mistake: Caching AI responses without user or tenant scope. Why it is wrong: one user's answer, including their data, is served to another. Instead: include tenant and user scope in the cache key, or don't cache personalised answers.
  • Mistake: Forgetting deletion. Why it is wrong: indexes, logs and conversation stores keep personal information after the source is deleted (APP 11.2). Instead: propagate deletes and set retention on every copy.
  • Mistake: No leakage tests. Why it is wrong: one missed filter in a refactor goes unnoticed until a customer finds it. Instead: cross-tenant integration tests in CI.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions logging prompts or redaction Why: Checks general logging hygiene for personal information beyond AI
    How to answer

    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.

  2. When: Candidate mentions tenant isolation in RAG Why: Checks how permission filtering is built into retrieval
    How to answer

    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.

🛠 Real-world problems: how you handle them

Customer conversations retained in AI telemetry
Situation
[A customer-service assistant] for [an Australian insurer] handled [about 20k conversations a day]. A privacy review found full prompts and responses, including names, addresses and claim details, stored in Application Insights for [90 days] and readable by [the whole engineering group].
Signals
Privacy review finding; KQL queries over `traces` and gen_ai span attributes returning message content; [about 2 million] stored conversations; no customer complaint yet.
Investigation
Found `EnableSensitiveData` turned on during an early debugging session and never reverted; mapped every copy (traces, logs, a debug blob container, the conversation store) with its retention and access; checked access logs for unusual queries against the workspace; assessed with the privacy officer whether this was an eligible data breach ([no unauthorised access found])
Resolution
Turned off content capture the same day; purged content-bearing records using the workspace data purge API and deleted the debug container; restricted workspace access; added redacted, sampled debug logging (1% of conversations, 14-day retention) for prompt troubleshooting.
Prevention
A configuration test that fails the build if sensitive-data capture is enabled outside dev; retention policies in IaC for every AI data store; privacy impact assessment updated and required for AI changes; quarterly KQL check for PII patterns in logs.

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].

↩ Usually asked after

More in .NET and AI

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me