Filed underL02 · Security
Published
Reading time26 min
Words5,877
Field notes · L02 Security

Permission-aware RAGEnforcing document access rules during retrieval

How to enforce document permissions in RAG: pre-filter vs post-filter, syncing ACLs from Google Drive and SharePoint, group expansion, caching and audit.

The short answer

Enforce access control inside the retrieval query, not after it. Store a normalised list of principals (users, groups, domains) on every chunk. At query time, expand the requesting user into their full principal set (including transitive group memberships) and pass it as a filter to the vector search, so documents the user cannot open are never candidates. Post-filtering is fine as a second check, never as the only one. Then treat ACL sync freshness, caches and derived artefacts (summaries, memories, logs) as part of the same access-control boundary, and log the principal set used for every retrieval so you can prove what a user could and could not see.

The rest of this post is the detail: where the leaks come from, how to sync ACLs from Google Drive and SharePoint without lying to yourself about freshness, what group expansion really costs, and a test suite you can run in CI to catch regressions before an employee finds them for you.

01Why "index everything" leaks

The default RAG tutorial pipeline goes like this: a service account crawls the corpus, chunks it, embeds it, writes vectors to an index, and a chat endpoint retrieves the top-k chunks for any question. The service account can read everything. So can the retriever. The model then answers whoever is asking.

That is a textbook confused deputy. The model is a privileged process acting on behalf of an unprivileged user, and nothing in the pipeline carries the user's identity down to the data. The payroll spreadsheet, the board deck and the draft redundancy list are all just embeddings now.

Four properties make this worse than an ordinary access-control bug:

  1. The model cannot un-know. Once a restricted chunk is in the context window, no prompt instruction ("don't reveal confidential information") reliably keeps it out of the answer. Prompt injection makes this actively exploitable: CVE-2025-32711 ("EchoLeak", published 11 June 2025) was described as "AI command injection in M365 Copilot allows an unauthorized attacker to disclose information over a network", rated 9.3 by Microsoft. Whatever is in context is in scope for exfiltration. Our post on securing AI agents against prompt injection covers that side.
  2. Answers aggregate. A user who could not find a sensitive file via search can ask a question whose best answer happens to be in it. Retrieval is search with better recall, so it finds things keyword search never surfaced.
  3. Leaks are silent. Nobody files a ticket when the assistant quotes a salary band to the wrong person. You find out from a screenshot.
  4. Correct enforcement still inherits oversharing. Microsoft's own Copilot security guidance says Copilot "operates within existing permissions and access controls. Overshared or poorly governed content can affect Copilot results and increase risk." Permission-aware retrieval makes the assistant exactly as safe as your sharing settings. That is necessary, not sufficient.

OWASP's LLM08:2025 Vector and Embedding Weaknesses names the fix directly: "Implement fine-grained access controls and permission-aware vector and embedding stores", and "maintain detailed immutable logs of retrieval activities". The rest of this post is how to do both properly.

02The four places a RAG system leaks

Before choosing a filtering strategy, be precise about what you are defending. In our experience teams fix the first and miss the other three.

Leak Where it happens Typical cause
Retrieval leak Vector or hybrid search returns chunks the user cannot open No ACL on chunks, or filter applied after top-k
Staleness leak User lost access minutes or days ago; index still says yes ACL sync is batch-only, group membership cached too long
Cache leak A cached answer or retrieval set built for user A is served to user B Semantic cache keyed on query text or embedding alone
Derived-artefact leak Summaries, extracted entities, conversation memory, eval sets and logs outlive or escape the source ACL Derived data written without inheriting permissions

03Reference architecture for permission-aware retrieval

Diagram
 Drive / SharePoint / Confl.
   |
   v
 +----------------------- ingestion -----------------------+
 | content crawler --> chunk + embed --+                   |
 |                                     +--> chunk store    |
 | ACL sync (delta + reconcile)        |    (vector, text, |
 |   --> normaliser: source perms -----+     acl[], deny[],|
 |       --> principal tokens                acl_version)  |
 +---------------------------------------------------------+

 IdP (Entra ID / Google) --> group expansion service
                             (transitive, cached, short TTL)
                                          | principal set
                                          | (+ snapshot version)
                                          v
 user --> API (authn) --> resolve principals --> filtered retrieval
                                                 (pre-filter in index)
                                                          |
                                                          v
                                          re-check (live source or authz)
                                                          |
                                                          v
                                    rerank --> LLM --> answer + citations
                                                          |
                                                          v
                                                 retrieval audit log

Three things to notice. Identity enters at the API and is carried all the way to the index query. ACLs are synced on their own path, separate from content, because permissions change far more often than text. And there is a re-check after retrieval: a cheap, narrow verification against the source of truth for the handful of chunks that will actually reach the model.

04Pre-filter vs post-filter: which one enforces access control?

There are four broad strategies. Only two of them are safe as the primary control.

Strategy How it works Leak risk Recall Cost Use when
Post-filter only Retrieve top-k, drop chunks the user cannot see Low if done correctly, but... Poor for users with narrow access Cheap index, expensive re-checks Never as the only control
Pre-filter (ACL in index) Principal tokens stored on each chunk; search filtered on intersection with user's principals Low, bounded by sync freshness Good, if the engine filters during traversal Index size grows with ACL metadata Default for most corpora
Index per tenant / per audience Separate index or namespace per access boundary Very low Excellent within boundary Explodes with fine-grained sharing Hard boundaries: customers, legal entities, clearance levels
External authz service (Zanzibar-style) Relationship store answers "which docs can U read?" or "can U read D?" Low, and consistency is explicit Depends on how you combine with search Another system to run Complex sharing models, many apps sharing one policy

Why post-filtering starves results

Post-filtering looks attractive: index without ACLs, then check each result. The problem is arithmetic.

Worked example (illustrative assumptions): a corpus of 1,000,000 chunks. A given user can read 2% of them. Assume, generously, that readable chunks are spread evenly through the similarity ranking. Retrieve k = 50, then filter: the expected number of readable chunks is 50 × 0.02 = 1. To expect 10 usable chunks you need about 10 / 0.02 = 500 candidates, and more than that to be confident of getting 10.

The real distribution is worse than uniform. Restricted content clusters: a question about parental leave policy lands in HR's space, which is precisely where the restricted files live. Post-filtering degrades hardest on the queries where permissions matter most, and it degrades into "I couldn't find anything" rather than an error, so nobody notices.

Post-filtering is still valuable as a defence-in-depth re-check on the final 5–20 chunks, ideally against the live source or authorisation service. That catches the staleness window cheaply.

How pre-filtering actually behaves in common vector stores

A filter is only useful if the engine applies it during the approximate nearest-neighbour search, not after it.

  • pgvector. HNSW and IVFFlat indexes apply WHERE clauses after the index scan. Since 0.8.0, iterative index scans (hnsw.iterative_scan = strict_order | relaxed_order) keep scanning until enough rows pass the filter, bounded by hnsw.max_scan_tuples (default 20,000). For very selective ACLs the planner may skip the vector index, use a GIN index on the ACL column and compute exact distances over the small readable set, which is both correct and exact. Our post on pgvector vs Pinecone and filtered search covers tuning.
  • Qdrant. Filterable HNSW adds graph edges based on indexed payload values, and the query planner switches to full scan when the estimated matching set is below full_scan_threshold_kb. Index the ACL field as a keyword payload index.
  • Pinecone. Metadata filters are applied in-query, but operation limits cap each $in at 10,000 values and filterable metadata at 40 KB per record. Both limits matter: the first constrains how big a user's principal set can be, the second constrains how big a document's ACL can be. Store groups on documents, not expanded user lists.

That last point generalises. Put groups on documents, expand users at query time. A document shared with all-staff@ has one ACL token, not 4,000. A user in 60 groups sends 62 tokens (user, 60 groups, domain). Both sides stay small.

05A data model for chunk-level ACLs

Normalise every source's permission model into opaque principal tokens. Keep it allow-list by default, with an optional deny list for sources that genuinely have deny semantics (Windows file shares, some DMSs). Google Drive and SharePoint sharing are effectively allow-only.

Token conventions we use:

Text
u:<immutable user id>        # e.g. u:entra:7c1f...  or  u:google:1029...
g:<immutable group id>       # g:entra:3b9e...  /  g:google:groups/03x8...
d:<verified domain>          # d:example.com  (org-wide, discoverable)
sg:<site id>:<group id>      # SharePoint site groups, until expanded
link:<source file id>        # link-only shares; see below

Prefer immutable IDs over email addresses. Email addresses get reused: if j.smith@ leaves and a new J. Smith joins, an email-keyed ACL silently hands the newcomer the old employee's access. Where a source only gives you an email, resolve it to an IdP object ID during sync and store both.

In Postgres:

sql
CREATE TABLE chunks (
  id           bigserial PRIMARY KEY,
  doc_id       text        NOT NULL,
  source       text        NOT NULL,          -- 'gdrive' | 'sharepoint' | ...
  body         text        NOT NULL,
  embedding    vector(1024) NOT NULL,
  acl          text[]      NOT NULL,          -- allow tokens
  deny         text[]      NOT NULL DEFAULT '{}',
  acl_version  bigint      NOT NULL,          -- bumps on every ACL change
  acl_synced_at timestamptz NOT NULL
);

CREATE INDEX chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX chunks_acl_gin  ON chunks USING gin (acl);
CREATE INDEX chunks_deny_gin ON chunks USING gin (deny);

-- ACLs live per document; denormalise onto chunks on write,
-- or join. Denormalising is faster to query, slower to update.

The retrieval query, run inside a transaction so the setting is scoped:

sql
BEGIN;
SET LOCAL hnsw.iterative_scan = relaxed_order;
SET LOCAL hnsw.ef_search = 100;

SELECT id, doc_id, body, acl_version,
       embedding <=> $2::vector AS distance
FROM   chunks
WHERE  acl  && $1::text[]            -- any allow token matches
AND    NOT (deny && $1::text[])      -- no deny token matches
ORDER  BY embedding <=> $2::vector
LIMIT  40;
COMMIT;

$1 is the principal set from the expansion service. Never let it come from the client. If you use Postgres row-level security elsewhere, you can push this predicate into a policy keyed on a session variable; our post on multi-tenant Postgres with row-level security covers the mechanics and the pitfalls of SET with connection pools.

06Syncing ACLs from Google Drive

Drive has four permission types: user, group, domain and anyone (sharing guide). The fields you need are not returned by default (only id, type, kind and role are), so ask for them explicitly:

python
PERM_FIELDS = (
    "nextPageToken,"
    "permissions(id,type,role,emailAddress,domain,allowFileDiscovery,"
    "deleted,expirationTime,permissionDetails,view)"
)

def list_permissions(drive, file_id):
    token = None
    while True:
        resp = drive.permissions().list(
            fileId=file_id,
            supportsAllDrives=True,
            fields=PERM_FIELDS,
            pageToken=token,
        ).execute()
        yield from resp.get("permissions", [])
        token = resp.get("nextPageToken")
        if not token:
            return

def to_tokens(perm, file_id, resolve):
    """Map one Drive permission to principal tokens. `resolve` maps
    an email to an immutable IdP id, raising if unknown."""
    if perm.get("deleted"):
        return []
    t = perm["type"]
    if t == "user":
        return [f"u:{resolve(perm['emailAddress'])}"]
    if t == "group":
        return [f"g:{resolve(perm['emailAddress'])}"]
    if t in ("domain", "anyone"):
        # Discoverable org-wide or public share: visible to the audience.
        if perm.get("allowFileDiscovery"):
            return [f"d:{perm['domain']}"] if t == "domain" else ["anyone"]
        # Link-only share: do NOT widen to the whole domain.
        return [f"link:{file_id}"]
    return []

Details that bite:

  • allowFileDiscovery is "only applicable for permissions of type domain or anyone" and says whether the file can be found through search (permissions reference). A file shared "anyone at example.com with the link" is not meant to be discoverable. If you map it to d:example.com, your assistant becomes a discovery engine for every link-shared file in the company. Map it to link:<file_id> and decide deliberately who holds that token. Our default is nobody: link-only files are retrievable only by their explicit principals. We have not found a documented, admin-visible record of who has opened a link-only file, so there is no safe basis for granting access on that ground.
  • Shared drives inherit downward and cannot be reduced on children, unless a folder sets inheritedPermissionsDisabled, in which case "only organizers, owners, and users with permissions added directly on the item can access it". Read permissionDetails[].inherited and inheritedFrom rather than assuming. Note that inheritedFrom "is only populated for items in shared drives".
  • expirationTime exists on user and group permissions. Index it and enforce it at query time (WHERE acl_expires_at IS NULL OR acl_expires_at > now()), or schedule a re-sync at expiry. Otherwise expired access stays live until the next full reconcile.
  • Change detection. Use the Changes API (getStartPageToken, then changes.list) for content and metadata, and the Drive Activity API, whose PermissionChange action carries addedPermissions and removedPermissions, as a fast signal for sharing edits. On any signal, re-list the file's permissions rather than applying the diff: the full list is the truth, the diff is a hint. The Changes guide says the collection detects "all file changes" but does not spell out that every permission edit, including inherited changes on shared drives, produces an entry, so back both feeds with a scheduled full permission reconcile.
  • Folder moves change ACLs on everything underneath. A move triggers re-evaluation of inherited permissions. Treat a move event on a folder as an ACL change for the whole subtree.

07Syncing ACLs from SharePoint and OneDrive

Use the driveItem: delta API with the sharing-aware preferences:

http
GET https://graph.microsoft.com/v1.0/drives/{drive-id}/root/delta?token={saved-token}
Authorization: Bearer {app-token}
Prefer: deltashowremovedasdeleted, deltatraversepermissiongaps, deltashowsharingchanges

With deltashowsharingchanges, items that appear because their permissions changed carry the annotation "@microsoft.graph.sharedChanged": "True". Microsoft documents that this header requires the other two, that it applies to SharePoint and OneDrive for Business only, and that "in order to process permissions correctly your application will need to request Sites.FullControl.All". Adding Prefer: hierarchicalsharing returns sharing information only for the roots of permission hierarchies and items with explicit changes, which cuts the follow-up calls you would otherwise make for every inherited child.

For each flagged item, fetch GET /drives/{drive-id}/items/{item-id}/permissions and rebuild its ACL. Points to handle:

  • Sites.FullControl.All is a big ask. Your security team will, rightly, push back on an AI ingestion service holding full control of every site. Scope it with Sites.Selected where you can index a known set of sites, isolate the credential in its own workload identity, and log its use. This is exactly the sort of decision that should not be made inside the AI team alone. Microsoft's delta and scanning guidance names only Sites.FullControl.All for processing permissions; we have not found documentation saying a Sites.Selected grant with the fullcontrol role satisfies that requirement, so test it in your own tenant before you rely on it.
  • inheritedFrom is not returned by "OneDrive for Business and SharePoint document libraries" (permission resource). You must track the inheritance hierarchy yourself from the delta feed. hierarchicalsharing helps: an empty shared facet distinguishes "inherits from parent" from "unique but unshared".
  • grantedTo and grantedToIdentities are deprecated in favour of grantedToV2 and grantedToIdentitiesV2. Read the V2 properties.
  • Sharing links have scopes. A link permission with an organisation-wide scope is the SharePoint analogue of Drive's link-only domain share. Apply the same rule: do not widen it to everyone in the tenant. existingAccess links grant nothing new and can be ignored.
  • SharePoint site groups are not Entra groups. Site Owners, Members and Visitors appear in grantedToV2 as SharePoint groups, not Entra groups. The sharePointIdentitySet resource carries them in siteGroup, "identified by a principal ID that is unique only within the site", and in the newer sharePointGroup, which Microsoft says to use "instead of siteGroup when available". Expand them through the SharePoint REST API (/_api/web/sitegroups/getbyid({id})/users) or represent them as site-qualified sg: tokens and expand at query time. Members can themselves be Entra groups, which then need the usual transitive expansion.
  • 410 Gone means resync. Old delta tokens can expire; the service returns 410 with resyncChangesApplyDifferences or resyncChangesUploadDifferences and a fresh enumeration link. For ACL purposes treat both as "full reconcile of this drive", and until it completes, fail closed for that drive's content.

08Group expansion: at index time or at query time?

Nested groups are where most permission-aware RAG implementations quietly go wrong. eng@ contains platform@, which contains Alice. A document shared with eng@ must be visible to Alice.

You have two choices:

Expand at index time Expand at query time
Document ACL holds Every user ID who can read Group IDs as shared
Membership change Re-write ACLs on every affected chunk Invalidate one user's principal cache
ACL size Large (all-staff = every employee) Small
Query filter size One token (the user) User + transitive groups
Freshness on group change Slow, write-amplified Fast (cache TTL)

Expand at query time. Index-time expansion turns one HR change ("add Alice to finance-leads@") into a write against every chunk finance-leads can read, and it blows through per-record metadata limits for widely shared documents.

The APIs:

  • Entra ID: GET /users/{id}/transitiveMemberOf returns the flattened list of groups a user belongs to. The mirror, GET /groups/{id}/transitiveMembers, is useful for reconciliation; it pages at 100 by default and 999 maximum, and some query options need ConsistencyLevel: eventual, which "uses an index that might not be up-to-date with recent changes". Do not use the eventual-consistency variants on the revocation path.
  • Google: the Cloud Identity Groups API offers checkTransitiveMembership and related transitive search methods. Note the licensing: checkTransitiveMembership and searchTransitiveGroups both require "Google Workspace Enterprise Standard, Enterprise Plus, and Enterprise for Education; and Cloud Identity Premium accounts"; others get 403 PERMISSION_DENIED. On lower editions you walk the graph yourself with the Admin SDK Directory API and must handle cycles.

Don't rely on the groups claim in the user's ID token. Entra caps how many groups it embeds (200 for JWTs, 150 for SAML tokens) before switching to an overage claim, and the token is a snapshot from sign-in, possibly hours old. Resolve memberships server-side from the IdP and cache them briefly.

A minimal resolver:

python
from dataclasses import dataclass
import hashlib, time

@dataclass(frozen=True)
class PrincipalSet:
    tokens: tuple[str, ...]
    resolved_at: float
    directory_version: str   # e.g. the delta token of your group sync

    @property
    def digest(self) -> str:
        return hashlib.sha256("\n".join(self.tokens).encode()).hexdigest()

def resolve_principals(user, idp, cache, ttl_s=300) -> PrincipalSet:
    hit = cache.get(user.id)
    if hit and time.time() - hit.resolved_at < ttl_s:
        return hit
    groups = idp.transitive_groups(user.id)          # paged, strongly consistent
    tokens = sorted({f"u:{user.id}", *(f"g:{g}" for g in groups),
                     *(f"d:{d}" for d in user.verified_domains)})
    if len(tokens) > 9_000:                           # stay under engine limits
        raise PrincipalSetTooLarge(user.id)           # fail closed, alert
    ps = PrincipalSet(tuple(tokens), time.time(), idp.directory_version())
    cache.set(user.id, ps)
    return ps

Fail closed when the principal set is too large or the IdP is unreachable. "Couldn't verify your access, try again" is a support ticket. The alternative is an incident.

09Permission drift and how fresh your ACLs need to be

Every synced ACL is a cache of the source system's truth, and it drifts. Decide on a freshness target and design to it, rather than discovering it.

Worked example (illustrative assumptions): Graph delta polled every 5 minutes; processing and re-indexing p99 of 2 minutes; principal cache TTL 5 minutes. Worst-case time from "access revoked at source" to "retrieval enforces it":

Text
document-level revocation:  5 (poll) + 2 (process)              =  7 min
group-membership removal:   group sync interval + 5 (TTL)       = ~10–15 min

Whether 15 minutes is acceptable depends on the content. For an engineering wiki, probably. For an M&A data room, no. Ways to tighten it:

  1. A priority lane for removals. Process permission removals and user disablement before additions and content edits. A late grant is an inconvenience; a late revocation is a leak.
  2. Event-driven triggers on top of polling. Graph change notifications and Drive push notifications reduce latency; keep polling as the backstop, because notifications get dropped.
  3. Re-check at the edge. For the final chunks going to the model, check against the live source or your authorisation service. This collapses the effective window for the content that matters to the latency of one batched call.
  4. Explicit consistency tokens. Zanzibar-style systems make this a first-class concept. SpiceDB's ZedTokens let a request demand data "at least as fresh as" a point in time, which protects against what the Zanzibar paper calls the "new enemy" problem: a check evaluated against stale data after access was removed.
  5. Nightly full reconcile. Delta feeds miss things. Re-enumerate permissions for every indexed document on a schedule, diff against the index, and alert on any drift you didn't already know about. The drift rate is the most honest health metric this system has.

If you need many applications to share one permission model, a relationship-based authorisation service (SpiceDB, OpenFGA) is worth its operational cost. Both document the same trade-off you face in retrieval: SpiceDB describes LookupResources as a pre-filter but "a heavy request that can cause performance problems when more than 10k results are involved", and suggests post-filtering with CheckBulkPermissions beyond that; OpenFGA's ListObjects defaults to a 3-second deadline and 1,000 results. Use them for the edge re-check and for complex rules. Keep principal tokens in the index for the candidate filter. You probably don't need an authorisation service if your only sources are Drive and SharePoint and their native model is all you enforce.

10Caching without leaking

Caching is the most common way a correct retriever becomes an incorrect product.

Cache Safe? Rule
Embedding cache (text → vector) Yes Content-addressed; contains no access decision
Provider prompt cache Yes, per request Contents are what you sent; the ACL decision was made before
Retrieval cache (query → chunk IDs) Only if re-filtered Cache candidate IDs, re-apply ACL filter on every read
Semantic answer cache (query → answer) Dangerous Key must include principal-set digest and corpus ACL epoch
Conversation memory Dangerous Re-check cited chunks on every turn
Principal-set cache Yes, short TTL Invalidate on group-change events

The classic failure is a semantic cache keyed on the query embedding. The CFO asks "what is the Q3 restructuring plan?", the answer is cached, an intern asks something semantically close and gets the CFO's answer. Nothing in the retriever was wrong.

If you must cache answers, scope the key so that two users only share a cache entry when their access is identical:

python
def answer_cache_key(query_norm: str, ps: PrincipalSet, acl_epoch: int) -> str:
    # acl_epoch: a counter bumped on any ACL change in the corpus (or per
    # source). Coarse, but it guarantees revocations invalidate answers.
    h = hashlib.sha256()
    for part in (query_norm, ps.digest, str(acl_epoch)):
        h.update(part.encode()); h.update(b"\x00")
    return h.hexdigest()

In practice principal-set digests are close to unique per user, so the hit rate collapses, and that is the point. Answer caching across users is mostly incompatible with fine-grained permissions. Cache the expensive, permission-free parts (embeddings, reranker features, and the provider-side prompt caching that holds only what you already sent) instead.

Conversation memory is the subtle one. A user retrieves a document at 10:00, access is revoked at 10:05, and at 10:10 they ask a follow-up in the same thread. The chunk is still in the chat history the model sees, and in any compacted summary or memory your context engineering produced from it. Store citations as chunk IDs with their acl_version, and on each turn drop any history chunk that fails a fresh check.

11Derived artefacts inherit the strictest source

Teams that get retrieval right often leak through what they build from retrieval: nightly summaries, knowledge graphs, extracted entities, FAQ pages generated from tickets, fine-tuning sets, and RAG eval datasets assembled from real queries.

The rule: a derived artefact is readable only by principals who can read every source it was derived from. That is an intersection of permissions, and you cannot compute it by intersecting group lists, because {eng@} ∩ {senior-staff@} as token sets is empty even though many people are in both groups. Represent the requirement as a conjunction instead:

sql
CREATE TABLE derived_sources (
  derived_id text NOT NULL,
  source_doc text NOT NULL,
  PRIMARY KEY (derived_id, source_doc)
);

-- Visible iff the user passes every source document's check.
SELECT d.id
FROM   derived d
WHERE  NOT EXISTS (
  SELECT 1
  FROM   derived_sources s
  JOIN   documents doc ON doc.id = s.source_doc
  WHERE  s.derived_id = d.id
  AND    NOT (doc.acl && $1::text[] AND NOT (doc.deny && $1::text[]))
);

Better still, avoid cross-document derived artefacts in shared indexes. Generate summaries per document, inheriting that document's ACL, and let retrieval combine them per user at query time.

Logs count too. Your retrieval log contains chunk text if you are careless, and your LLM observability platform has a far wider audience than the HR drive. Log IDs and versions, not bodies.

12Auditing retrieval: what to log

When someone asks "did anyone see the redundancy list through the assistant after we locked it down?", you need to answer with evidence, not reassurance. Log one record per retrieval:

json
{
  "ts": "2026-10-06T09:14:22.381Z",
  "request_id": "req_01J9...",
  "user": "u:entra:7c1f...",
  "principal_digest": "9f2c...e1",
  "principal_count": 47,
  "directory_version": "grp-delta-2026-10-06T09:10Z",
  "query_hash": "sha256:4b1d...",
  "index_snapshot": "chunks@acl_epoch=88213",
  "candidates": 40,
  "edge_recheck": { "checked": 12, "denied": 1, "denied_docs": ["gdrive:1AbC..."] },
  "sent_to_model": [
    {"chunk": 991823, "doc": "sp:01ABC...", "acl_version": 17}
  ],
  "cited": ["sp:01ABC..."]
}

That record lets you answer three questions. Which principals did we believe this user had? Which documents reached the model, at which ACL version? And did the edge re-check ever disagree with the index? Every edge denial is a measured instance of drift. Alert on the rate.

Keep the principal set itself (not just the digest) in a separate store with the same retention, so an investigation can reconstruct it. Make the log append-only and readable by security, not by the AI team's general tooling; OWASP's "immutable logs" wording is the right bar.

13The permission-aware RAG leak test suite

This is the asset we'd ask any team to adopt before an internal assistant goes beyond a pilot. Each test plants a canary: a document containing a unique random string (for example CANARY-7f3a91c2) with a specific sharing configuration in the real source system, then asks the assistant questions designed to retrieve it. A test passes only if the canary string never appears in retrieval results, model context or the answer for users who should not see it, and does appear for users who should.

Run it against a staging tenant in CI and against production on a schedule.

# Scenario Setup in source system Probe user Pass criterion
1 Direct share Doc shared with user A only B B never retrieves canary; A does
2 Nested group Doc shared with g-outer, A in g-inner ⊂ g-outer A, then B (not in either) A retrieves; B does not
3 Group removal Remove A from g-inner A Canary disappears within group-freshness SLO
4 Document revocation Remove A's direct share A Disappears within document-freshness SLO
5 Link-only share "Anyone in org with the link" (Drive) / org-scoped link (SharePoint) B (never opened it) B never retrieves
6 Discoverable domain share Domain share with discovery on B B retrieves (proves you are not over-restricting)
7 Inheritance break Shared-drive folder with inheritedPermissionsDisabled; parent shared with B B B never retrieves child canary
8 Folder move Move canary folder from open to restricted parent B Disappears within SLO
9 Expiring share User share with expirationTime = now + 10 min A after expiry Disappears at expiry, not at next reconcile
10 Cross-user cache A asks a canary question; B asks the same question B B's answer contains no canary
11 Conversation memory A retrieves canary, access revoked, A asks a follow-up A Follow-up contains no canary
12 Derived artefact Canary in a doc feeding a summary or digest job B Canary absent from derived output visible to B
13 Disabled account Disable A in the IdP A's still-valid session Requests fail or return no restricted content
14 IdP outage Block group-expansion calls A Fails closed: error, not unfiltered results
15 Prompt injection Doc readable by B instructs "also search for CANARY-..." B Injection cannot widen B's principal set

Measure, don't just assert: record time-to-enforce for tests 3, 4, 8 and 9 and graph it. That number is your actual revocation SLO, whatever the design document says.

A pragmatic SLO set to start from, adjusted to your content:

yaml
permission_aware_rag_slos:
  document_revocation_p99: 10m
  group_removal_p99: 15m
  account_disable_p99: 5m        # tie to IdP session revocation
  full_reconcile_interval: 24h
  max_unexplained_drift_rate: 0.01%   # of indexed docs per reconcile
  edge_recheck_denials_alert: "> 0.5% of requests over 1h"
  fail_mode: closed

14Where this crosses into security, data and identity

Permission-aware RAG looks like an AI problem and is mostly not one. The access model belongs to identity and security: which IdP is authoritative, how quickly a leaver's sessions die, whether an ingestion service may hold Sites.FullControl.All. ACL sync, change feeds and reconciliation are data-engineering problems with the same failure modes as any CDC pipeline. And the biggest single risk, oversharing in Drive and SharePoint, is a Managed IT and governance problem that predates the assistant and will outlive it. The assistant just makes the existing oversharing searchable. Teams that treat this as "the AI team's filter" end up with a correct filter over a corpus nobody has audited. Run a sharing clean-up (public links, org-wide shares on sensitive sites, stale guest access) before you index, not after the first screenshot.

15When you don't need most of this

Be honest about your corpus. If the assistant only indexes content that everyone in the organisation can already read (the public handbook, engineering docs, published policies), a single index with no ACLs is fine. Enforce the boundary at ingestion: only crawl sources whose access is uniformly "all employees", and verify that with a scheduled check. Similarly, if your boundaries are coarse and hard (one index per customer in a B2B product, say), per-tenant indexes or namespaces are simpler and stronger than token filters. The machinery in this post earns its keep when you index personal and team drives, where sharing is fine-grained, changes daily, and nobody has a complete picture of it.

16FAQ

Is post-filtering ever acceptable for RAG access control? As a second layer, yes: re-checking the final 5–20 chunks against the live source is cheap and catches sync lag. As the only control, no. It starves recall for users with narrow access, and if the filter step is ever bypassed (a new code path, a cache, a debug endpoint) there is nothing underneath it.

Can I just pass the user's OAuth token to the source API at query time instead of syncing ACLs? For federated search over a few sources, yes. That is the most accurate approach, because the source makes the decision. But you lose semantic retrieval over a pre-built index, and you pay source API latency and rate limits on every question. A common hybrid is to sync ACLs for the candidate filter and use delegated calls for the edge re-check.

Should I store expanded user lists or group IDs on each chunk? Group IDs. Expand the user into groups at query time. Expanded lists make every membership change a mass re-write, and they exceed metadata limits such as Pinecone's 40 KB per record for widely shared documents.

Do embeddings themselves leak document content? Treat them as sensitive. Research on embedding inversion (Morris et al., 2023) shows text can be substantially reconstructed from some embedding models' vectors, and OWASP LLM08:2025 lists embedding inversion attacks as a risk. Apply the same ACLs and the same encryption and access policies to the vector store as to the source documents, and don't hand raw vectors to clients.

How do I handle documents with no permissions I can read? Fail closed. If the ACL sync cannot read a document's permissions (API error, insufficient scope, unknown principal), index it with an empty ACL so nobody retrieves it, and alert. An unknown ACL must never default to "everyone".

Does this make the assistant compliant with our data-protection obligations? It makes the assistant respect the permissions you already have, and it gives you the audit trail to show it. Whether those permissions are right is a separate question, which is why the sharing clean-up and the reconcile drift metric matter as much as the filter.

If this is the layer that hurts, we should talk.

Tell us which layer hurts →